问:
Unable to load to Bigquery from GCS using python. Client has no attribute issue
I am trying to load a file from Google Cloud Storage to Google BigQuery and I am running into some issues:

This is the code I used (directly copied from here):

答:
You probably are not using version 0.28, you can check it by running:

```<code>pip freeze | grep google-cloud-core
</code>```

This is the code you probably are looking for (version 0.27):

```<code>def load_data_from_gcs(dataset_name, table_name, source):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, source)

    job.begin()
    job.result()  # Wait for job to complete

    print('Loaded {} rows into {}:{}.'.format(
        job.output_rows, dataset_name, table_name))
</code>```

You can also run pip install --upgrade google-cloud-bigquery to updated your client but remember before running this that the latest version is backwards incompatible so it can break your whole code.

Body:
You probably are not using version 0.28, you can check it by running:

pip freeze | grep google-cloud-core

This is the code you probably are looking for (version 0.27):

def load_data_from_gcs(dataset_name, table_name, source):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, source)

    job.begin()
    job.result()  # Wait for job to complete

    print('Loaded {} rows into {}:{}.'.format(
        job.output_rows, dataset_name, table_name))

You can also run pip install --upgrade google-cloud-bigquery to updated your client but remember before running this that the latest version is backwards incompatible so it can break your whole code.


来源: stackexchange

问:
Efficient Numpy slicing on 3d array
I am trying to find the most efficient way to do slicing for a 3D numpy array. This is a subset of the data, just for test purposes :

```<code>in_arr =np.array([[[0,1,2,5],[2,3,2,6],[0,1,3,2]],[[1,2,3,4],[3,1,0,5],[2,4,0,1]]])
indx =[[3,1,2],[2,0,1]]
</code>```

I need to get the value at the indx as stated. For example, indx[0][0] is 3, so I am looking for the 3rd elem of in_arr[0][0], in this case, 5.

I have the following code that will do what i need it to do, but the time complexeity is n^2, which I am not happy about.

```<code>list_in =[]
for x in range(len(indx)):
    arr2 = []
    for y in range(len(indx[x])):
        arr2.append(in_arr[x][y][indx[x][y]])
        #print in_arr[x][y][indx[x][y]]
    list_in.append(arr2)
print list_in
</code>```

I am looking for a very fast and efficient way to do the same task for a large dataset.

答:
You can do this efficiently using broadcasted arrays of indices; for example:

```<code>i1 = np.arange(2)[:, np.newaxis]
i2 = np.arange(3)[np.newaxis, :]
i3 = np.array(indx)
in_arr[i1, i2, i3]
# array([[5, 3, 3],
#        [3, 3, 4]])
</code>```

What numpy does here is to effectively match the entries of the three index arrays, and extract the associated entries from in_arr: the reason for the [:, np.newaxis] and [np.newaxis, :] terms is that it reshapes the three arrays to be compatible via numpy's broadcasting rules.

ContentLicense: CC BY-SA 3.0

Title: Efficient Numpy slicing on 3d array

Body:
I am trying to find the most efficient way to do slicing for a 3D numpy array. This is a subset of the data, just for test purposes :

in_arr =np.array([[[0,1,2,5],[2,3,2,6],[0,1,3,2]],[[1,2,3,4],[3,1,0,5],[2,4,0,1]]])
indx =[[3,1,2],[2,0,1]]

I need to get the value at the indx as stated. For example, indx[0][0] is 3, so I am looking for the 3rd elem of in_arr[0][0], in this case, 5.

I have the following code that will do what i need it to do, but the time complexeity is n^2, which I am not happy about.

list_in =[]
for x in range(len(indx)):
    arr2 = []
    for y in range(len(indx[x])):
        arr2.append(in_arr[x][y][indx[x][y]])
        #print in_arr[x][y][indx[x][y]]
    list_in.append(arr2)
print list_in

I am looking for a very fast and efficient way to do the same task for a large dataset.

Body:
You can do this efficiently using broadcasted arrays of indices; for example:

i1 = np.arange(2)[:, np.newaxis]
i2 = np.arange(3)[np.newaxis, :]
i3 = np.array(indx)
in_arr[i1, i2, i3]
# array([[5, 3, 3],
#        [3, 3, 4]])

What numpy does here is to effectively match the entries of the three index arrays, and extract the associated entries from in_arr: the reason for the [:, np.newaxis] and [np.newaxis, :] terms is that it reshapes the three arrays to be compatible via numpy's broadcasting rules.


问:
difference between input:disabled and input[disabled] CSS selector
I'm wondering is there any difference between using the :disabled CSS pseudo-class selector and the [disabled] CSS attribute selector (e.g. different browsers support or whatever) to apply styles on a disabled HTML input element or are they totally equivalent?

答:
The :disabled approach is supported by browsers that support CSS3, while [disabled] is supported by browsers supporting CSS2 onward.

Browser support is very similar for both; the major difference being IE7 backward vs IE9 backward compatibility.

Likewise, the [disabled] approach is supported by native browsers in older mobile OS versions.

For more details, refer to:

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled


问:
Date range picker in non-military format
I am working on a project that requires the daterange picker to be in non-military format, while still enforcing a min date. The current set up works although the daterange picker is in military format, despite setting timePicker24Hour: false, - I need the picker to be in non-military format. Any idea why this is and how to accomplish this?

```<code>$('input[name="launchdate"]').daterangepicker({
                                    timePicker24Hour: false,
                                    timePickerIncrement: 15,
                                    singleDatePicker: true,
                                    showDropdowns: true,
                                    timePicker: true,
                                    autoApply: true,
                                    minDate: moment().hour(13).minutes(0),
                                    format: 'hh:mm A',
                                    locale: {
                                        format: "MM/DD/YYYY hh:mm A"
                                    }
                                });
</code>```

答:
Your code is working fine!

Here is a short snippet which gives you non-military time format with  (12h) am/pm.

var minDateValue = moment().add(13, 'hours');
$('input[name="launchdate"]').daterangepicker({
    timePicker24Hour: false,
    timePickerIncrement: 15,
    singleDatePicker: true,
    showDropdowns: true,
    timePicker: true,
    autoApply: true,
    minDate: minDateValue,
    format: 'hh:mm A',
    locale: {
        format: "MM/DD/YYYY hh:mm A"
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />

<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<!-- Input -->
<input name="launchdate"/></code>```

If you want to get military time format (24h):

Remove the A in your format options and set timePicker24Hour to true.

EDIT: added moment().add(13, 'hours') as minDate value.

Body:
I am working on a project that requires the daterange picker to be in non-military format, while still enforcing a min date. The current set up works although the daterange picker is in military format, despite setting timePicker24Hour: false, - I need the picker to be in non-military format. Any idea why this is and how to accomplish this?

$('input[name="launchdate"]').daterangepicker({
                                    timePicker24Hour: false,
                                    timePickerIncrement: 15,
                                    singleDatePicker: true,
                                    showDropdowns: true,
                                    timePicker: true,
                                    autoApply: true,
                                    minDate: moment().hour(13).minutes(0),
                                    format: 'hh:mm A',
                                    locale: {
                                        format: "MM/DD/YYYY hh:mm A"
                                    }
                                });

Body:
Your code is working fine!

Here is a short snippet which gives you non-military time format with  (12h) am/pm.

var minDateValue = moment().add(13, 'hours');
$('input[name="launchdate"]').daterangepicker({
    timePicker24Hour: false,
    timePickerIncrement: 15,
    singleDatePicker: true,
    showDropdowns: true,
    timePicker: true,
    autoApply: true,
    minDate: minDateValue,
    format: 'hh:mm A',
    locale: {
        format: "MM/DD/YYYY hh:mm A"
    }
});

<!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />

<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<!-- Input -->
<input name="launchdate"/>

If you want to get military time format (24h):

Remove the A in your format options and set timePicker24Hour to true.

EDIT: added moment().add(13, 'hours') as minDate value.


问:
Web API appears to be adding time zone offset to DateTime data
I have a legacy ASP.NET WebForms application that collects a date value in a textbox and since we don't explicitly specify a time it defaults to midnight. For example, if we enter today's date, the DateTime value is 12/08/2017 00:00:00.

I send the data to our WebApi and when I debug the controller and inspect the incoming data, that value will be read as 12/08/2017 07:00:00. Our local time zone is UTC-7:00. However, the client application passes the value 12/08/2017 00:00:00 right before sending it over. Something is performing a shift on the time and it appears to be compensating for the time zone.

Clearly I don't want this. I shouldn't have to add code in the API to shave off any time value in my DateTime data. What can be done about this? I've never seen this behavior before.

Here's the code that sends the data to the API:

```<code>public static void Update(Newsletter newsletter)
{
    if (newsletter == null)
      throw new ArgumentNullException(nameof(newsletter));

    using (var client = WebApiUtils.GetConfiguredClient())
    {
        var uriString = $"Newsletters/{newsletter.ID}";
        var requestUri = new Uri(uriString, UriKind.Relative);

        using (var content = GenerateStringContent(newsletter))
        {
            using (var response = client.PutAsync(requestUri, content).Result)
            {
                response.EnsureSuccessStatusCode();
            }
        }
    }
}

public static HttpClient GetConfiguredClient()
{
    var uriString = GetWebApiUri(); // Read from web.config
    var client = new HttpClient { BaseAddress = uriString };

    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonMediaType));

    return client;
}

public static StringContent GenerateStringContent(object data)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(data);
    var content = new StringContent(json, Encoding.UTF8, JsonMediaType);

    return content;
}
</code>```

My guess is that the serialization is doing the time zone shift but I don't know how to correct it if that's the case.

答:
If you want to treat all incoming / outgoing DateTime instances as Utc by default in your Web API application then you can add this to your WebApiConfig.cs file.

```<code>public static class WebApiConfig {
  public static void Register(HttpConfiguration config) {
    // other code unchanged
    config.SetTimeZoneInfo(TimeZoneInfo.Utc);
  }
}
</code>```

Body:
I have a legacy ASP.NET WebForms application that collects a date value in a textbox and since we don't explicitly specify a time it defaults to midnight. For example, if we enter today's date, the DateTime value is 12/08/2017 00:00:00.

I send the data to our WebApi and when I debug the controller and inspect the incoming data, that value will be read as 12/08/2017 07:00:00. Our local time zone is UTC-7:00. However, the client application passes the value 12/08/2017 00:00:00 right before sending it over. Something is performing a shift on the time and it appears to be compensating for the time zone.

Clearly I don't want this. I shouldn't have to add code in the API to shave off any time value in my DateTime data. What can be done about this? I've never seen this behavior before.

Here's the code that sends the data to the API:

public static void Update(Newsletter newsletter)
{
    if (newsletter == null)
      throw new ArgumentNullException(nameof(newsletter));

    using (var client = WebApiUtils.GetConfiguredClient())
    {
        var uriString = $"Newsletters/{newsletter.ID}";
        var requestUri = new Uri(uriString, UriKind.Relative);

        using (var content = GenerateStringContent(newsletter))
        {
            using (var response = client.PutAsync(requestUri, content).Result)
            {
                response.EnsureSuccessStatusCode();
            }
        }
    }
}

public static HttpClient GetConfiguredClient()
{
    var uriString = GetWebApiUri(); // Read from web.config
    var client = new HttpClient { BaseAddress = uriString };

    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonMediaType));

    return client;
}

public static StringContent GenerateStringContent(object data)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(data);
    var content = new StringContent(json, Encoding.UTF8, JsonMediaType);

    return content;
}

My guess is that the serialization is doing the time zone shift but I don't know how to correct it if that's the case.

Body:
If you want to treat all incoming / outgoing DateTime instances as Utc by default in your Web API application then you can add this to your WebApiConfig.cs file.

public static class WebApiConfig {
  public static void Register(HttpConfiguration config) {
    // other code unchanged
    config.SetTimeZoneInfo(TimeZoneInfo.Utc);
  }
}


问:
Pointer to a class method in c++
A have a lot of B classes, a class A has one object b. This object b has a function (calc) that needs a pointer to a method in an object of A. This method (fun) acess private variables in class (in my example just return 3).

```<code>class A;

class B {
public:
  virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run(){ return b->calc(&A::fun); };
};

int main() {
  B* b = new B();
  A a(b);
  a.run();
  return 0;
}
</code>```

How can I use a pointer to a method correctly in definition of calc method in class B?

I am getting this error message:

```<code>teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member     function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
   virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
                                                      ^
</code>```

答:
If you are able to use C++11, then you should use std::function and std::bind: Otherwise you need to use a pointer to member function + a pointer to the instance.

With C++11

```<code>#include <functional>

class B {
public:
  virtual int calc (std::function<int()>&& fun) { return 2 * fun();  }; };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run() { return b->calc(std::bind(&A::fun, this)); };
};
</code>```

Without C++11

```<code>class B {
public:
  virtual int calc (int(A::*fnptr)(), A* a) { return 2 * (a->*fnptr)(); };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run() { return b->calc(&A::fun, this); };
};
</code>```

See example here.

Title: Pointer to a class method in c++

Body:
A have a lot of B classes, a class A has one object b. This object b has a function (calc) that needs a pointer to a method in an object of A. This method (fun) acess private variables in class (in my example just return 3).

class A;

class B {
public:
  virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run(){ return b->calc(&A::fun); };
};

int main() {
  B* b = new B();
  A a(b);
  a.run();
  return 0;
}

How can I use a pointer to a method correctly in definition of calc method in class B?

I am getting this error message:

teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member     function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
   virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
                                                      ^

Body:
If you are able to use C++11, then you should use std::function and std::bind: Otherwise you need to use a pointer to member function + a pointer to the instance.

With C++11

#include <functional>

class B {
public:
  virtual int calc (std::function<int()>&& fun) { return 2 * fun();  }; };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run() { return b->calc(std::bind(&A::fun, this)); };
};

Without C++11

class B {
public:
  virtual int calc (int(A::*fnptr)(), A* a) { return 2 * (a->*fnptr)(); };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run() { return b->calc(&A::fun, this); };
};

See example here.


问:
lxml.etree, element.text doesn't return the entire text from an element
I scrapped some html via xpath, that I then converted into an etree.  Something similar to this:

```<code><td> text1 <a> link </a> text2 </td>
</code>```

but when I call element.text, I only get text1 (It must be there, when I check my query in FireBug, the text of the  elements is highlighted, both the text before and after the embedded anchor elements...

答: Use element.xpath("string()") or lxml.etree.tostring(element, method="text") - see the documentation.

Body:
I scrapped some html via xpath, that I then converted into an etree.  Something similar to this:

 text1  link  text2

but when I call element.text, I only get text1 (It must be there, when I check my query in FireBug, the text of the  elements is highlighted, both the text before and after the embedded anchor elements...


问:
sap.m.PlanningCalendarView Headers
I would like to show (dates/days) in headers when implementing sap.m.

PlanningCalendarViews with Month as Interval Type like here with full months: https://experience.sap.com/fiori-design-web/wpcontent/uploads/sites/5/2016/11/Switching_Row_Header1-1100x512.png

Codepen (https://codepen.io/Coopyrightdmin/pen/bYPORX?editors=1111):

```<code><PlanningCalendar id="Calendar" viewKey="D"
        rows="{path: '/people'}"
        appointmentsVisualization="Filled"
        showEmptyIntervalHeaders="false">
        <views>
                <PlanningCalendarView
                    key="D"
                    id="CalendarView"
                    intervalType="Month"
                    intervalsS="1"
                    intervalsM="1"
                    intervalsL="1"
                    showSubIntervals="true">
                </PlanningCalendarView>
        </views>
    ...
</code>```

Should I extend the control or is this technically possible in standard?

答:
Since 1.50, we just need to call method setBuiltInViews("One Month")
codepen has been updated.</p>

Title: sap.m.PlanningCalendarView Headers

Body:
I would like to show (dates/days) in headers when implementing sap.m.

PlanningCalendarViews with Month as Interval Type like here with full months: https://experience.sap.com/fiori-design-web/wpcontent/uploads/sites/5/2016/11/Switching_Row_Header1-1100x512.png

Codepen (https://codepen.io/Coopyrightdmin/pen/bYPORX?editors=1111):

<PlanningCalendar id="Calendar" viewKey="D"
        rows="{path: '/people'}"
        appointmentsVisualization="Filled"
        showEmptyIntervalHeaders="false">
        <views>
                <PlanningCalendarView
                    key="D"
                    id="CalendarView"
                    intervalType="Month"
                    intervalsS="1"
                    intervalsM="1"
                    intervalsL="1"
                    showSubIntervals="true">
                </PlanningCalendarView>
        </views>
    ...

Should I extend the control or is this technically possible in standard?


问:
AMP and code blocks
I have a web about programming and it has some articles with code blocks. Now Google Webmaster tools reports me that I have some issues with my AMP implementation.

I have searched a bit and I think that the problem is the usage of code blocks like this:

```<code><pre lang="c">
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
...
```
```

AMP tools analyze this code and report me some issues, for example:

The tag "stdio.h" isn't allowed

The tag "stdlib.h" isn't allowed

I have read the AMP documentation and I haven't found any solution, so do you know how to fix it?

PD: Post the code as image isn't a valid solution for mine.

答:
In the case that you are using PHP, the function htmlentities scapes all special characters to avoid issues.

The required translations are (&,",',<,>)

Title: AMP and code blocks

Body:
I have a web about programming and it has some articles with code blocks. Now Google Webmaster tools reports me that I have some issues with my AMP implementation.

I have searched a bit and I think that the problem is the usage of code blocks like this:

#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
...

AMP tools analyze this code and report me some issues, for example:

The tag "stdio.h" isn't allowed

The tag "stdlib.h" isn't allowed

I have read the AMP documentation and I haven't found any solution, so do you know how to fix it?

PD: Post the code as image isn't a valid solution for mine.


问:
How can i call another activity from a GridView?
i have gridview in my app. and i have 6 items in it. i want call another actvity when click item. how can i do it? here is my code. help me pls.
now when i click item i can show message with toast. but i want run another activity help me pls.</p>

```<code>public class GridViewImageTextActivity extends AppCompatActivity {

    GridView androidGridView;

    String[] gridViewString = {
            "Hesapla", "Geçmiş", "Paylaş", "Geribildirim", "Sıralama", "Beğen",

    } ;
    int[] gridViewImageId = {
            R.drawable.hesap, R.drawable.gecmis, R.drawable.paylas, R.drawable.geribildirim, R.drawable.siralama, R.drawable.begen

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_view_image_text);

        CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(GridViewImageTextActivity.this, gridViewString, gridViewImageId);
        androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
        androidGridView.setAdapter(adapterViewAndroid);
        androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int i, long id) {
                Toast.makeText(GridViewImageTextActivity.this, "GridView Item: " + gridViewString[+i], Toast.LENGTH_LONG).show();
            }
        });

    }
}
</code>```

答:
First Create 6 Activities and their layouts for each activity.

Assign ids to each 6 items like button1,button2,button3 and so on

Replace Toast message line this Switch Case Statement

Here is sample code for first 3 items

```<code>swithc(View v){case R.id.button1:startActivity(new Intent(GridViewImageTextActivity.this,ActivityB.clsss));break;case R.id.button2:startActivity(new Intent(GridViewImageTextActivity.this,ActivityC.clsss));break;case R.id.button3:startActivity(new Intent(GridViewImageTextActivity.this,ActivityD.clsss));break;}
</code>```

Body:
i have gridview in my app. and i have 6 items in it. i want call another actvity when click item. how can i do it? here is my code. help me pls.
now when i click item i can show message with toast. but i want run another activity help me pls.

public class GridViewImageTextActivity extends AppCompatActivity {

    GridView androidGridView;

    String[] gridViewString = {
            "Hesapla", "Geçmiş", "Paylaş", "Geribildirim", "Sıralama", "Beğen",

    } ;
    int[] gridViewImageId = {
            R.drawable.hesap, R.drawable.gecmis, R.drawable.paylas, R.drawable.geribildirim, R.drawable.siralama, R.drawable.begen

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_view_image_text);

        CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(GridViewImageTextActivity.this, gridViewString, gridViewImageId);
        androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
        androidGridView.setAdapter(adapterViewAndroid);
        androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int i, long id) {
                Toast.makeText(GridViewImageTextActivity.this, "GridView Item: " + gridViewString[+i], Toast.LENGTH_LONG).show();
            }
        });

    }
}

Body:
First Create 6 Activities and their layouts for each activity.

Assign ids to each 6 items like button1,button2,button3 and so on

Replace Toast message line this Switch Case Statement

Here is sample code for first 3 items

swithc(View v){case R.id.button1:startActivity(new Intent(GridViewImageTextActivity.this,ActivityB.clsss));break;case R.id.button2:startActivity(new Intent(GridViewImageTextActivity.this,ActivityC.clsss));break;case R.id.button3:startActivity(new Intent(GridViewImageTextActivity.this,ActivityD.clsss));break;}


问:
Wrapping sub-menu items with div - WordPress
In WordPress I am trying to wrap  around the items that are in my sub menu list . I've written the HTML as I want it to appear, but how do I put this into wp_nav_menu()?</p>

```<code><ul class="menu">
  <li class="has_children"><a>Games</a>
    <ul class="sub-menu">
      <div class="column"> <!-- this line needs adding -->
        <li>
          <h4>Games</h4>
          <ul>
            <li><a href="#">Game 1</a></li>
            <li><a href="#">Game 2</a></li>
          </ul>
        </li>
    </ul>
  </li>
</ul>
</code>```

答:
Make a function

```<code>class Walker_Nav_Pointers extends Walker_Nav_Menu
{
    function start_lvl( &$output, $depth = 0, $args = array() )
    {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class=\"sub-menu\">\n";
        $output .= "\n<div class=\"column\">\n";
    }
    function end_lvl( &$output, $depth = 0, $args = array() )
    {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul>\n".($depth ? "$indent</div>\n" : "");
    }
}
</code>```

Wherever you're calling your nav menu, add this to the existing
arguments:

```<code><?php
 $navArgs = array('walker' => new Walker_Nav_Pointers());
 wp_nav_menu($navArgs);
?>
</code>```

Body:
In WordPress I am trying to wrap  around the items that are in my sub menu list . I've written the HTML as I want it to appear, but how do I put this into wp_nav_menu()?

Games

Games

Game 1

Game 2

Body:
Make a function

class Walker_Nav_Pointers extends Walker_Nav_Menu
{
    function start_lvl( &$output, $depth = 0, $args = array() )
    {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class=\"sub-menu\">\n";
        $output .= "\n<div class=\"column\">\n";
    }
    function end_lvl( &$output, $depth = 0, $args = array() )
    {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul>\n".($depth ? "$indent</div>\n" : "");
    }
}

Wherever you're calling your nav menu, add this to the existing
arguments:

<?php
 $navArgs = array('walker' => new Walker_Nav_Pointers());
 wp_nav_menu($navArgs);
?>


问:
Horizontal scroll inside WP7 pivot page
I'm having problems with horizontal scrolling inside Pivot control in WP7. I have a Grid with ScrollViewer and ten or more buttons inside. Since all buttons don't fit on the screen i need to be able to horizontally scroll. But when i click and drag on buttons the whole Pivot page starts moving and eventually switches to next pivot page. (buttons inside ScrollView also scroll but only for short distance)

Can I somehow disable Pivot page switching when I click inside ScrollView?

答:
Solution: http://blogs.msdn.com/b/luc/archive/2010/11/22/preventing-the-pivot-or-panorama-controls-from-scrolling.aspx?wa=wsignin1.0

I use this for Slider in Pivot and Pivot in Pivot

ContentLicense: CC BY-SA 2.5

Title: Horizontal scroll inside WP7 pivot page


答:
A pointer-to-class method is defined and initialized as (assuming SomeFn matches the signature):

```<code>RetType (ClassName::*pfn)(Args) = &ClassName::SomeFn;
</code>```

And is called as:

```<code>ClassName * ptr = GetClassPtr();
(ptr->*pfn)(arg, arg);
</code>```

Title: Pointer to a class method in c++

Body:
A pointer-to-class method is defined and initialized as (assuming SomeFn matches the signature):

RetType (ClassName::*pfn)(Args) = &ClassName::SomeFn;

And is called as:

ClassName * ptr = GetClassPtr();
(ptr->*pfn)(arg, arg);


问:
Jackson JSon : Can not deserialize instance of java.lang.String out of START_OBJECT token
I'm using an API and I'm trying to deserialize  the results with Jackson but I always have the same mistake.

I guess my POJO is not right but I can't find what's wrong.

The mistake is on libs

I've tried to declare as String or as List without any success. Any idea ?

```<code>{
"libs": {},
"items": [
    {
        "id": "001",
        "cars": [
            "cd1042af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    },
    {

        "id": "002",
        "cars": [
            "cd1043af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    }]
</code>```

}

```<code>public class Page<Car> {

    private List<String> libs;

    private List<Car>items;

    public List<Car> getItems() {
        return items;
    }

    public void setItems(List<Car> items) {
        this.items = items;
    }

    public List<String> getLibs() {
        return libs;
    }

    public void setLibs(List<String> libs) {
        this.libs = libs;
    }

}
</code>```

Body:
I'm using an API and I'm trying to deserialize  the results with Jackson but I always have the same mistake.

I guess my POJO is not right but I can't find what's wrong.

The mistake is on libs

I've tried to declare as String or as List without any success. Any idea ?

{
"libs": {},
"items": [
    {
        "id": "001",
        "cars": [
            "cd1042af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    },
    {

        "id": "002",
        "cars": [
            "cd1043af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    }]

}

public class Page<Car> {

    private List<String> libs;

    private List<Car>items;

    public List<Car> getItems() {
        return items;
    }

    public void setItems(List<Car> items) {
        this.items = items;
    }

    public List<String> getLibs() {
        return libs;
    }

    public void setLibs(List<String> libs) {
        this.libs = libs;
    }

}

Body:
Corrected json is as follows:

{
  "libs": [],
  "items": [
    {
      "id": "001",
      "cars": [
        "cd1042af-856d-4649-a170-032d15a4119b",
        "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
        "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
      ],
      "name": "James"
    },
    {
      "id": "002",
      "cars": [
        "cd1043af-856d-4649-a170-032d15a4119b",
        "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
        "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
      ],
      "name": "James"
    }
  ]
}


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答: Well, this is how I see your problem. The fact that you came from SQL, a 4GL (fourth generation language) which closer to human language than a 3GL such as C#, is like somebody use to drive airplane doesn’t get what’s a big deal to drive a car. You should either try to learn how to bike (a 2GL like assembly language) or try to drive a lower end car (such as Fortan or C ) to appreciate a language like C#.</p>

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

LastEditorDisplayName: Ten P.


问:
WPF inline x:Array on Binding
Is it possible to use inline arrays in XAML?

I'm trying to transform something like this:

```<code><Control>
    <Control.Property>
        <Binding Path="MyVariable" Converter="{StaticResource MyConverter}">
            <Binding.ConverterParameter>
                <x:Array Type="s:Boolean">
                    <s:Boolean>True</s:Boolean>
                    <s:Boolean>False</s:Boolean>
                </x:Array>
            </Binding.ConverterParameter>
        </Binding>
    </Control.Property>
</Control>
</code>```

Into something like this:

```<code><Control Property="{Binding MyVariable,
 Converter={StaticResource MyConverter},
 ConverterParameter={x:Array s:Boolean, Items=[]{ {s:Boolean True}; {s:Boolean False} }}}"
/>
</code>```

But Visual Studio shows me following error bellow "Property":

The TypeConverter for “IList” does not support converting from a string

OBS:

I don't know if thats the correct syntax for inline x:Array in XAML, I wrote that because its the only one that VS didn't whine about

Of course the example doesn't seem practical, it's just an easy way of showing what I'm looking for

答:
Is it possible to use inline arrays in XAML?

No. I am afraid there is no valid syntax for defining an array "inline" in XAML.

You could define it as reusable resource with an x:Key:

```<code><x:Array x:Key="array" Type="s:Boolean">
    <s:Boolean>True</s:Boolean>
    <s:Boolean>False</s:Boolean>
</x:Array>
</code>```

..and then reference it using the StaticResource markup extension.

```<code><Control Property="{Binding MyVariable,
         Converter={StaticResource MyConverter},
         ConverterParameter={StaticResource arr}}" />
</code>```

Or you could define a custom array class and define it as a resource:

```<code><local:MyCollectionType />
</code>```

You can for example populate the custom type with items in its constructor if you don't want to waste a few more lines in your XAML markup. But there is no built-in support for something like this:

```<code>Items=[]{ {s:Boolean True}; {s:Boolean False} }}}"
</code>```

Yet another approach would be to create a custom markup expression.

Title: WPF inline x:Array on Binding

Body:
Is it possible to use inline arrays in XAML?

I'm trying to transform something like this:

<Control>
    <Control.Property>
        <Binding Path="MyVariable" Converter="{StaticResource MyConverter}">
            <Binding.ConverterParameter>
                <x:Array Type="s:Boolean">
                    <s:Boolean>True</s:Boolean>
                    <s:Boolean>False</s:Boolean>
                </x:Array>
            </Binding.ConverterParameter>
        </Binding>
    </Control.Property>
</Control>

Into something like this:

<Control Property="{Binding MyVariable,
 Converter={StaticResource MyConverter},
 ConverterParameter={x:Array s:Boolean, Items=[]{ {s:Boolean True}; {s:Boolean False} }}}"
/>

But Visual Studio shows me following error bellow "Property":

The TypeConverter for “IList” does not support converting from a string

OBS:

I don't know if thats the correct syntax for inline x:Array in XAML, I wrote that because its the only one that VS didn't whine about

Of course the example doesn't seem practical, it's just an easy way of showing what I'm looking for

Body:
Is it possible to use inline arrays in XAML?

No. I am afraid there is no valid syntax for defining an array "inline" in XAML.

You could define it as reusable resource with an x:Key:

<x:Array x:Key="array" Type="s:Boolean">
    <s:Boolean>True</s:Boolean>
    <s:Boolean>False</s:Boolean>
</x:Array>

..and then reference it using the StaticResource markup extension.

<Control Property="{Binding MyVariable,
         Converter={StaticResource MyConverter},
         ConverterParameter={StaticResource arr}}" />

Or you could define a custom array class and define it as a resource:

<local:MyCollectionType />

You can for example populate the custom type with items in its constructor if you don't want to waste a few more lines in your XAML markup. But there is no built-in support for something like this:

Items=[]{ {s:Boolean True}; {s:Boolean False} }}}"

Yet another approach would be to create a custom markup expression.


问:
Using Invoke-SQL query with Foreach loop
I have a list of instances I have imported into the

$SQLServerList

I want to have them look for the databases on each instance.

```<code>foreach ($server in $SQLServerList ){
    Invoke-Sqlcmd -Query "use master select name, database_id, create_date, recovery_model_desc from sys.databases"  -ServerInstance $server
}
</code>```

however this won't run what am i doing wrong?

答:
Use the below it should make it easier to troubleshoot your error.. See if the count matches what you have in the CSV file. You can also list it out to view the content of the CSV.. plus changed the database in use from inside the script to the Parameter -Database. </p>

```<code>$inputfile = "C:\Databases\JUSTCREATED.csv"

[Array]$SQLServerList = get-content -Path $inputfile

$SQLServerList.count

foreach ($server in $SQLServerList ){

    Write-Output $server
    try{
    Invoke-Sqlcmd -Query " select name, database_id, create_date, recovery_model_desc from sys.databases"  -ServerInstance $server -Database master
        }
        catch
        {

        Write-Output $_.Exception.Message

        }

}
</code>```

Body:
I have a list of instances I have imported into the

$SQLServerList

I want to have them look for the databases on each instance.

foreach ($server in $SQLServerList ){
    Invoke-Sqlcmd -Query "use master select name, database_id, create_date, recovery_model_desc from sys.databases"  -ServerInstance $server
}

however this won't run what am i doing wrong?

Body:
Use the below it should make it easier to troubleshoot your error.. See if the count matches what you have in the CSV file. You can also list it out to view the content of the CSV.. plus changed the database in use from inside the script to the Parameter -Database.

$inputfile = "C:\Databases\JUSTCREATED.csv"

[Array]$SQLServerList = get-content -Path $inputfile

$SQLServerList.count

foreach ($server in $SQLServerList ){

    Write-Output $server
    try{
    Invoke-Sqlcmd -Query " select name, database_id, create_date, recovery_model_desc from sys.databases"  -ServerInstance $server -Database master
        }
        catch
        {

        Write-Output $_.Exception.Message

        }

}


问:
Netlogo- average link length code snippet
I'm trying to monitor the length of my links in Netlogo- but I'm having a hard time getting used to the syntax. Is anyone familiar enough with it to just take the mean of all link-lengths?

Thanks.

答:
Using this simple setup:

```<code>to setup
  ca
  crt 10 [
    setxy random-pxcor random-pycor
  ]
  ask turtles [
    if not any? my-links [
      create-link-with one-of other turtles
    ]
  ]
  reset-ticks
end
</code>```

You can use of with [link-length] to return a list of link lengths (try just typing print [link-length] of links in the console), then use mean to take the mean of that list. If you put that in a to-report procedure, you will be able to display the mean-link-length in a "monitor" widget in the "Interface":

```<code>to-report mean-link-length
  report mean [link-length] of links
end
</code>```

Body:
Using this simple setup:

to setup
  ca
  crt 10 [
    setxy random-pxcor random-pycor
  ]
  ask turtles [
    if not any? my-links [
      create-link-with one-of other turtles
    ]
  ]
  reset-ticks
end

You can use of with [link-length] to return a list of link lengths (try just typing print [link-length] of links in the console), then use mean to take the mean of that list. If you put that in a to-report procedure, you will be able to display the mean-link-length in a "monitor" widget in the "Interface":

to-report mean-link-length
  report mean [link-length] of links
end


问:
Adding Query String Params to my Swagger Specs
I am using Swashbuckle (swagger for C#) with my Web API.  I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString

Example: http://myapi.com/endpoint/?page=5&perpage=10

I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?

I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed.  Below is the code for my solution:

```<code>[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
    public SwaggerParameterAttribute(string name, string description)
    {
        Name = name;
        Description = description;
    }

    public string Name { get; private set; }
    public Type DataType { get; set; }
    public string ParameterType { get; set; }
    public string Description { get; private set; }
    public bool Required { get; set; } = false;
}
</code>```

Register the Attribute with the Swagger Config:

```<code>GlobalConfiguration.Configuration
    .EnableSwagger(c =>
        {
            c.OperationFilter<SwaggerParametersAttributeHandler>();
        });
</code>```

Then add this attribute to your methods:

```<code>[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
</code>```

答:
There's some comments here regarding missing information on the SwaggerParametersAttributeHandler. It is an operation filter to help you determine what to do to your attributes.

Here's an example handler I used that allows me to override nullable parameters' required fields using the SwaggerParameterAttribute.

```<code>public class RequiredParameterOverrideOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        // Get all SwaggerParameterAttributes on the method
        var attributes = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerParameterAttribute>();

        if (operation.parameters == null)
        {
            operation.parameters = new List<Parameter>();
        }

        // For each attribute found, find the operation parameter (this is where Swagger looks to generate the Swagger doc)
        // Override the required fields based on the attribute's required field
        foreach (var attribute in attributes)
        {
            var referencingOperationParameter = operation.parameters.FirstOrDefault(p => p.name == attribute.Name);

            if (referencingOperationParameter != null)
            {
                referencingOperationParameter.required = attribute.Required;
            }
        }
    }
}
</code>```

Body:
I am using Swashbuckle (swagger for C#) with my Web API.  I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString

Example: http://myapi.com/endpoint/?page=5&perpage=10

I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?

I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed.  Below is the code for my solution:

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
    public SwaggerParameterAttribute(string name, string description)
    {
        Name = name;
        Description = description;
    }

    public string Name { get; private set; }
    public Type DataType { get; set; }
    public string ParameterType { get; set; }
    public string Description { get; private set; }
    public bool Required { get; set; } = false;
}

Register the Attribute with the Swagger Config:

GlobalConfiguration.Configuration
    .EnableSwagger(c =>
        {
            c.OperationFilter<SwaggerParametersAttributeHandler>();
        });

Then add this attribute to your methods:

[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]

Body:
There's some comments here regarding missing information on the SwaggerParametersAttributeHandler. It is an operation filter to help you determine what to do to your attributes.

Here's an example handler I used that allows me to override nullable parameters' required fields using the SwaggerParameterAttribute.

public class RequiredParameterOverrideOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        // Get all SwaggerParameterAttributes on the method
        var attributes = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerParameterAttribute>();

        if (operation.parameters == null)
        {
            operation.parameters = new List<Parameter>();
        }

        // For each attribute found, find the operation parameter (this is where Swagger looks to generate the Swagger doc)
        // Override the required fields based on the attribute's required field
        foreach (var attribute in attributes)
        {
            var referencingOperationParameter = operation.parameters.FirstOrDefault(p => p.name == attribute.Name);

            if (referencingOperationParameter != null)
            {
                referencingOperationParameter.required = attribute.Required;
            }
        }
    }
}


问:
Execute Process Task - Not working in SSIS Properly
I have a python code which reads a csv file, creates a table in sql and inserts records inside that table. The code works perfectly fine. The SSIS task takes around 2-3 minutes to run and its okay, because the code would require that much time, but it is not creating anything on the database.

This is my code,

```<code>#Import the required libraries
import pandas
import pyodbc
import os

#Set the Current Directory
path="C:/Users/MOLAP/Desktop/Data Warehouse Project/1. Datasets/Structured Data"
os.chdir(path)

#Establish connection with the server and the database
conn_str = (
    r'DRIVER={ODBC Driver 13 for SQL Server};'
    r'SERVER=MOLAP;'
    r'DATABASE=EnergyUsageEffects_Database;'
    r'Trusted_Connection=yes;'
)

cnxn = pyodbc.connect(conn_str)

cursor = cnxn.cursor()

#If a table is present - Truncate it else create the table
if cursor.tables(table='EnergyConsumption_Electrical', tableType='TABLE').fetchone():
    cursor.execute("Truncate table EnergyConsumption_Electrical")
    cnxn.commit()
else:
    cursor.execute("Create table EnergyConsumption_Electrical (CountryName nvarchar(255), Year nvarchar(255), Unit nvarchar(255), Indicator nvarchar(255), Product nvarchar(255), ConsumptionValue float) ")
    cnxn.commit()

#Read the CSV Inside the dataframe
df = pandas.read_csv("Electrical Energy Types.csv")

#Convert the dataframe into a list
ReqList = df.values.tolist()

#Loop through the list and Insert record after record inside the table
for i in range(len(ReqList)):
    Val1 = ReqList[i][0]
    Val2= ReqList[i][1]
    Val3= ReqList[i][2]
    Val4= ReqList[i][3]
    Val5= ReqList[i][4]
    Val6= ReqList[i][5]
    cursor.execute("insert into EnergyConsumption_Electrical (CountryName, Year, Unit, Indicator, Product, ConsumptionValue) values (?,?,?,?,?,?)", Val1, Val2, Val3, Val4, Val5, Val6)
    cnxn.commit()
</code>```

This is my configuration on the SSIS,

Where am I going wrong in this?

答:
Step 1) Remove this task from your package.

Step 2) Create a Data Flow that has a Flat File Source that points to your .csv and an OLE DB Destination task that points to your database.table.

There's really no reason to reinvent the wheel here. SSIS has native tools to make this task mostly trivial.

Body:
I have a python code which reads a csv file, creates a table in sql and inserts records inside that table. The code works perfectly fine. The SSIS task takes around 2-3 minutes to run and its okay, because the code would require that much time, but it is not creating anything on the database.

This is my code,

#Import the required libraries
import pandas
import pyodbc
import os

#Set the Current Directory
path="C:/Users/MOLAP/Desktop/Data Warehouse Project/1. Datasets/Structured Data"
os.chdir(path)

#Establish connection with the server and the database
conn_str = (
    r'DRIVER={ODBC Driver 13 for SQL Server};'
    r'SERVER=MOLAP;'
    r'DATABASE=EnergyUsageEffects_Database;'
    r'Trusted_Connection=yes;'
)

cnxn = pyodbc.connect(conn_str)

cursor = cnxn.cursor()

#If a table is present - Truncate it else create the table
if cursor.tables(table='EnergyConsumption_Electrical', tableType='TABLE').fetchone():
    cursor.execute("Truncate table EnergyConsumption_Electrical")
    cnxn.commit()
else:
    cursor.execute("Create table EnergyConsumption_Electrical (CountryName nvarchar(255), Year nvarchar(255), Unit nvarchar(255), Indicator nvarchar(255), Product nvarchar(255), ConsumptionValue float) ")
    cnxn.commit()

#Read the CSV Inside the dataframe
df = pandas.read_csv("Electrical Energy Types.csv")

#Convert the dataframe into a list
ReqList = df.values.tolist()

#Loop through the list and Insert record after record inside the table
for i in range(len(ReqList)):
    Val1 = ReqList[i][0]
    Val2= ReqList[i][1]
    Val3= ReqList[i][2]
    Val4= ReqList[i][3]
    Val5= ReqList[i][4]
    Val6= ReqList[i][5]
    cursor.execute("insert into EnergyConsumption_Electrical (CountryName, Year, Unit, Indicator, Product, ConsumptionValue) values (?,?,?,?,?,?)", Val1, Val2, Val3, Val4, Val5, Val6)
    cnxn.commit()

This is my configuration on the SSIS,

Where am I going wrong in this?


问:
Recursive tree template including ng-click with multidimensional index as parameter
Good evening,

Is there any way to create a template that recursively shows a structure and has an onclick function on every item. This onclick function needs the current index including all parent indexes of this element (for example [0][2][1] for BMW in the list below).

```<code>A [0]
  Tree [0][0]
    ...
  House [0][1]
    ...
  Car [0][2]
    Mercedes [0][2][0]
    BMW [0][2][1]
    Audi [0][2][2]
    VW [0][2][3]
    Chrysler [0][2][4]
B [1]
  ...
C [2]
  ...
</code>```

My current directives look like this but I have no idea how I cant get the FULL INDEX of every element for the ng-click function.

```<code>app.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: `
          <ul>
            <member ng-repeat='member in collection'
                    member='member' index='$parent.index + $index'>
            </member>
          </ul>`
    }
});

app.directive('member', function ($compile) {
    return {
        restrict: "E",
        replace: true,
        template: "<li ng-click=\"select(member)\">{{member.title}}</li>",
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.sub"></collection>';
            if (angular.isArray(scope.member.sub)) {
                $compile(collectionSt)(scope, function(cloned, scope) {
                    element.append(cloned);
                  });
            }
        }
    }
});
</code>```

答:
In the controller, add a fullIndex property to each member and return that property as an argument of the ng-click function:

```<code>template: `<li ng-click="select(member.fullIndex)">{{member.title}}</li>`,
</code>```

Having the template compute the fullIndex value with AngularJS expressions would make the app difficult to understand, debug, and maintain. It is better to do the computation in JavaScript.

Body:
Good evening,

Is there any way to create a template that recursively shows a structure and has an onclick function on every item. This onclick function needs the current index including all parent indexes of this element (for example [0][2][1] for BMW in the list below).

A [0]
  Tree [0][0]
    ...
  House [0][1]
    ...
  Car [0][2]
    Mercedes [0][2][0]
    BMW [0][2][1]
    Audi [0][2][2]
    VW [0][2][3]
    Chrysler [0][2][4]
B [1]
  ...
C [2]
  ...

My current directives look like this but I have no idea how I cant get the FULL INDEX of every element for the ng-click function.

app.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: `

            <member ng-repeat='member in collection'
                    member='member' index='$parent.index + $index'>
            </member>

`
    }
});

app.directive('member', function ($compile) {
    return {
        restrict: "E",
        replace: true,
        template: "
{{member.title}}
",
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.sub"></collection>';
            if (angular.isArray(scope.member.sub)) {
                $compile(collectionSt)(scope, function(cloned, scope) {
                    element.append(cloned);
                  });
            }
        }
    }
});

Body:
In the controller, add a fullIndex property to each member and return that property as an argument of the ng-click function:

template: `<li ng-click="select(member.fullIndex)">{{member.title}}</li>`,

Having the template compute the fullIndex value with AngularJS expressions would make the app difficult to understand, debug, and maintain. It is better to do the computation in JavaScript.


问:
XmlSchema assert the size with another element
I am trying to make an xmlSchema to validate my game maps.

I have a global element defined as following

```<code>    <xs:element name="size">
      <xs:complexType>
        <xs:sequence>
          <xs:element type="xs:byte" name="rowCount"/>
          <xs:element type="xs:byte" name="columnCount"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
</code>```

And I have to other elements which I want to have the same size as the ones defined in the global element.

So the min and max of the following elements to follow the size set in the global element. I'm using XSD 1.1 so I can use assert, but I don't know the syntax to correctly define the rule.

```<code><xs:element name="rows" minOccurs & maxOccurs=VALUE OF size.rowCount>

<xs:element name="tiles" minOccurs & maxOccurs=VALUE OF size.columnCount>
</code>```

Thanks

答:
You might write, for example

```<code><xs:assert test="every $table in descendant::table
                 satisfies count($table/row) = size/@rowCount"/>
</code>```

But the details depend on your exact structure.

The important thing is that the assertion belongs to the object that contains all the values involved in the condition - an assertion can't look outside the subtree of the element on which it is defined. And the XPath expressions are relative to that containing element. Also, remember to use namespace prefixes if the elements are in a namespace.

Body:
I am trying to make an xmlSchema to validate my game maps.

I have a global element defined as following

    <xs:element name="size">
      <xs:complexType>
        <xs:sequence>
          <xs:element type="xs:byte" name="rowCount"/>
          <xs:element type="xs:byte" name="columnCount"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>

And I have to other elements which I want to have the same size as the ones defined in the global element.

So the min and max of the following elements to follow the size set in the global element. I'm using XSD 1.1 so I can use assert, but I don't know the syntax to correctly define the rule.

<xs:element name="rows" minOccurs & maxOccurs=VALUE OF size.rowCount>

<xs:element name="tiles" minOccurs & maxOccurs=VALUE OF size.columnCount>

Thanks

Body:
You might write, for example

<xs:assert test="every $table in descendant::table
                 satisfies count($table/row) = size/@rowCount"/>

But the details depend on your exact structure.

The important thing is that the assertion belongs to the object that contains all the values involved in the condition - an assertion can't look outside the subtree of the element on which it is defined. And the XPath expressions are relative to that containing element. Also, remember to use namespace prefixes if the elements are in a namespace.


问:
Where is my mistake - Date calculator for selectbox in Javascript/jQuery?
```<code>$(.dateselboxes) .change( function(){

var y; y=$("#year").val();
var m; m=$("#month").val();
var d;
</code>```

// check leap year

```<code>var leapYear;
if(y%4==0)
{
    if(y%100==0)
    {
        if(y%400==0) {leapYear=true;}
        else {leapYear=false;}
    }
    else {leapYear=true;}
}
else {leapYear=false;}
</code>```

// calculate the number of days

```<code>var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
    {
        if(leapYear==true) {dz=29;}
        else {dz=28;}
    }
else {dz=30;}
</code>```

// remove last option a couple of times

```<code>switch(dz)
    {
        case 28:
            for(i=0;i<3;i++)
            {$("#day option:last").remove();}
            break;
        case 29:
            for(i=0;i<2;i++)
            {$("#day option:last").remove();}
            break;
        case 30:
            $("#day option:last").remove();
            break;
        default:
            var axaxax=0;
            break;
    }
</code>```

});

答:
Where you are calculating the number of days by checking the month #, you have single = instead of ==.
Replace with:

```<code>if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) {dz=31;}
</code>```

The single = will assign the new value to your m variable and always evaluate to be true, so I assume you were seeing 31 in your day selector always.  As a practice, I like to avoid this scenario by reversing the check.  ie: if(0 == x) since you can't assign to 0 an accidental single = will result in a javascript error, making it easier to avoid the mistake.

Body:
$(.dateselboxes) .change( function(){

var y; y=$("#year").val();
var m; m=$("#month").val();
var d;

// check leap year

var leapYear;
if(y%4==0)
{
    if(y%100==0)
    {
        if(y%400==0) {leapYear=true;}
        else {leapYear=false;}
    }
    else {leapYear=true;}
}
else {leapYear=false;}

// calculate the number of days

var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
    {
        if(leapYear==true) {dz=29;}
        else {dz=28;}
    }
else {dz=30;}

// remove last option a couple of times

switch(dz)
    {
        case 28:
            for(i=0;i<3;i++)
            {$("#day option:last").remove();}
            break;
        case 29:
            for(i=0;i<2;i++)
            {$("#day option:last").remove();}
            break;
        case 30:
            $("#day option:last").remove();
            break;
        default:
            var axaxax=0;
            break;
    }

});

Body:
Where you are calculating the number of days by checking the month #, you have single = instead of ==.
Replace with:

if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) {dz=31;}

The single = will assign the new value to your m variable and always evaluate to be true, so I assume you were seeing 31 in your day selector always.  As a practice, I like to avoid this scenario by reversing the check.  ie: if(0 == x) since you can't assign to 0 an accidental single = will result in a javascript error, making it easier to avoid the mistake.


问:
Why does auto seemingly deduce a reference when using structured bindings?
Consider the following code that uses structured bindings from C++17:

```<code>int a = 0, b = 0;
auto [x, y] = std::tie(a, b);
y = 1;
std::cout << a << ' ' << b << '\n';
</code>```

Since I used auto, I would expect the code to print 0 0 as y should be a copy. However, it prints 0 1. Why? I thought that a bare auto never deduces a reference.

答:
As cppreference notes, the portion of the declaration preceding [ (i.e. auto in your case) does not apply to the introduced identifiers. Instead, it applies to a hidden variable that is created by the compiler under the covers. Your structured-binding declaration

```<code>auto [x, y] = std::tie(a, b);
</code>```

is roughly equivalent to

```<code>auto e = std::tie(a, b);
decltype(std::get<0>(e)) x = std::get<0>(e);
decltype(std::get<1>(e)) y = std::get<1>(e);
</code>```

As you can see, auto is applied to the hidden variable e and not to the declaration of x and y. The type of e is std::tuple<int&, int&>, and decltype(std::get<1>(e)) gives you int&.

Body:
Consider the following code that uses structured bindings from C++17:

int a = 0, b = 0;
auto [x, y] = std::tie(a, b);
y = 1;
std::cout << a << ' ' << b << '\n';

Since I used auto, I would expect the code to print 0 0 as y should be a copy. However, it prints 0 1. Why? I thought that a bare auto never deduces a reference.

Body:
As cppreference notes, the portion of the declaration preceding [ (i.e. auto in your case) does not apply to the introduced identifiers. Instead, it applies to a hidden variable that is created by the compiler under the covers. Your structured-binding declaration

auto [x, y] = std::tie(a, b);

is roughly equivalent to

auto e = std::tie(a, b);
decltype(std::get<0>(e)) x = std::get<0>(e);
decltype(std::get<1>(e)) y = std::get<1>(e);

As you can see, auto is applied to the hidden variable e and not to the declaration of x and y. The type of e is std::tuple<int&, int&>, and decltype(std::get<1>(e)) gives you int&.


问:
How to recode and encode a country pair variable in R
I am trying to recode a variable for country pairs, e.g. an exporter EFG and an importeur ISR equals the country pair EFGISR. I need these pairs for a panel data analysis and therefore these country pairs have to be set to numeric variables. I am familiar to the as.numeric command, however recoding these variables back to the format seems to be a tough job. Do you guys know a better way to code it or a way to use the factor variable as a referene for a recode call ? I will have to use the plm package and the command make.pballanced().

Cheers and I would really appreciate your help!

edit:

```<code>idvar <- c(BRAWLD, BRAALB, BRADZA, BRAARG, BRAAUS, BRAAUT, BRABHR, BRAARM)

as.numeric(idvar)
[1] 108   2  30   5   7   8  12   6   9  15  11  17  23  19

as.factor(idvar)
[1] 108   2  30   5   7   8  12   6   9  15  11  17  23  19
</code>```

This is the part where I would like to have again

```<code>idvar
BRAWLD, BRAALB, BRADZA, BRAARG, BRAAUS, BRAAUT, BRABHR, BRAARM
</code>```

I am Heading my dataset here:

```<code>year    exp exp_iso                  imp imp_iso       nw       tv     nw_c nw_dc     tv_c tv_dc tv_total nw_total id_var
1996-BRAARE 1996 Brazil     BRA United Arab Emirates     ARE   563812  1245639   563812     0  1245639     0  1245639   563812 BRAARE
1996-BRAARG 1996 Brazil     BRA            Argentina     ARG 34006800 77508984 34006800     0 77508984     0 77508984 34006800 BRAARG
1996-BRAARM 1996 Brazil     BRA              Armenia     ARM    38398   70656    38398     0    70656     0    70656    38398 BRAARM
1996-BRAAUS 1996 Brazil     BRA            Australia     AUS  3213000  7864554  3213000     0  7864554     0  7864554  3213000 BRAAUS
1996-BRAAUT 1996 Brazil     BRA              Austria     AUT 11189578 25442560 11189578     0 25442560     0 25442560 11189578 BRAAUT
1996-BRABEL 1996 Brazil     BRA              Belgium     BEL 41944172 93179224 41944172     0 93179224     0 93179224 41944172 BRABEL
</code>```

答: I found an appealing solution to the problem. Using the package countryodes provides a formula with which I could paste the charachter country codes as numeric codes using the countrycode = "iso3n".</p>

Body:
I am trying to recode a variable for country pairs, e.g. an exporter EFG and an importeur ISR equals the country pair EFGISR. I need these pairs for a panel data analysis and therefore these country pairs have to be set to numeric variables. I am familiar to the as.numeric command, however recoding these variables back to the format seems to be a tough job. Do you guys know a better way to code it or a way to use the factor variable as a referene for a recode call ? I will have to use the plm package and the command make.pballanced().

Cheers and I would really appreciate your help!

edit:

idvar <- c(BRAWLD, BRAALB, BRADZA, BRAARG, BRAAUS, BRAAUT, BRABHR, BRAARM)

as.numeric(idvar)
[1] 108   2  30   5   7   8  12   6   9  15  11  17  23  19

as.factor(idvar)
[1] 108   2  30   5   7   8  12   6   9  15  11  17  23  19

This is the part where I would like to have again

idvar
BRAWLD, BRAALB, BRADZA, BRAARG, BRAAUS, BRAAUT, BRABHR, BRAARM

I am Heading my dataset here:

year    exp exp_iso                  imp imp_iso       nw       tv     nw_c nw_dc     tv_c tv_dc tv_total nw_total id_var
1996-BRAARE 1996 Brazil     BRA United Arab Emirates     ARE   563812  1245639   563812     0  1245639     0  1245639   563812 BRAARE
1996-BRAARG 1996 Brazil     BRA            Argentina     ARG 34006800 77508984 34006800     0 77508984     0 77508984 34006800 BRAARG
1996-BRAARM 1996 Brazil     BRA              Armenia     ARM    38398   70656    38398     0    70656     0    70656    38398 BRAARM
1996-BRAAUS 1996 Brazil     BRA            Australia     AUS  3213000  7864554  3213000     0  7864554     0  7864554  3213000 BRAAUS
1996-BRAAUT 1996 Brazil     BRA              Austria     AUT 11189578 25442560 11189578     0 25442560     0 25442560 11189578 BRAAUT
1996-BRABEL 1996 Brazil     BRA              Belgium     BEL 41944172 93179224 41944172     0 93179224     0 93179224 41944172 BRABEL


问:
Dynamic Breadcrumbs in ASP.NET
i have a problem concerning a breadcrumb navigation.
In my application i have a Start.aspx where i build a navigation menu for the next module (control1.ascx, control2.ascx, ...)  which should be loaded after clicking.
This ascx contains a grid with some data rows and link buttons to load other ascx on the start page
This is the common way the app works.

Now i need to visualize which ascx is loaded in the breadcrumb
Maybe we can viaualize it like this:

Start.aspx -> control1.ascx -> control1_1.ascx

Right now the app would be on the lowest level and if i click on "control1.ascx" this control should be loaded again or if i choose Start.aspx the "Home" should be loaded.

```<code>protected override void Render(HtmlTextWriter output)
    {

        NavigationDataTable moduleNameList = new NavigationDataTable();
        List<usp_GetNavigationElements_Result> ModuleList = moduleNameList.GetModulesList(1, LoggedInUser);
        StringBuilder sbResult1 = new StringBuilder();
        //string sbResult;

        if (Page.Items["title"] != null)
        {
            string id = Page.Items["title"].ToString();
            PageTitle = Page.Items["title"].ToString();
        }

        //------------------------------------------------------------------------------------------

        var request = HttpContext.Current.Request;
        System.Collections.Specialized.NameValueCollection coll;
        // Load ServerVariable collection into NameValueCollection object.
        coll = request.ServerVariables;
        string serverName = request.ServerVariables["SERVER_NAME"];

        //------------------------------------------------------------------------------------------

        string strDomain = "";
        if (serverName == "localhost")
        {
            //Lokal
            strDomain = "localhost:49573";
        }
        else
        {
            //Intranet
            strDomain = "i";
        }

        string strURL = "/Start.aspx";
        string strDirs = "control1.ascx";

        Separator3 = new Image();

        Separator3.Height = 52;
        Separator3.Width = 52;

        ArrowSeparator = new Image();
        ArrowSeparator.ImageUrl = "/img/mb_arrow_separator.png";

        HomeSymbol = new Image();
        HomeSymbol.ImageUrl = "/img/mb_home.png";

        // Home-Navigation for Start
        sbResult1.Append("<img src='" + HomeSymbol.ImageUrl + "'>");
        sbResult1.Append("<a href='http://" + strDomain + "/modules" + strURL + "'style='text-decoration:none;'>" + RootName + " " + "</a>");
        sbResult1.Append("<img src='" + ArrowSeparator.ImageUrl + "' hspace='10'>");

        //-------------------------------------------------------------------------------------------------------------------------------

        foreach (var item in ModuleList)
        {
            if (HttpContext.Current.Session["ModuleTitle"] != null)
            {
                if (item.ModuleTitle == HttpContext.Current.Session["ModuleTitle"].ToString() )
                {
                    //sbResult1.Append("<a href='http://" + strDomain + "/modules" + strURL + "?" + item.ModuleName + "'>" + item.ModuleTitle + "</a>" + Separator);

                    Separator3.ImageUrl = "/img/" + HttpContext.Current.Session["ModuleTitle"].ToString() + ".png";
                    sbResult1.Append("<img src='" + Separator3.ImageUrl + " 'hspace='10'>");
                    sbResult1.Append(HttpContext.Current.Session["ModuleTitle"]).ToString();
                }
            }
        }
        if (!ModuleList.Contains(HttpContext.Current.Session["ModuleTitle"]))
        {

            if (HttpContext.Current.Session["ModuleTitle"] != null)
            {
                if (HttpContext.Current.Session["ModuleTitle"].ToString().Contains("_"))//|| HttpContext.Current.Session["ModuleSubTitle"] != null)
                {
                    string[] std = HttpContext.Current.Session["ModuleTitle"].ToString().Split('_');

                    Separator3.ImageUrl = "/img/" + std[0] + ".png";
                    sbResult1.Append("<img src='" + Separator3.ImageUrl + "' hspace='10'>");
                    sbResult1.Append("<a href='http://" + strDomain + "/modules" + strURL + "?" + std[0] + "'style='text-decoration:none;'>" + std[0] + " " + "</a>");
                    sbResult1.Append("<img src='" + ArrowSeparator.ImageUrl + "' hspace='10'>");

                    sbResult1.Append("<img src='/img/Prozess.png' hspace='10'>");

                    sbResult1.Append(std[1]);

                }

            }
        }

        //-------------------------------------------------------------------------------------------------------------------------------

        output.Write(sbResult1.ToString());
    }
</code>```

Do i have to make this Breadcrumb.cs and override Render() or is there a better way.

Greets DarkGecko

答:
have you considered a SiteMapPath?

```<code><asp:SiteMapPath ID="SiteMapPath1" Runat="server"></asp:SiteMapPath>
</code>```

https://msdn.microsoft.com/en-us/library/x20z8c51.aspx

Title: Dynamic Breadcrumbs in ASP.NET

Body:
i have a problem concerning a breadcrumb navigation.
In my application i have a Start.aspx where i build a navigation menu for the next module (control1.ascx, control2.ascx, ...)  which should be loaded after clicking.
This ascx contains a grid with some data rows and link buttons to load other ascx on the start page
This is the common way the app works.

Now i need to visualize which ascx is loaded in the breadcrumb
Maybe we can viaualize it like this:

Start.aspx -> control1.ascx -> control1_1.ascx

Right now the app would be on the lowest level and if i click on "control1.ascx" this control should be loaded again or if i choose Start.aspx the "Home" should be loaded.

protected override void Render(HtmlTextWriter output)
    {

        NavigationDataTable moduleNameList = new NavigationDataTable();
        List<usp_GetNavigationElements_Result> ModuleList = moduleNameList.GetModulesList(1, LoggedInUser);
        StringBuilder sbResult1 = new StringBuilder();
        //string sbResult;

        if (Page.Items["title"] != null)
        {
            string id = Page.Items["title"].ToString();
            PageTitle = Page.Items["title"].ToString();
        }

        //------------------------------------------------------------------------------------------

        var request = HttpContext.Current.Request;
        System.Collections.Specialized.NameValueCollection coll;
        // Load ServerVariable collection into NameValueCollection object.
        coll = request.ServerVariables;
        string serverName = request.ServerVariables["SERVER_NAME"];

        //------------------------------------------------------------------------------------------

        string strDomain = "";
        if (serverName == "localhost")
        {
            //Lokal
            strDomain = "localhost:49573";
        }
        else
        {
            //Intranet
            strDomain = "i";
        }

        string strURL = "/Start.aspx";
        string strDirs = "control1.ascx";

        Separator3 = new Image();

        Separator3.Height = 52;
        Separator3.Width = 52;

        ArrowSeparator = new Image();
        ArrowSeparator.ImageUrl = "/img/mb_arrow_separator.png";

        HomeSymbol = new Image();
        HomeSymbol.ImageUrl = "/img/mb_home.png";

        // Home-Navigation for Start
        sbResult1.Append("");
        sbResult1.Append("" + RootName + " " + "");
        sbResult1.Append("");

        //-------------------------------------------------------------------------------------------------------------------------------

        foreach (var item in ModuleList)
        {
            if (HttpContext.Current.Session["ModuleTitle"] != null)
            {
                if (item.ModuleTitle == HttpContext.Current.Session["ModuleTitle"].ToString() )
                {
                    //sbResult1.Append("" + item.ModuleTitle + "" + Separator);

                    Separator3.ImageUrl = "/img/" + HttpContext.Current.Session["ModuleTitle"].ToString() + ".png";
                    sbResult1.Append("");
                    sbResult1.Append(HttpContext.Current.Session["ModuleTitle"]).ToString();
                }
            }
        }
        if (!ModuleList.Contains(HttpContext.Current.Session["ModuleTitle"]))
        {

            if (HttpContext.Current.Session["ModuleTitle"] != null)
            {
                if (HttpContext.Current.Session["ModuleTitle"].ToString().Contains("_"))//|| HttpContext.Current.Session["ModuleSubTitle"] != null)
                {
                    string[] std = HttpContext.Current.Session["ModuleTitle"].ToString().Split('_');

                    Separator3.ImageUrl = "/img/" + std[0] + ".png";
                    sbResult1.Append("");
                    sbResult1.Append("" + std[0] + " " + "");
                    sbResult1.Append("");

                    sbResult1.Append("");

                    sbResult1.Append(std[1]);

                }

            }
        }

        //-------------------------------------------------------------------------------------------------------------------------------

        output.Write(sbResult1.ToString());
    }

Do i have to make this Breadcrumb.cs and override Render() or is there a better way.

Greets DarkGecko

Body:
have you considered a SiteMapPath?

<asp:SiteMapPath ID="SiteMapPath1" Runat="server"></asp:SiteMapPath>

https://msdn.microsoft.com/en-us/library/x20z8c51.aspx


问:
Number of items purchased per invoice using seaborn and pandas
I'm using online retail dataset and I want to plot the distribution of number of items per invoice number.

InvoiceNo of type: non-null object

Quantity  of type: non-null int64

How to do that? Also, I didn't know how to filter using pandas operations to get that without visualizations.
like for example if I want to know the quantity per invoice I can do:

```<code>retail_uk.groupby('InvoiceNo').sum().sort_values(by='Quantity', ascending=False)['Quantity']
</code>```

I need an answer for both:

How to plot that with Seaborn (more important because it allows me to get a better idea of the distribution) what are the different data transformations needed to achieve that?

How to do it using groupby of Pandas.

答:
If you want to know the number of rows for each unique InvoiceNo, you can do

```<code>df.groupby('InvoiceNo').size()
</code>```

If you want to group all the unique InvoiceNo's together and sum the 'Quantity' rows within each group, you do

```<code>df.groupby('InvoiceNo').agg(np.sum)['Quantity']
</code>```

Body:
I'm using online retail dataset and I want to plot the distribution of number of items per invoice number.

InvoiceNo of type: non-null object

Quantity  of type: non-null int64

How to do that? Also, I didn't know how to filter using pandas operations to get that without visualizations.
like for example if I want to know the quantity per invoice I can do:

retail_uk.groupby('InvoiceNo').sum().sort_values(by='Quantity', ascending=False)['Quantity']

I need an answer for both:

How to plot that with Seaborn (more important because it allows me to get a better idea of the distribution) what are the different data transformations needed to achieve that?

How to do it using groupby of Pandas.

Body:
If you want to know the number of rows for each unique InvoiceNo, you can do

df.groupby('InvoiceNo').size()

If you want to group all the unique InvoiceNo's together and sum the 'Quantity' rows within each group, you do

df.groupby('InvoiceNo').agg(np.sum)['Quantity']


问:
Collecting process ids of parallel process in bash file
Below I have a script that is collecting the process ids of individual commands, and appending them to an array in bash. For some reason as you can see stdout below, the end resulting array just contains one item, the latest id. How can the resulting PROCESS_IDS array at the end of this script contain all four process ids?

```<code>PROCESS_IDS=()

function append {
    echo $1
    PROCESS_IDS=("${PROCESS_IDS[@]}" $1)
}

sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait

echo "${PROCESS_IDS[@]}"
</code>```

Here is the stdout:

```<code>83873
83875
83879
83882
three
one
four
two
83882
</code>```

答:
<s>My guess is that</s> whenever you send a function call to the background, it has a copy of the global variable on its own, so they're appending the PID to four independent copies of PROCESS_IDS. That's why every function call finds that it is empty and stores a single PID in it.

http://www.gnu.org/software/bash/manual/bashref.html#Lists

If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background.

If you want to collect the outputs from all four function calls, let them write to disk and read the output at the end:

```<code>function append {
    echo $1 | tee /tmp/file.$1
}

sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait

cat /tmp/file.*
</code>```

Edit: this is just a proof of concept - don't do it with file system anyway (as William pointed out, this is going to be error prone unless you take care of uniqueness and synchronization). I only wanted to illustrate that you need to find another way of getting the information out of the subshells.

Body:
Below I have a script that is collecting the process ids of individual commands, and appending them to an array in bash. For some reason as you can see stdout below, the end resulting array just contains one item, the latest id. How can the resulting PROCESS_IDS array at the end of this script contain all four process ids?

PROCESS_IDS=()

function append {
    echo $1
    PROCESS_IDS=("${PROCESS_IDS[@]}" $1)
}

sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait

echo "${PROCESS_IDS[@]}"

Here is the stdout:

83873
83875
83879
83882
three
one
four
two
83882

Body:
<s>My guess is that</s> whenever you send a function call to the background, it has a copy of the global variable on its own, so they're appending the PID to four independent copies of PROCESS_IDS. That's why every function call finds that it is empty and stores a single PID in it.

http://www.gnu.org/software/bash/manual/bashref.html#Lists

If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background.

If you want to collect the outputs from all four function calls, let them write to disk and read the output at the end:

function append {
    echo $1 | tee /tmp/file.$1
}

sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait

cat /tmp/file.*

Edit: this is just a proof of concept - don't do it with file system anyway (as William pointed out, this is going to be error prone unless you take care of uniqueness and synchronization). I only wanted to illustrate that you need to find another way of getting the information out of the subshells.


问:
C++ Stack Implementation (not working right)
Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+).

I am using a stack to convert a, user inputed, infix express to postfix. It seems to work fine except printing out the operands in the stack at the end.

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

class DishWell{
public:
    char ReturnFront(){
        return Well.front();
    }
    void Push(char x){
        Well.push_back(x);
    }
    void Pop(){
        Well.pop_back();
    }
    bool IsEmpty(){
        return Well.empty();
    }
private:
    vector<char> Well;
};

bool Precidence(char Input, char Stack){
    int InputPrecidence,StackPrecidence;
    switch (Input){
        case '*':
            InputPrecidence = 4;
            break;
        case '/':
            InputPrecidence = 4;
            break;
        case '+':
            InputPrecidence = 3;
            break;
        case '-':
            InputPrecidence = 3;
            break;
        case '(':
            InputPrecidence = 2;
            break;
        default:
            InputPrecidence = 0;
    }
switch (Stack){
    case '*':
        StackPrecidence = 4;
        break;
    case '/':
        StackPrecidence = 4;
        break;
    case '+':
        StackPrecidence = 3;
        break;
    case '-':
        StackPrecidence = 3;
        break;
    case '(':
        StackPrecidence = 2;
        break;
    default:
        StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}

int main(int argc, char** argv) {
    DishWell DishTray;
    char Input;
    bool InputFlag;
    InputFlag = true;
    cout<<"Enter Input, invalid input will terminate"<<endl;
    while(InputFlag){
        cout<<"Input: ";
        cin>>Input;
        cout<<endl;
        if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
            cout<<Input;
        if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
            if(DishTray.IsEmpty())
                DishTray.Push(Input);
            else if(Precidence(Input,DishTray.ReturnFront()))
                DishTray.Push(Input);
            else if(!Precidence(Input,DishTray.ReturnFront()))
                cout<<"Output: "<<Input<<endl;
        }
        else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
            InputFlag = false;
    }
    int counter = 0;
    while(!DishTray.IsEmpty()){
        counter++;
        cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
        DishTray.Pop();
    }
    return 0;
</code>```

Thank you, Macaire Bell

答: When you're working with a stack, you usually want to be able to see the value on the top of the stack. Your class only allows the very first item pushed (i.e. the bottom of the stack) to be visible. Your ReturnFront() should probably return Well.back() and perhaps it should be called something like ReturnTop().</p>

Body:
Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+).

I am using a stack to convert a, user inputed, infix express to postfix. It seems to work fine except printing out the operands in the stack at the end.

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

class DishWell{
public:
    char ReturnFront(){
        return Well.front();
    }
    void Push(char x){
        Well.push_back(x);
    }
    void Pop(){
        Well.pop_back();
    }
    bool IsEmpty(){
        return Well.empty();
    }
private:
    vector<char> Well;
};

bool Precidence(char Input, char Stack){
    int InputPrecidence,StackPrecidence;
    switch (Input){
        case '*':
            InputPrecidence = 4;
            break;
        case '/':
            InputPrecidence = 4;
            break;
        case '+':
            InputPrecidence = 3;
            break;
        case '-':
            InputPrecidence = 3;
            break;
        case '(':
            InputPrecidence = 2;
            break;
        default:
            InputPrecidence = 0;
    }
switch (Stack){
    case '*':
        StackPrecidence = 4;
        break;
    case '/':
        StackPrecidence = 4;
        break;
    case '+':
        StackPrecidence = 3;
        break;
    case '-':
        StackPrecidence = 3;
        break;
    case '(':
        StackPrecidence = 2;
        break;
    default:
        StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}

int main(int argc, char** argv) {
    DishWell DishTray;
    char Input;
    bool InputFlag;
    InputFlag = true;
    cout<<"Enter Input, invalid input will terminate"<<endl;
    while(InputFlag){
        cout<<"Input: ";
        cin>>Input;
        cout<<endl;
        if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
            cout<<Input;
        if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
            if(DishTray.IsEmpty())
                DishTray.Push(Input);
            else if(Precidence(Input,DishTray.ReturnFront()))
                DishTray.Push(Input);
            else if(!Precidence(Input,DishTray.ReturnFront()))
                cout<<"Output: "<<Input<<endl;
        }
        else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
            InputFlag = false;
    }
    int counter = 0;
    while(!DishTray.IsEmpty()){
        counter++;
        cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
        DishTray.Pop();
    }
    return 0;

Thank you, Macaire Bell


问:
with R, how to scan the interval value and print out subdata of other dataset?
Dataset 1:

```<code>dput(kk)

structure(list(V1 = c(1.05, NA, NA, NA, NA, NA, NA, NA, NA,
NA,
1.06, NA, NA, NA, NA, NA, NA, NA), V2 = c(NA, NA, 105.11, 105.12,
105.13, 105.14, 105.15, NA, 105.94, 105.99, NA, NA, 106.11, 106.12,
106.13, 106.14, 106.19, 106.2)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-18L))

show(kk)
       V1     V2
1  1.05     NA
2    NA     NA
3    NA 105.11
4    NA 105.12
5    NA 105.13
6    NA 105.14
7    NA 105.15
8    NA     NA
9    NA 105.94
10   NA 105.99
11 1.06     NA
12   NA     NA
13   NA 106.11
14   NA 106.12
15   NA 106.13
16   NA 106.14
17   NA 106.19
18   NA 106.20
</code>```

Dataset 2:

```<code>structure(list(V1 = structure(1:4, .Label = c("1.05 ~ 1.06",  "1.07",
"1.08", "1.09 ~ 1.10"), class = "factor")), .Names = "V1", class =
"data.frame", row.names = c(NA,
-4L))
           V1
1 1.05 ~ 1.06
2        1.07
3        1.08
4 1.09 ~ 1.10
</code>```

How can I scan the interval value of V1 in dataset 2 and print out the sub category data of dataset 1 which covers the interval on new dataset like above?

答:
If I understand correctly you are after something like this:

```<code>lapply(df2$V1, function(x) {
  z <- as.numeric(unlist(strsplit(as.character(x), split = " ~ ")))
  b <- which(df1$V1 %in% z)
  if(length(b)==0) return(NULL)
  if(length(b)==1) return(df1[b,])
  if(length(b)==2) return(df1[b[1]:b[2],])
})
#result
[[1]]
     V1     V2
1  1.05     NA
2    NA     NA
3    NA 105.11
4    NA 105.12
5    NA 105.13
6    NA 105.14
7    NA 105.15
8    NA     NA
9    NA 105.94
10   NA 105.99
11 1.06     NA

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL
</code>```

Explanation

with

```<code>lapply(df2$V1, function(x)...
</code>```

you go through elements of df2$V1 one by one and apply a function on each.

the function first splits the string at " ~ " then converts to numeric after un listing since strsplit returns a list and not a vector

```<code>z <- as.numeric(unlist(strsplit(as.character(x), split = " ~ ")))
</code>```

Then it determines which elements of df1$V1 are in z

```<code>b <- which(df1$V1 %in% z)
</code>```

And if b has 0 elements it returns NULL

if b has 1 element it returns just one row for df1$V1

if b has 2 elements it returns a range or rows from b[1] to b[2]

Body:
Dataset 1:

dput(kk)

structure(list(V1 = c(1.05, NA, NA, NA, NA, NA, NA, NA, NA,
NA,
1.06, NA, NA, NA, NA, NA, NA, NA), V2 = c(NA, NA, 105.11, 105.12,
105.13, 105.14, 105.15, NA, 105.94, 105.99, NA, NA, 106.11, 106.12,
106.13, 106.14, 106.19, 106.2)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-18L))

show(kk)
       V1     V2
1  1.05     NA
2    NA     NA
3    NA 105.11
4    NA 105.12
5    NA 105.13
6    NA 105.14
7    NA 105.15
8    NA     NA
9    NA 105.94
10   NA 105.99
11 1.06     NA
12   NA     NA
13   NA 106.11
14   NA 106.12
15   NA 106.13
16   NA 106.14
17   NA 106.19
18   NA 106.20

Dataset 2:

structure(list(V1 = structure(1:4, .Label = c("1.05 ~ 1.06",  "1.07",
"1.08", "1.09 ~ 1.10"), class = "factor")), .Names = "V1", class =
"data.frame", row.names = c(NA,
-4L))
           V1
1 1.05 ~ 1.06
2        1.07
3        1.08
4 1.09 ~ 1.10

How can I scan the interval value of V1 in dataset 2 and print out the sub category data of dataset 1 which covers the interval on new dataset like above?

Body:
If I understand correctly you are after something like this:

lapply(df2$V1, function(x) {
  z <- as.numeric(unlist(strsplit(as.character(x), split = " ~ ")))
  b <- which(df1$V1 %in% z)
  if(length(b)==0) return(NULL)
  if(length(b)==1) return(df1[b,])
  if(length(b)==2) return(df1[b[1]:b[2],])
})
#result
[[1]]
     V1     V2
1  1.05     NA
2    NA     NA
3    NA 105.11
4    NA 105.12
5    NA 105.13
6    NA 105.14
7    NA 105.15
8    NA     NA
9    NA 105.94
10   NA 105.99
11 1.06     NA

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

Explanation

with

lapply(df2$V1, function(x)...

you go through elements of df2$V1 one by one and apply a function on each.

the function first splits the string at " ~ " then converts to numeric after un listing since strsplit returns a list and not a vector

z <- as.numeric(unlist(strsplit(as.character(x), split = " ~ ")))

Then it determines which elements of df1$V1 are in z

b <- which(df1$V1 %in% z)

And if b has 0 elements it returns NULL

if b has 1 element it returns just one row for df1$V1

if b has 2 elements it returns a range or rows from b[1] to b[2]