问:
Semantic UI two almost-identical dropdowns - one works, one does not
I'm building a system that requires two dropdown on the same screen, literally one under another.

The below is an exact representation of my code.

```<code><div class="field">
    <label>Operational Category</label>
    <div class="ui selection dropdown">
        <input type="hidden" class="ui hidden timeType" name="time_type" value="10" />
        <i class="simple dropdown icon"></i>
        <div class="menu">
            <% for (let thisTimeType of timeTypes) { %>
                <div data-value="<%= thisTimeType.getId() %>"><%= thisTimeType.getName() %></div>
            <% } %>
        </div>
    </div>
</div>

<div class="field">
    <label>Task Category</label>
    <div class="ui selection dropdown">
        <input type="hidden" class="ui hidden category" name="card_category_id" value="<%= card_category_id %>" />
        <i class="simple dropdown icon"></i>
        <div class="default text">(no category)</div>
        <div class="menu">
            <% for (let thisCardCategory of cardCategories) { %>
            <% let isActive  = (thisCardCategory.getId() == card_category_id) ? 'active item' : 'item' %>
                <div class="<%= isActive %>" data-value="<%= thisCardCategory.getId() %>"><%= thisCardCategory.getName() %></div>
            <% } %>
        </div>
    </div>
</div>
</code>```

At the bottom of the file is a call to

```<code>jQuery('.ui.dropdown').dropdown();
</code>```

One of the dropdowns (ironically, the second one) works and the other one does not and I cannot figure out why. Things I've tried:

Giving the first one a 'default text'

Removing the second one to see if the first one will work

using 'simple' class to see if it's constructed okay. It hovers and shows options, although it looks rubbish.

Any thoughts? because I'm thoroughly confused by this. Am I missing something super-obvious?

Body:
I'm building a system that requires two dropdown on the same screen, literally one under another.

The below is an exact representation of my code.

    Operational Category

        <input type="hidden" class="ui hidden timeType" name="time_type" value="10" />

            <% for (let thisTimeType of timeTypes) { %>
                <div data-value="<%= thisTimeType.getId() %>"><%= thisTimeType.getName() %>

            <% } %>

    Task Category

        <input type="hidden" class="ui hidden category" name="card_category_id" value="<%= card_category_id %>" />

(no category)

            <% for (let thisCardCategory of cardCategories) { %>
            <% let isActive  = (thisCardCategory.getId() == card_category_id) ? 'active item' : 'item' %>
                <div class="<%= isActive %>" data-value="<%= thisCardCategory.getId() %>"><%= thisCardCategory.getName() %>

            <% } %>

At the bottom of the file is a call to

jQuery('.ui.dropdown').dropdown();

One of the dropdowns (ironically, the second one) works and the other one does not and I cannot figure out why. Things I've tried:

Giving the first one a 'default text'

Removing the second one to see if the first one will work

using 'simple' class to see if it's constructed okay. It hovers and shows options, although it looks rubbish.

Any thoughts? because I'm thoroughly confused by this. Am I missing something super-obvious?

Body:
Answer: As per IronGeek's comment, the answer is super-simple:

I was missing the item css className (class="item") on the first dropdown.

For example: <div class="item" data-value="<%= thisTimeType.getId() %>"><%= thisTimeType.getName() %></div>


来源: stackexchange

问:
Increasing all elements by integer x in O(n) in a program possibility?
So I have stumbled upon a problem to solve:

I need to create a data structure that will have a set of integers.
It needs to have methods:
The class is named:

class structure

methods:

void structure::new(); //creates an empty set

void structure::insert(int x); //inserts an integer x into the set

bool structure::isElement(int x); //checks if x is in the set

void structure::increaseBy(int x); // increases all elements in set by x

I guess this one is a homework question.

But i just want an opinion what data structure is the best to use in this implementation.

And how can i create the last method that would increase all elements by x in O(1) times, at first it seems like impossible.
Even if there are some c++ operators that have a functionality like that, wouldn't they have the same complexity?

I mean i could use a vector, array, even some linked list, set or similar structures.

So the problems isn't with first three methods, they are pretty easy to do, and also it is okay to use O(n) for the last one, but it's not "full points" unless it's O(1) time complexity. So is there a way to do it? Any hints would be helpful, and also I apologize if i made a mistake in creating this question it's my first time posting in stackoverflow.com, i was only using/posting math.stackexchange.com until now, so any advice would be appreciated as well.

Thank you in advance.

答:
Let's add addedSum member to your class:

```<code>template<typename Set> struct setWithInc {
    Set container;
    int addedSum;

    setWithInc() : addedSum(0) {}

    bool isElement(int x) {
        return container.find(x - addedSum) != container.end();
    }

    void insert(int x) {
        container.insert(x - addedSum);
    }

    void increaseBy(int x) {
        addedSum += x;
    }
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's add addedSum member to your class:

template<typename Set> struct setWithInc {
    Set container;
    int addedSum;

    setWithInc() : addedSum(0) {}

    bool isElement(int x) {
        return container.find(x - addedSum) != container.end();
    }

    void insert(int x) {
        container.insert(x - addedSum);
    }

    void increaseBy(int x) {
        addedSum += x;
    }
};


问:
Add fields dynamically in drupal depending on selected option using ajax/jquery
I'm trying to create/add textfields dynamically in drupal depending on the selected option for a select list.

if Jack is selected, then create textfield with "Jack" as content.

What I have done so far using Drupal's #ajax property, I managed to create textfields but could not get the select list option as field value.

```<code>$form['select_list'] = array(
    '#type' => 'select',
    '#options' => array('jack'=>'Jack', 'ben'=>'Ben'),
    '#ajax' => array(
         'callback' => 'mymodule_ajax_add',
         'wrapper' => 'select_list_fieldset',
         'method' => 'replace',
         'effect' => 'fade'
    )
);

$form['select_list_fieldset'] = array(
      '#type' => 'fieldset',
      '#prefix' => '<div id="select_list_fieldset">',
      '#suffix' => '</div>';
);

$form_state['storage']['num_people'] = isset($form_state['storage']['num_people']) ? $form_state['storage']['num_people'] : 1;

if($form_state['storage']['num_people']){
    for( $i = 1; $i < $form_state['storage']['num_people']; $i++){
        $form['select_list_fieldset'][$i]['person_name'] = array(
            '#title' => 'Name',
            '#type' => 'textfield',
            '#value' => ???????
        );
    }
}

$form_state['storage']['num_people']++;

function mymodule_ajax_add($form, &$form_state){
    return $form['select_list_fieldset'];
}
</code>```

I got this to work but got frustrated on how to populate the fields with what I want.

I also tried to do it explicitly using jQuery. I managed to re-create fields pre-populated with the values depending on the selected option from the select list.

```<code>$('#select_list').change(function(){
    var name_key = $(this).val();
    var name_value = $(this).text();

    $('#select_list_fieldset').append('<input type="text" value="'+name_value+'">');
});
</code>```

The problem with writing it through jQuery is that once the form is submitted all dynamically created fields are disregarded. I read it somewhere here in stackoverflow.

Can anyone help me and point me to the right direction on how to achieve this? Thanks a lot in advance.

答:
Get selected option of select_list :

```<code>$selected_name = isset($form_state['values']['select_list]) ? $form_state['values']['select_list'] :  NULL;
</code>```

Set default value for person_name :

```<code>'#default_value' =>  $selected_name,
</code>```

Body:
I'm trying to create/add textfields dynamically in drupal depending on the selected option for a select list.

if Jack is selected, then create textfield with "Jack" as content.

What I have done so far using Drupal's #ajax property, I managed to create textfields but could not get the select list option as field value.

$form['select_list'] = array(
    '#type' => 'select',
    '#options' => array('jack'=>'Jack', 'ben'=>'Ben'),
    '#ajax' => array(
         'callback' => 'mymodule_ajax_add',
         'wrapper' => 'select_list_fieldset',
         'method' => 'replace',
         'effect' => 'fade'
    )
);

$form['select_list_fieldset'] = array(
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
';
);

$form_state['storage']['num_people'] = isset($form_state['storage']['num_people']) ? $form_state['storage']['num_people'] : 1;

if($form_state['storage']['num_people']){
    for( $i = 1; $i < $form_state['storage']['num_people']; $i++){
        $form['select_list_fieldset'][$i]['person_name'] = array(
            '#title' => 'Name',
            '#type' => 'textfield',
            '#value' => ???????
        );
    }
}

$form_state['storage']['num_people']++;

function mymodule_ajax_add($form, &$form_state){
    return $form['select_list_fieldset'];
}

I got this to work but got frustrated on how to populate the fields with what I want.

I also tried to do it explicitly using jQuery. I managed to re-create fields pre-populated with the values depending on the selected option from the select list.

$('#select_list').change(function(){
    var name_key = $(this).val();
    var name_value = $(this).text();

    $('#select_list_fieldset').append('<input type="text" value="'+name_value+'">');
});

The problem with writing it through jQuery is that once the form is submitted all dynamically created fields are disregarded. I read it somewhere here in stackoverflow.

Can anyone help me and point me to the right direction on how to achieve this? Thanks a lot in advance.

Body:
Get selected option of select_list :

$selected_name = isset($form_state['values']['select_list]) ? $form_state['values']['select_list'] :  NULL;

Set default value for person_name :

'#default_value' =>  $selected_name,


问:
htaccess not working in a hosting
I'm done a site on XAMPP and I wanted to transfer it on a Hosting.

The problem is the htaccess that does not work in the hosting.

```<code>    Options -Indexes

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico

  RewriteRule ^(.*)(\.)(.*)$ index.php?url=$1.$3 [L,QSA]
  RewriteRule ^ajax$ _res/ajax.php [QSA]
  #RewriteRule ^(.*)$ index.php?t=$1 [L,QSA]
</IfModule>
</code>```

答:
Try without L:

```<code># Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico

  RewriteRule ^(.*)(\.)(.*)$ index.php?url=$1.$3 [QSA]
  RewriteRule ^ajax$ _res/ajax.php [QSA]
  #RewriteRule ^(.*)$ index.php?t=$1 [QSA]
</IfModule>
</code>```

From RewriteRule Flags:

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

Try test your .hateaccess on some htaccess tester.

Title: htaccess not working in a hosting

Body:
I'm done a site on XAMPP and I wanted to transfer it on a Hosting.

The problem is the htaccess that does not work in the hosting.

    Options -Indexes

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico

  RewriteRule ^(.*)(\.)(.*)$ index.php?url=$1.$3 [L,QSA]
  RewriteRule ^ajax$ _res/ajax.php [QSA]
  #RewriteRule ^(.*)$ index.php?t=$1 [L,QSA]
</IfModule>

Body:
Try without L:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico

  RewriteRule ^(.*)(\.)(.*)$ index.php?url=$1.$3 [QSA]
  RewriteRule ^ajax$ _res/ajax.php [QSA]
  #RewriteRule ^(.*)$ index.php?t=$1 [QSA]
</IfModule>

From RewriteRule Flags:

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

Try test your .hateaccess on some htaccess tester.


问:
Increase the size of the text box in the BigQuery UI
This is a silly question. I write lots of queries, sometimes long, in the BigQuery UI. The text box only displays a dozen lines or so, which forces me to scroll a lot, all the time. Is there a way to increase the size of the text box?</p>

答: Yes sure, there is a divider you can use to make bigger, if you don't see check your browser extensions as it might cut it out.


问:
SQL Server - Generating schedule list of repeating dates
We have a set of records where each record (Job) has a cycle (or frequency) in days that determines when the job appears on somebody's work list. E.G

Job A is generated every 7 days
Job B is generated every 14 days.

Each Job also has a start date.

I need to generate a table which contains all the possible job dates between a date range.

Here is my first part of code which generates the possible dates.

```<code>DECLARE @ForecastEarliestStartDate as DATETIME, @formStartDate as DATE,@formEndDate as DATE, @cycleInDays as BIGINT;

--set input param values
SET @ForecastEarliestStartDate = CAST('2017-07-03' AS DATETIME)
SET @formStartDate = getdate();
SET @formEndDate = getdate()+60;
SET @cycleInDays = 28;

WITH mycte AS
(
  SELECT @ForecastEarliestStartDate DateValue
  UNION ALL
  SELECT   DateValue + @cycleInDays
  FROM    mycte
  WHERE   DateValue + @cycleInDays < @formEndDate
)

SELECT  *
FROM    mycte
WHERE DateValue between @formStartDate and @formEndDate
OPTION (MAXRECURSION 0);
</code>```

This works fine as for a single Job, but how can I run it against a whole table of Jobs where @ForecastEarliestStartDate, @formStartDate, @formEndDate, @cycleInDays are fields in a table?

答:
I'll often use a TVF to create dynamic date/time ranges.  Often faster than a recursive CTE and it is parameter driven.  You supply the date/time range, datepart, and increment.

For Example

```<code>Select * From [dbo].[udf-Range-Date]('2017-07-03',getdate()+60,'DD',7)
</code>```

Returns

```<code>RetSeq  RetVal
1   2017-07-03
2   2017-07-10
3   2017-07-17
4   2017-07-24
5   2017-07-31
6   2017-08-07
7   2017-08-14
8   2017-08-21
9   2017-08-28
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[udf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D
     From  cte3,cte0
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[udf-Range-Date]('2016-10-01','2020-10-01','YY',1)
Select * from [dbo].[udf-Range-Date]('2016-01-01','2017-01-01','MM',1)
*/
</code>```

Edit - Working Example of CROSS APPLY

```<code>Declare @YourTable table (JobName varchar(50),StartDate date,Interval int)
Insert Into @YourTable values
 ('Job A','2017-07-03',7)
,('Job B','2017-07-03',14)

Select A.JobName
      ,JobDate = B.RetVal
 From @YourTable A
 Cross Apply [dbo].[udf-Range-Date](A.StartDate,getdate()+60,'DD',A.Interval) B
</code>```

Returns

```<code>JobName JobDate
Job A   2017-07-03
Job A   2017-07-10
Job A   2017-07-17
Job A   2017-07-24
Job A   2017-07-31
Job A   2017-08-07
Job A   2017-08-14
Job A   2017-08-21
Job A   2017-08-28
Job B   2017-07-03   -- << Notice differant span for Job B
Job B   2017-07-17
Job B   2017-07-31
Job B   2017-08-14
Job B   2017-08-28
</code>```

Body:
We have a set of records where each record (Job) has a cycle (or frequency) in days that determines when the job appears on somebody's work list. E.G

Job A is generated every 7 days
Job B is generated every 14 days.

Each Job also has a start date.

I need to generate a table which contains all the possible job dates between a date range.

Here is my first part of code which generates the possible dates.

DECLARE @ForecastEarliestStartDate as DATETIME, @formStartDate as DATE,@formEndDate as DATE, @cycleInDays as BIGINT;

--set input param values
SET @ForecastEarliestStartDate = CAST('2017-07-03' AS DATETIME)
SET @formStartDate = getdate();
SET @formEndDate = getdate()+60;
SET @cycleInDays = 28;

WITH mycte AS
(
  SELECT @ForecastEarliestStartDate DateValue
  UNION ALL
  SELECT   DateValue + @cycleInDays
  FROM    mycte
  WHERE   DateValue + @cycleInDays < @formEndDate
)

SELECT  *
FROM    mycte
WHERE DateValue between @formStartDate and @formEndDate
OPTION (MAXRECURSION 0);

This works fine as for a single Job, but how can I run it against a whole table of Jobs where @ForecastEarliestStartDate, @formStartDate, @formEndDate, @cycleInDays are fields in a table?

Body:
I'll often use a TVF to create dynamic date/time ranges.  Often faster than a recursive CTE and it is parameter driven.  You supply the date/time range, datepart, and increment.

For Example

Select * From [dbo].[udf-Range-Date]('2017-07-03',getdate()+60,'DD',7)

Returns

RetSeq  RetVal
1   2017-07-03
2   2017-07-10
3   2017-07-17
4   2017-07-24
5   2017-07-31
6   2017-08-07
7   2017-08-14
8   2017-08-21
9   2017-08-28

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D
     From  cte3,cte0
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[udf-Range-Date]('2016-10-01','2020-10-01','YY',1)
Select * from [dbo].[udf-Range-Date]('2016-01-01','2017-01-01','MM',1)
*/

Edit - Working Example of CROSS APPLY

Declare @YourTable table (JobName varchar(50),StartDate date,Interval int)
Insert Into @YourTable values
 ('Job A','2017-07-03',7)
,('Job B','2017-07-03',14)

Select A.JobName
      ,JobDate = B.RetVal
 From @YourTable A
 Cross Apply [dbo].[udf-Range-Date](A.StartDate,getdate()+60,'DD',A.Interval) B

Returns

JobName JobDate
Job A   2017-07-03
Job A   2017-07-10
Job A   2017-07-17
Job A   2017-07-24
Job A   2017-07-31
Job A   2017-08-07
Job A   2017-08-14
Job A   2017-08-21
Job A   2017-08-28
Job B   2017-07-03   -- << Notice differant span for Job B
Job B   2017-07-17
Job B   2017-07-31
Job B   2017-08-14
Job B   2017-08-28


问:
Fragment Cache a user control in asp.net webform Masterpage
I had a Masterpage which uses as sidebar for navigation .I created a user control for that sidebar  as each user will have their own set of navigation menus.

Inside my UserMenu I use Infragistic webexplorer and Iam creating each item  of webexplorer using ado.net result from database dynamically.

Everything is working fine .in high bandwidth but in low bandwidth it takes 3-4 seconds for the menubar to load.causing users to wait so much on each postback.

So I tried fragment caching .but i seems not working.can you suggest me whats wrong

In masterpage I did

```<code>    <div>
    //this is my usercontrol
                         <uc1:DynamicMenuBar runat="server" id="DynamicMenuBar" />
    </div>
     <div id="main" class="content" >

       <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                    <div class="bodybackground">
                    </div>

                </asp:ContentPlaceHolder>
  </div>
</code>```

In my usercontrol .ascx

```<code><%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DynamicMenuBar.ascx.cs" Inherits="ArtWebApp.DynamicMenuBar" %>
<%@ Register assembly="Infragistics35.Web.v12.1, Version=12.1.20121.2236, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" namespace="Infragistics.Web.UI.NavigationControls" tagprefix="ig" %>
<%@ OutputCache Duration="600" VaryByParam="none" %>
<ig:WebExplorerBar ID="WebExplorerBar1" runat="server" Width="250px">
</ig:WebExplorerBar>
</code>```

And in my usercontrol .ascx.cs I had done the below

```<code>   public partial class DynamicMenuBar : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadexplorerebar(); //this function creates the groups and childs based on the database result dynamically
                this.WebExplorerBar1.EnableViewState = true;
            }
        }
</code>```

答: It seems to be the internet problem. Try using AJAX call instead of server code for menu retrieval</p>

Body:
I had a Masterpage which uses as sidebar for navigation .I created a user control for that sidebar  as each user will have their own set of navigation menus.

Inside my UserMenu I use Infragistic webexplorer and Iam creating each item  of webexplorer using ado.net result from database dynamically.

Everything is working fine .in high bandwidth but in low bandwidth it takes 3-4 seconds for the menubar to load.causing users to wait so much on each postback.

So I tried fragment caching .but i seems not working.can you suggest me whats wrong

In masterpage I did

    //this is my usercontrol
                         <uc1:DynamicMenuBar runat="server" id="DynamicMenuBar" />

       <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                </asp:ContentPlaceHolder>

In my usercontrol .ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DynamicMenuBar.ascx.cs" Inherits="ArtWebApp.DynamicMenuBar" %>
<%@ Register assembly="Infragistics35.Web.v12.1, Version=12.1.20121.2236, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" namespace="Infragistics.Web.UI.NavigationControls" tagprefix="ig" %>
<%@ OutputCache Duration="600" VaryByParam="none" %>
<ig:WebExplorerBar ID="WebExplorerBar1" runat="server" Width="250px">
</ig:WebExplorerBar>

And in my usercontrol .ascx.cs I had done the below

   public partial class DynamicMenuBar : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadexplorerebar(); //this function creates the groups and childs based on the database result dynamically
                this.WebExplorerBar1.EnableViewState = true;
            }
        }


问:
Casting an object to List<T> to be able to use extension methods
I have generated an extension method to display a IList<T> in a meaningful manner:

```<code>public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}
</code>```

To use this extension I can do this:

```<code>IList<someClass> myList = CreateList();
myList.ToDisplay();
</code>```

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

```<code>public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}
</code>```

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

答:
Example below uses reflection to detect if the type is an IList so it will be safe to cast it as a IList.</p>

```<code>var lst = new List<SomeObject>();
var obj = lst;

var type = obj.GetType();
var ilistType = typeof(IList<>);

if(type == ilistType || type.GetInterfaces().Any(c=>c.IsGenericType && c.GetGenericTypeDefinition() == ilistType)){
Console.WriteLine("object is a list");
// code here
}
</code>```

Body:
I have generated an extension method to display a IList<T> in a meaningful manner:

public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

To use this extension I can do this:

IList<someClass> myList = CreateList();
myList.ToDisplay();

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

Body:
Example below uses reflection to detect if the type is an IList so it will be safe to cast it as a IList.

var lst = new List<SomeObject>();
var obj = lst;

var type = obj.GetType();
var ilistType = typeof(IList<>);

if(type == ilistType || type.GetInterfaces().Any(c=>c.IsGenericType && c.GetGenericTypeDefinition() == ilistType)){
Console.WriteLine("object is a list");
// code here
}


问:
Deploying Symfony 1.4 project
I have recently developed a project which is written using Symfony 1.4 which I installed through PEAR. In previous Symfony versions there used to be freeze and unfreeze functions to copy all the necessary files, but in this versions these functions are missing. So my question is - what is the fastest way to deploy my project on a shared hosting?

答:
Shared hosting is always a pain with Symfony. I haven't attempted it myself. But what you can do is just copy the lib folder from your symfony installation into your project lib folder and just point your projectConfiguration.php to where you put the symfony libs in your project.

This just does the same thing as the freeze but manually.

ContentLicense: CC BY-SA 2.5

Title: Deploying Symfony 1.4 project


问:
Reference invalidated after std::vector push_back
I wrote an example which leads with Visual to a crash. I think the critical section is here:

```<code>A a;
B b(a);
pair p(a, b);
res.push_back(p);
</code>```

I assign a temporary which takes a reference to another temporary and move it into a vector. I also noticed that the program seems not to crash with GCC. I think the problem is, that the reference is invalidated since the moment I move the objects into the vector. Do I have to use new?

```<code>// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <math.h>

class Materials {
public:
  Materials() = default;
};

class A {
private:
  std::vector<Materials> _storage;

public:
  void setStorage(const std::vector<Materials> &val) {
    _storage = val;
  }
};

class B {
private:
  A &_a;

public:
  B(A &foo) : _a(foo) {}

  void run() {
    std::vector<Materials> val;
    for (int i = 0; i < 1000; i++) {
      val.push_back(Materials());
    }

    _a.setStorage(val);
  }
};

struct pair {
  pair(const A &a, const B &b)
    : _a(a)
    , _b(b)
  {
  }

  A _a;
  B _b;
};

std::vector<pair> make_list() {
  std::vector<pair> res;
  for (int i = 0; i < 10; i++) {
    A a;
    B b(a);
    pair p(a, b);
    res.push_back(p);
  }
  return res;
}

int main()
{
  std::vector<pair> list = make_list();
  B &ref = list[1]._b;
  ref.run();
}
</code>```

答: Instances of A and B classes created in function make_list are local and valid only within the functions. Objects are allocated in stack and content may be destroyed when program leaves make_list. "new" could help because objects are allocated in heap and will be there until allocated memory will be freed.  </p>

Body:
I wrote an example which leads with Visual to a crash. I think the critical section is here:

A a;
B b(a);
pair p(a, b);
res.push_back(p);

I assign a temporary which takes a reference to another temporary and move it into a vector. I also noticed that the program seems not to crash with GCC. I think the problem is, that the reference is invalidated since the moment I move the objects into the vector. Do I have to use new?

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <math.h>

class Materials {
public:
  Materials() = default;
};

class A {
private:
  std::vector<Materials> _storage;

public:
  void setStorage(const std::vector<Materials> &val) {
    _storage = val;
  }
};

class B {
private:
  A &_a;

public:
  B(A &foo) : _a(foo) {}

  void run() {
    std::vector<Materials> val;
    for (int i = 0; i < 1000; i++) {
      val.push_back(Materials());
    }

    _a.setStorage(val);
  }
};

struct pair {
  pair(const A &a, const B &b)
    : _a(a)
    , _b(b)
  {
  }

  A _a;
  B _b;
};

std::vector<pair> make_list() {
  std::vector<pair> res;
  for (int i = 0; i < 10; i++) {
    A a;
    B b(a);
    pair p(a, b);
    res.push_back(p);
  }
  return res;
}

int main()
{
  std::vector<pair> list = make_list();
  B &ref = list[1]._b;
  ref.run();
}


问:
Command /Applications/Xcode-beta.app/Contents/Developer/usr/bin/actool failed with exit code 255
It happens in new Xcode7 beta:

```<code>CompileAssetCatalog /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Products/Debug-iphoneos/InstaAd.app InstaAd/Images.xcassets
    cd /Users/admin/Documents/git/InstaAdIOS/InstaAd
    export PATH="/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode-beta.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode-beta.app/Contents/Developer/usr/bin/actool --output-format human-readable-text --notices --warnings --export-dependency-info /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Intermediates/InstaAd.build/Debug-iphoneos/InstaAd.build/assetcatalog_dependencies.txt --output-partial-info-plist /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Intermediates/InstaAd.build/Debug-iphoneos/InstaAd.build/assetcatalog_generated_info.plist --app-icon AppIcon --launch-image LaunchImage --compress-pngs --enable-on-demand-resources YES --filter-for-device-model iPhone7,2 --filter-for-device-os-version 8.4 --target-device iphone --target-device ipad --minimum-deployment-target 8.0 --platform iphoneos --compile /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Products/Debug-iphoneos/InstaAd.app /Users/admin/Documents/git/InstaAdIOS/InstaAd/InstaAd/Images.xcassets

2015-08-10 14:25:53.366 IBCocoaTouchImageCatalogTool[1054:10336] CoreUI(DEBUG): CSIGenerator using 'LZVN' Compression coreui version (358.000000)
2015-08-10 14:25:56.449 ibtoold[675:6100] An uncaught exception was raised
2015-08-10 14:25:56.450 ibtoold[675:6100] The agent crashed

Application Specific Information:
CoreSimulator 179 - Device: IBSimDeviceTypeiPad1x - Runtime: iOS 9.0 (13A4325c) - DeviceType: IBSimDeviceTypeiPad1x

Thread 6 Crashed:: TDRenditionsDistiller._distill:
0   com.apple.CoreFoundation        0x000000010bc03f61 __CFBasicHashDrain + 353
1   com.apple.CoreFoundation        0x000000010bbf4a1c CFRelease + 300
2   com.apple.CoreFoundation        0x000000010bc03f42 __CFBasicHashDrain + 322
3   com.apple.CoreFoundation        0x000000010bbf4a1c CFRelease + 300
4   com.apple.ImageIO.framework     0x000000010d7f8028 modifyJPEG + 2859
5   com.apple.ImageIO.framework     0x000000010d6079b8 CGImageDestinationCopyImageSource + 576
6   com.apple.CoreThemeDefinition   0x000000010dbfcec9 -[TDSimpleArtworkRenditionSpec createCSIRepresentationWithCompression:colorSpaceID:document:] + 1690
7   com.apple.CoreThemeDefinition   0x000000010dc0555b -[TDRenditionsDistiller _distill:] + 609
8   com.apple.Foundation            0x000000010b2c73ab __NSThread__start__ + 1198
9   libsystem_pthread.dylib         0x000000010d236268 _pthread_body + 131
10  libsystem_pthread.dylib         0x000000010d2361e5 _pthread_start + 176
11  libsystem_pthread.dylib         0x000000010d23441d thread_start + 13

Last command:
_ON_QUEUE_sendMessage:toChannelReturningError:during:

Backtrace of last command:
  0  0x00000001111c69f6 -[IBAbstractPlatformToolProxy _ON_QUEUE_sendMessage:toChannelReturningError:during:] (in IDEInterfaceBuilderKit)
  1  0x00000001111c68bb __74-[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:]_block_invoke (in IDEInterfaceBuilderKit)
  2  0x00007fff8c046c13 _dispatch_client_callout (in libdispatch.dylib)
  3  0x00007fff8c047e5e _dispatch_barrier_sync_f_invoke (in libdispatch.dylib)
  4  0x000000011007aabc DVTDispatchSync (in DVTFoundation)
  5  0x00000001111c67de -[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:] (in IDEInterfaceBuilderKit)
  6  0x000000011aae2526 (in IDEInterfaceBuilderCocoaTouchIntegration)
  7  0x000000011aacda8b (in IDEInterfaceBuilderCocoaTouchIntegration)
  8  0x000000011111dbf3 __84-[IBICAbstractPlatformAdapter compileSelectedItems:options:queue:completionHandler:]_block_invoke (in IDEInterfaceBuilderKit)
  9  0x000000011007abb0 __DVTDispatchAsync_block_invoke (in DVTFoundation)
 10  0x00007fff8c04b323 _dispatch_call_block_and_release (in libdispatch.dylib)
 11  0x00007fff8c046c13 _dispatch_client_callout (in libdispatch.dylib)
 12  0x00007fff8c052cbf _dispatch_main_queue_callback_4CF (in libdispatch.dylib)
 13  0x00007fff8d58b3f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ (in CoreFoundation)
 14  0x00007fff8d54668f __CFRunLoopRun (in CoreFoundation)
 15  0x00007fff8d545bd8 CFRunLoopRunSpecific (in CoreFoundation)
 16  0x00000001111912bc -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:whileBlockExecutesConcurrently:] (in IDEInterfaceBuilderKit)
 17  0x00000001111914ba -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:waitingForSemaphore:] (in IDEInterfaceBuilderKit)
 18  0x000000010fde887a (in ibtoold)
 19  0x000000010fde9e30 (in ibtoold)
 20  0x000000010fdea2b0 (in ibtoold)
 21  0x000000010fdf7e6f (in ibtoold)
 22  0x000000010fdf8523 (in ibtoold)
 23  0x000000010fdf83fa (in ibtoold)
 24  0x000000010fde76c2 (in ibtoold)
 25  0x000000010fdf7a64 (in ibtoold)
 26  0x000000010fdf6cc9 (in ibtoold)
 27  0x00007fff8eb585c9 start (in libdyld.dylib)
2015-08-10 14:25:56.451 ibtoold[675:6100] (
    0   CoreFoundation                      0x00007fff8d63803c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff980b976e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff8d637bd9 -[NSException raise] + 9
    3   IDEInterfaceBuilderKit              0x00000001111c5b55 -[IBAbstractPlatformToolProxy _errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:shouldRaiseOnFailures:waitForCrashLog:] + 1632
    4   IDEInterfaceBuilderKit              0x00000001111c54cb -[IBAbstractPlatformToolProxy errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:] + 98
    5   IDEInterfaceBuilderKit              0x00000001111c6a90 -[IBAbstractPlatformToolProxy _ON_QUEUE_sendMessage:toChannelReturningError:during:] + 227
    6   IDEInterfaceBuilderKit              0x00000001111c68bb __74-[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:]_block_invoke + 38
    7   libdispatch.dylib                   0x00007fff8c046c13 _dispatch_client_callout + 8
    8   libdispatch.dylib                   0x00007fff8c047e5e _dispatch_barrier_sync_f_invoke + 57
    9   DVTFoundation                       0x000000011007aabc DVTDispatchSync + 62
    10  IDEInterfaceBuilderKit              0x00000001111c67de -[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:] + 393
    11  IDEInterfaceBuilderCocoaTouchIntegration 0x000000011aae2526 IBUISegmentConfiguration + 6975
    12  IDEInterfaceBuilderCocoaTouchIntegration 0x000000011aacda8b IBUIControlEventTypeToUIControlEventMask + 17323
    13  IDEInterfaceBuilderKit              0x000000011111dbf3 __84-[IBICAbstractPlatformAdapter compileSelectedItems:options:queue:completionHandler:]_block_invoke + 230
    14  DVTFoundation                       0x000000011007abb0 __DVTDispatchAsync_block_invoke + 69
    15  libdispatch.dylib                   0x00007fff8c04b323 _dispatch_call_block_and_release + 12
    16  libdispatch.dylib                   0x00007fff8c046c13 _dispatch_client_callout + 8
    17  libdispatch.dylib                   0x00007fff8c052cbf _dispatch_main_queue_callback_4CF + 861
    18  CoreFoundation                      0x00007fff8d58b3f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    19  CoreFoundation                      0x00007fff8d54668f __CFRunLoopRun + 2159
    20  CoreFoundation                      0x00007fff8d545bd8 CFRunLoopRunSpecific + 296
    21  IDEInterfaceBuilderKit              0x00000001111912bc -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:whileBlockExecutesConcurrently:] + 500
    22  IDEInterfaceBuilderKit              0x00000001111914ba -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:waitingForSemaphore:] + 131
    23  ibtoold                             0x000000010fde887a ibtoold + 10362
    24  ibtoold                             0x000000010fde9e30 ibtoold + 15920
    25  ibtoold                             0x000000010fdea2b0 ibtoold + 17072
    26  ibtoold                             0x000000010fdf7e6f ibtoold + 73327
    27  ibtoold                             0x000000010fdf8523 ibtoold + 75043
    28  ibtoold                             0x000000010fdf83fa ibtoold + 74746
    29  ibtoold                             0x000000010fde76c2 ibtoold + 5826
    30  ibtoold                             0x000000010fdf7a64 ibtoold + 72292
    31  ibtoold                             0x000000010fdf6cc9 ibtoold + 68809
    32  libdyld.dylib                       0x00007fff8eb585c9 start + 1
    33  ???                                 0x0000000000000002 0x0 + 2
)
Command /Applications/Xcode-beta.app/Contents/Developer/usr/bin/actool failed with exit code 255
</code>```

How to solve this issue?

答:
This error happened with me because the image name contained some unsupported characters (it was saved by Xcode as c71a25e%2FÍcone-XPTO Imagem - 120x120.png, even when placed in .xcassets).

Changing the image name solved this error for me.

Body:
It happens in new Xcode7 beta:

CompileAssetCatalog /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Products/Debug-iphoneos/InstaAd.app InstaAd/Images.xcassets
    cd /Users/admin/Documents/git/InstaAdIOS/InstaAd
    export PATH="/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode-beta.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode-beta.app/Contents/Developer/usr/bin/actool --output-format human-readable-text --notices --warnings --export-dependency-info /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Intermediates/InstaAd.build/Debug-iphoneos/InstaAd.build/assetcatalog_dependencies.txt --output-partial-info-plist /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Intermediates/InstaAd.build/Debug-iphoneos/InstaAd.build/assetcatalog_generated_info.plist --app-icon AppIcon --launch-image LaunchImage --compress-pngs --enable-on-demand-resources YES --filter-for-device-model iPhone7,2 --filter-for-device-os-version 8.4 --target-device iphone --target-device ipad --minimum-deployment-target 8.0 --platform iphoneos --compile /Users/admin/Library/Developer/Xcode/DerivedData/InstaAd-ddgdnbxlpxipirebpndfmgrxspel/Build/Products/Debug-iphoneos/InstaAd.app /Users/admin/Documents/git/InstaAdIOS/InstaAd/InstaAd/Images.xcassets

2015-08-10 14:25:53.366 IBCocoaTouchImageCatalogTool[1054:10336] CoreUI(DEBUG): CSIGenerator using 'LZVN' Compression coreui version (358.000000)
2015-08-10 14:25:56.449 ibtoold[675:6100] An uncaught exception was raised
2015-08-10 14:25:56.450 ibtoold[675:6100] The agent crashed

Application Specific Information:
CoreSimulator 179 - Device: IBSimDeviceTypeiPad1x - Runtime: iOS 9.0 (13A4325c) - DeviceType: IBSimDeviceTypeiPad1x

Thread 6 Crashed:: TDRenditionsDistiller._distill:
0   com.apple.CoreFoundation        0x000000010bc03f61 __CFBasicHashDrain + 353
1   com.apple.CoreFoundation        0x000000010bbf4a1c CFRelease + 300
2   com.apple.CoreFoundation        0x000000010bc03f42 __CFBasicHashDrain + 322
3   com.apple.CoreFoundation        0x000000010bbf4a1c CFRelease + 300
4   com.apple.ImageIO.framework     0x000000010d7f8028 modifyJPEG + 2859
5   com.apple.ImageIO.framework     0x000000010d6079b8 CGImageDestinationCopyImageSource + 576
6   com.apple.CoreThemeDefinition   0x000000010dbfcec9 -[TDSimpleArtworkRenditionSpec createCSIRepresentationWithCompression:colorSpaceID:document:] + 1690
7   com.apple.CoreThemeDefinition   0x000000010dc0555b -[TDRenditionsDistiller _distill:] + 609
8   com.apple.Foundation            0x000000010b2c73ab __NSThread__start__ + 1198
9   libsystem_pthread.dylib         0x000000010d236268 _pthread_body + 131
10  libsystem_pthread.dylib         0x000000010d2361e5 _pthread_start + 176
11  libsystem_pthread.dylib         0x000000010d23441d thread_start + 13

Last command:
_ON_QUEUE_sendMessage:toChannelReturningError:during:

Backtrace of last command:
  0  0x00000001111c69f6 -[IBAbstractPlatformToolProxy _ON_QUEUE_sendMessage:toChannelReturningError:during:] (in IDEInterfaceBuilderKit)
  1  0x00000001111c68bb __74-[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:]_block_invoke (in IDEInterfaceBuilderKit)
  2  0x00007fff8c046c13 _dispatch_client_callout (in libdispatch.dylib)
  3  0x00007fff8c047e5e _dispatch_barrier_sync_f_invoke (in libdispatch.dylib)
  4  0x000000011007aabc DVTDispatchSync (in DVTFoundation)
  5  0x00000001111c67de -[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:] (in IDEInterfaceBuilderKit)
  6  0x000000011aae2526 (in IDEInterfaceBuilderCocoaTouchIntegration)
  7  0x000000011aacda8b (in IDEInterfaceBuilderCocoaTouchIntegration)
  8  0x000000011111dbf3 __84-[IBICAbstractPlatformAdapter compileSelectedItems:options:queue:completionHandler:]_block_invoke (in IDEInterfaceBuilderKit)
  9  0x000000011007abb0 __DVTDispatchAsync_block_invoke (in DVTFoundation)
 10  0x00007fff8c04b323 _dispatch_call_block_and_release (in libdispatch.dylib)
 11  0x00007fff8c046c13 _dispatch_client_callout (in libdispatch.dylib)
 12  0x00007fff8c052cbf _dispatch_main_queue_callback_4CF (in libdispatch.dylib)
 13  0x00007fff8d58b3f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ (in CoreFoundation)
 14  0x00007fff8d54668f __CFRunLoopRun (in CoreFoundation)
 15  0x00007fff8d545bd8 CFRunLoopRunSpecific (in CoreFoundation)
 16  0x00000001111912bc -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:whileBlockExecutesConcurrently:] (in IDEInterfaceBuilderKit)
 17  0x00000001111914ba -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:waitingForSemaphore:] (in IDEInterfaceBuilderKit)
 18  0x000000010fde887a (in ibtoold)
 19  0x000000010fde9e30 (in ibtoold)
 20  0x000000010fdea2b0 (in ibtoold)
 21  0x000000010fdf7e6f (in ibtoold)
 22  0x000000010fdf8523 (in ibtoold)
 23  0x000000010fdf83fa (in ibtoold)
 24  0x000000010fde76c2 (in ibtoold)
 25  0x000000010fdf7a64 (in ibtoold)
 26  0x000000010fdf6cc9 (in ibtoold)
 27  0x00007fff8eb585c9 start (in libdyld.dylib)
2015-08-10 14:25:56.451 ibtoold[675:6100] (
    0   CoreFoundation                      0x00007fff8d63803c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff980b976e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff8d637bd9 -[NSException raise] + 9
    3   IDEInterfaceBuilderKit              0x00000001111c5b55 -[IBAbstractPlatformToolProxy _errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:shouldRaiseOnFailures:waitForCrashLog:] + 1632
    4   IDEInterfaceBuilderKit              0x00000001111c54cb -[IBAbstractPlatformToolProxy errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:] + 98
    5   IDEInterfaceBuilderKit              0x00000001111c6a90 -[IBAbstractPlatformToolProxy _ON_QUEUE_sendMessage:toChannelReturningError:during:] + 227
    6   IDEInterfaceBuilderKit              0x00000001111c68bb __74-[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:]_block_invoke + 38
    7   libdispatch.dylib                   0x00007fff8c046c13 _dispatch_client_callout + 8
    8   libdispatch.dylib                   0x00007fff8c047e5e _dispatch_barrier_sync_f_invoke + 57
    9   DVTFoundation                       0x000000011007aabc DVTDispatchSync + 62
    10  IDEInterfaceBuilderKit              0x00000001111c67de -[IBAbstractPlatformToolProxy sendMessage:toChannelReturningError:during:] + 393
    11  IDEInterfaceBuilderCocoaTouchIntegration 0x000000011aae2526 IBUISegmentConfiguration + 6975
    12  IDEInterfaceBuilderCocoaTouchIntegration 0x000000011aacda8b IBUIControlEventTypeToUIControlEventMask + 17323
    13  IDEInterfaceBuilderKit              0x000000011111dbf3 __84-[IBICAbstractPlatformAdapter compileSelectedItems:options:queue:completionHandler:]_block_invoke + 230
    14  DVTFoundation                       0x000000011007abb0 __DVTDispatchAsync_block_invoke + 69
    15  libdispatch.dylib                   0x00007fff8c04b323 _dispatch_call_block_and_release + 12
    16  libdispatch.dylib                   0x00007fff8c046c13 _dispatch_client_callout + 8
    17  libdispatch.dylib                   0x00007fff8c052cbf _dispatch_main_queue_callback_4CF + 861
    18  CoreFoundation                      0x00007fff8d58b3f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    19  CoreFoundation                      0x00007fff8d54668f __CFRunLoopRun + 2159
    20  CoreFoundation                      0x00007fff8d545bd8 CFRunLoopRunSpecific + 296
    21  IDEInterfaceBuilderKit              0x00000001111912bc -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:whileBlockExecutesConcurrently:] + 500
    22  IDEInterfaceBuilderKit              0x00000001111914ba -[NSRunLoop(IBIDEFoundationRunLoopAdditions) ib_spinRunLoopInMode:waitingForSemaphore:] + 131
    23  ibtoold                             0x000000010fde887a ibtoold + 10362
    24  ibtoold                             0x000000010fde9e30 ibtoold + 15920
    25  ibtoold                             0x000000010fdea2b0 ibtoold + 17072
    26  ibtoold                             0x000000010fdf7e6f ibtoold + 73327
    27  ibtoold                             0x000000010fdf8523 ibtoold + 75043
    28  ibtoold                             0x000000010fdf83fa ibtoold + 74746
    29  ibtoold                             0x000000010fde76c2 ibtoold + 5826
    30  ibtoold                             0x000000010fdf7a64 ibtoold + 72292
    31  ibtoold                             0x000000010fdf6cc9 ibtoold + 68809
    32  libdyld.dylib                       0x00007fff8eb585c9 start + 1
    33  ???                                 0x0000000000000002 0x0 + 2
)
Command /Applications/Xcode-beta.app/Contents/Developer/usr/bin/actool failed with exit code 255

How to solve this issue?


问:
How to run a script only on Unity editor startup?
I'm writing my own autosave script for Unity editor and I want it to run its setup method when the editor is launched. I've tried using InitializeOnLoad, but it calls the static constructor not only when the editor starts but also every time the Play button is pressed, initializing again my script and resetting all its timers.

I've tried to put a condition to initialize the script only if the timers have their value set to the default value, but apparently InitializeOnLoad creates another instance of my script, so everything gets reset and the condition is useless.

Then I thought about creating a bool in the editor preferences at startup to check, when I press Play, if the script has been launched before. But then I can't find a way to reset this value when the editor is closed, so when I launch the editor again the bool is still true and the autosave doesn't start.

I also tried using ExecuteInEditMode to call the OnDestroy method and set the editor pref to false, but of course it only works when there's an instance of the script attached to a GameObject in the scene, which is not the case for an editor script.

Is there a solution to this out there?
Thanks in advance.

答:
Use this inside your static constructor:</p>

```<code>if (!EditorApplication.isPlayingOrWillChangePlaymode) {
    //Do constructor stuff
}
</code>```

Body:
Use this inside your static constructor:

if (!EditorApplication.isPlayingOrWillChangePlaymode) {
    //Do constructor stuff
}


问:
How to import self-signed SSL certificate to Volley on Android 4.1+
I develop android application which uses Volley.
All communication is done via HTTPS connection.
Because I test it on local environment, I use self-signed certificates for Tomcat.

Before, I had only android 2.3 and 3.0 devices. Now I've got also 4.1 and 4.4.

My implementation uses this approach: http://developer.android.com/training/articles/security-ssl.html (part Unknown certificate authority)
On devices with Android up to 4.1 it works perfectly. SSLSocketFactory with custom certificates is passed to Volley:

```<code>Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, socketFactory));
</code>```

But what happens on Android 4.1+?
Why it does not work?
I tried also with NullX509TrustManager like this:

```<code>private static class NullX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
</code>```

But it still does not work...

答:
Trust all SSL certificates:-
You can bypass SSL if you want to test on the testing server.
But do not use this code for production.

```<code>public static class NukeSSLCerts {
protected static final String TAG = "NukeSSLCerts";

public static void nuke() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                    return myTrustedAnchors;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
    }
}
</code>```

}

Please call this function in onCreate() function in Activity or in your Application Class.

```<code>NukeSSLCerts.nuke();
</code>```

This can be used for Volley in Android.
More Ref.
https://newfivefour.com/android-trust-all-ssl-certificates.html

Body:
I develop android application which uses Volley.
All communication is done via HTTPS connection.
Because I test it on local environment, I use self-signed certificates for Tomcat.

Before, I had only android 2.3 and 3.0 devices. Now I've got also 4.1 and 4.4.

My implementation uses this approach: http://developer.android.com/training/articles/security-ssl.html (part Unknown certificate authority)
On devices with Android up to 4.1 it works perfectly. SSLSocketFactory with custom certificates is passed to Volley:

Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, socketFactory));

But what happens on Android 4.1+?
Why it does not work?
I tried also with NullX509TrustManager like this:

private static class NullX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

But it still does not work...

Body:
Trust all SSL certificates:-
You can bypass SSL if you want to test on the testing server.
But do not use this code for production.

public static class NukeSSLCerts {
protected static final String TAG = "NukeSSLCerts";

public static void nuke() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                    return myTrustedAnchors;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
    }
}

}

Please call this function in onCreate() function in Activity or in your Application Class.

NukeSSLCerts.nuke();

This can be used for Volley in Android.
More Ref.
https://newfivefour.com/android-trust-all-ssl-certificates.html


答:
Here's a possible implementation

```<code>class structure
{
public:
    void insert(int x) {ls.push_front(x - offset);}
    bool isElement(int x) {return std::find(ls.begin(), ls.end(), x - offset) != ls.end();}
    void increaseBy(int x) {offset += x;}
private:
    int offset = 0;
    std::list<int> ls;
};
</code>```

This is

O(1) for insert

O(n) for isElement

O(1) for increaseBy

Title: Increasing all elements by integer x in O(n) in a program possibility?

Body:
So I have stumbled upon a problem to solve:

I need to create a data structure that will have a set of integers.
It needs to have methods:
The class is named:

class structure

methods:

void structure::new(); //creates an empty set

void structure::insert(int x); //inserts an integer x into the set

bool structure::isElement(int x); //checks if x is in the set

void structure::increaseBy(int x); // increases all elements in set by x

I guess this one is a homework question.

But i just want an opinion what data structure is the best to use in this implementation.

And how can i create the last method that would increase all elements by x in O(1) times, at first it seems like impossible.
Even if there are some c++ operators that have a functionality like that, wouldn't they have the same complexity?

I mean i could use a vector, array, even some linked list, set or similar structures.

So the problems isn't with first three methods, they are pretty easy to do, and also it is okay to use O(n) for the last one, but it's not "full points" unless it's O(1) time complexity. So is there a way to do it? Any hints would be helpful, and also I apologize if i made a mistake in creating this question it's my first time posting in stackoverflow.com, i was only using/posting math.stackexchange.com until now, so any advice would be appreciated as well.

Thank you in advance.

Body:
Here's a possible implementation

class structure
{
public:
    void insert(int x) {ls.push_front(x - offset);}
    bool isElement(int x) {return std::find(ls.begin(), ls.end(), x - offset) != ls.end();}
    void increaseBy(int x) {offset += x;}
private:
    int offset = 0;
    std::list<int> ls;
};

This is

O(1) for insert

O(n) for isElement

O(1) for increaseBy


问:
How to abort execution in a local plug?
If I use a plug locally in a controller.

For example:

```<code>defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug :authenticate_user_by_api_key!

  def some_method(conn, params) do

  end

  defp authenticate_user_by_api_key!(conn, params) do
    # Authenticate
    #How to permit execution or abort it?
  end
end
</code>```

As I understand, authenticate_user_by_api_key will be called before any method, correct?

I need to allow or abort execution of called method, how would I do so?

答:
As I understand, authenticate_user_by_api_key will be called before any method, correct?

Yes.

I need to allow or abort execution of called method, how would I do so?

You can use Plug.Conn.halt/1 to halt the execution of further plugs, including the function that was originally going to be called by the Phoenix Router. For valid authentication, you can just return the original conn and execution will continue.

(Note: the second argument to the plug function is the plug options, not Phoenix's params. To access params in the plug, you can use conn.params.)

```<code>defp authenticate_user_by_api_key!(conn, opts) do
  if some_condition_which_is_true_for_valid_key do
    conn
  else
    # you'll generally want to respond with something before halting execution
    conn
    |> put_status(400)
    |> text("invalid api key")
    |> halt
  end
end
</code>```

Title: How to abort execution in a local plug?

Body:
If I use a plug locally in a controller.

For example:

defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug :authenticate_user_by_api_key!

  def some_method(conn, params) do

  end

  defp authenticate_user_by_api_key!(conn, params) do
    # Authenticate
    #How to permit execution or abort it?
  end
end

As I understand, authenticate_user_by_api_key will be called before any method, correct?

I need to allow or abort execution of called method, how would I do so?

Body:
As I understand, authenticate_user_by_api_key will be called before any method, correct?

Yes.

I need to allow or abort execution of called method, how would I do so?

You can use Plug.Conn.halt/1 to halt the execution of further plugs, including the function that was originally going to be called by the Phoenix Router. For valid authentication, you can just return the original conn and execution will continue.

(Note: the second argument to the plug function is the plug options, not Phoenix's params. To access params in the plug, you can use conn.params.)

defp authenticate_user_by_api_key!(conn, opts) do
  if some_condition_which_is_true_for_valid_key do
    conn
  else
    # you'll generally want to respond with something before halting execution
    conn
    |> put_status(400)
    |> text("invalid api key")
    |> halt
  end
end


问:
Run the right scripts before deployment elastic beanstalk
I am editing my .ebextensions .config file to run some initialisation commands before deployment. I thought this commands would be run in the same folder of the extracted .zip containing my app. But that's not the case. manage.py is in the root directory of my zip and if I do the commands:

```<code>  01_collectstatic:
    command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput"
</code>```

I get a ERROR: [Instance: i-085e84b9d1df851c9] Command failed on instance. Return code: 2 Output: python: can't open file 'manage.py': [Errno 2] No such file or directory.

I could do command: "python /opt/python/current/app/manage.py collectstatic --noinput" but that would run the manage.py that successfully was deployed previously instead of running the one that is being deployed atm.

I tried to check what was the working directory of the commands ran by the .config by doing command: "pwd" and it seems that pwd is /opt/elasticbeanstalk/eb_infra which doesn't contain my app.

So I probably need to change $PYTHONPATH to contain the right path, but I don't know which path is it.

In this comment the user added the following to his .config file:

```<code>option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: myapp.settings
    PYTHONPATH: "./src"
</code>```

Because his manage.py lives inside the src folder within the root of his zip. In my case I would do PYTHONPATH: "." but it's not working.

答:
AWS support solved the problem. Here's their answer:

When Beanstalk is deploying an application, it keeps your application files in a "staging" directory while the EB Extensions and Hook Scripts are being processed. Once the pre-deploy scripts have finished, the application is then moved to the "production" directory. The issue you are having is related to the "manage.py" file not being in the expected location when your "01_collectstatic" command is being executed.

The staging location for your environment (Python 3.4, Amazon Linux 2017.03) is "/opt/python/ondeck/app".

The EB Extension "commands" section is executed before the staging directory is actually created. To run your script once the staging directory has been created, you should use "container_commands". This section is meant for modifying your application after the application has been extracted, but before it has been deployed to the production directory. It will automatically run your command in your staging directory.

Can you please try implementing the container_command section and see if it helps resolve your problem? The syntax will look similar to this (but please test it before deploying to production):

```<code>container_commands:
  01_collectstatic:
    command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput"
</code>```

Body:
I am editing my .ebextensions .config file to run some initialisation commands before deployment. I thought this commands would be run in the same folder of the extracted .zip containing my app. But that's not the case. manage.py is in the root directory of my zip and if I do the commands:

  01_collectstatic:
    command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput"

I get a ERROR: [Instance: i-085e84b9d1df851c9] Command failed on instance. Return code: 2 Output: python: can't open file 'manage.py': [Errno 2] No such file or directory.

I could do command: "python /opt/python/current/app/manage.py collectstatic --noinput" but that would run the manage.py that successfully was deployed previously instead of running the one that is being deployed atm.

I tried to check what was the working directory of the commands ran by the .config by doing command: "pwd" and it seems that pwd is /opt/elasticbeanstalk/eb_infra which doesn't contain my app.

So I probably need to change $PYTHONPATH to contain the right path, but I don't know which path is it.

In this comment the user added the following to his .config file:

option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: myapp.settings
    PYTHONPATH: "./src"

Because his manage.py lives inside the src folder within the root of his zip. In my case I would do PYTHONPATH: "." but it's not working.

Body:
AWS support solved the problem. Here's their answer:

When Beanstalk is deploying an application, it keeps your application files in a "staging" directory while the EB Extensions and Hook Scripts are being processed. Once the pre-deploy scripts have finished, the application is then moved to the "production" directory. The issue you are having is related to the "manage.py" file not being in the expected location when your "01_collectstatic" command is being executed.

The staging location for your environment (Python 3.4, Amazon Linux 2017.03) is "/opt/python/ondeck/app".

The EB Extension "commands" section is executed before the staging directory is actually created. To run your script once the staging directory has been created, you should use "container_commands". This section is meant for modifying your application after the application has been extracted, but before it has been deployed to the production directory. It will automatically run your command in your staging directory.

Can you please try implementing the container_command section and see if it helps resolve your problem? The syntax will look similar to this (but please test it before deploying to production):

container_commands:
  01_collectstatic:
    command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput"


问:
Translations with many components using ng2-translate
Hi I have a problem with translations, I'm using ng2-translate and this theme: SB Admin Bootstrap 4 Angular 4

I have an header with a language select dropdown menù, if I change language only my header component is translated but not the entire page (I have correctly configured pipes in all my project and imported translatemodule in the correct module)

My component.html is:

```<code><app-header></app-header>
<app-sidebar></app-sidebar>
<section class="main-container">
<router-outlet></router-outlet>
</section>
</code>```

In my header I have this dropdown:

```<code><div>
 <label>
  {{ 'HOME.SELECT' | translate }}
  <select #langSelect (change)="translate.use(langSelect.value);setLang()">
   <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
  </select>
 </label>
</div>
</code>```

What is the way to change language at entire page if it's formed by many other components?

答:
You need to import the ng2-translate module in all your modules where you are using translate pipe. it better to install the next version ngx-translate/core.

For ngx-translate/core need to import TranslateModule in all your sub-modules

```<code>...
import {TranslateModule} from '@ngx-translate/core';
...

@NgModule({
    imports: [
        ...,
        TranslateModule //or TranslateModule.forChild()
    ]
</code>```

Body:
Hi I have a problem with translations, I'm using ng2-translate and this theme: SB Admin Bootstrap 4 Angular 4

I have an header with a language select dropdown menù, if I change language only my header component is translated but not the entire page (I have correctly configured pipes in all my project and imported translatemodule in the correct module)

My component.html is:

<app-header></app-header>
<app-sidebar></app-sidebar>

<router-outlet></router-outlet>

In my header I have this dropdown:

  {{ 'HOME.SELECT' | translate }}
  <select #langSelect (change)="translate.use(langSelect.value);setLang()">
   <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
  </select>

What is the way to change language at entire page if it's formed by many other components?

Body:
You need to import the ng2-translate module in all your modules where you are using translate pipe. it better to install the next version ngx-translate/core.

For ngx-translate/core need to import TranslateModule in all your sub-modules

...
import {TranslateModule} from '@ngx-translate/core';
...

@NgModule({
    imports: [
        ...,
        TranslateModule //or TranslateModule.forChild()
    ]


问:
Windows form, display dynamic google map instead of static map in .NET
I am trying to display a dynamic google map on a windows form in .NET

I have succeeded in implementing a windows form asking a request on google map as followed :

```<code> public Form1()
    {
        InitializeComponent();
    }

    private void find_data_Click_1(object sender, EventArgs e)
    {
        string street = txt_street.Text;
        string city = txt_city.Text;
        try
        {
            StringBuilder queryaddress = new StringBuilder();
            queryaddress.Append("http://maps.google.com/maps?q=");
            if (street != string.Empty)
            {
                queryaddress.Append(street + "," + "+");
            }
            if (city != string.Empty)
            {
                queryaddress.Append(city + "," + "+");
            }
            webBrowser1.Navigate(queryaddress.ToString());
        }
        catch
        {
            MessageBox.Show("Error");
        }
    }
</code>```

Then I succeeded in having a staticmap with google api with multiple markers doing this :

```<code>private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder queryaddress = new StringBuilder();
            queryaddress.Append("https://maps.googleapis.com/maps/api/staticmap?center=63.259591,-144.667969&zoom=6&size=400x400&markers=color:blue%7Clabel:S%7C62.107733,-145.541936&markers=size:tiny%7Ccolor:green%7CDelta+Junction,AK&markers=size:mid%7Ccolor:0xFFFF00%7Clabel:C%7CTok,AK&key=myApiKey");
            webBrowser1.Navigate(queryaddress.ToString());
        }
        catch
        {
            MessageBox.Show("Error");
        }
    }
</code>```

What I would like to have is the same output as the staticmap with multiple markers but with the interaction offers as in google map like in the first code portions.

I use to code with R and python, using the library leaflet to ease the implementation.

I don't know how to do multiple plot markers on interactive maps in C#.

答:
I finally found a turnkey solution with tutorials at this address :
http://www.independent-software.com/gmap-net-tutorial-maps-markers-and-polygons/</p>

Body:
I am trying to display a dynamic google map on a windows form in .NET

I have succeeded in implementing a windows form asking a request on google map as followed :

 public Form1()
    {
        InitializeComponent();
    }

    private void find_data_Click_1(object sender, EventArgs e)
    {
        string street = txt_street.Text;
        string city = txt_city.Text;
        try
        {
            StringBuilder queryaddress = new StringBuilder();
            queryaddress.Append("http://maps.google.com/maps?q=");
            if (street != string.Empty)
            {
                queryaddress.Append(street + "," + "+");
            }
            if (city != string.Empty)
            {
                queryaddress.Append(city + "," + "+");
            }
            webBrowser1.Navigate(queryaddress.ToString());
        }
        catch
        {
            MessageBox.Show("Error");
        }
    }

Then I succeeded in having a staticmap with google api with multiple markers doing this :

private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder queryaddress = new StringBuilder();
            queryaddress.Append("https://maps.googleapis.com/maps/api/staticmap?center=63.259591,-144.667969&zoom=6&size=400x400&markers=color:blue%7Clabel:S%7C62.107733,-145.541936&markers=size:tiny%7Ccolor:green%7CDelta+Junction,AK&markers=size:mid%7Ccolor:0xFFFF00%7Clabel:C%7CTok,AK&key=myApiKey");
            webBrowser1.Navigate(queryaddress.ToString());
        }
        catch
        {
            MessageBox.Show("Error");
        }
    }

What I would like to have is the same output as the staticmap with multiple markers but with the interaction offers as in google map like in the first code portions.

I use to code with R and python, using the library leaflet to ease the implementation.

I don't know how to do multiple plot markers on interactive maps in C#.


问:
How do you add a "PrivateIpAddresses" to a Network interface
I am looking for the output of the troposphere to look like this(json). I could not find any examples to point me in the right direction at all. And in the future if I come across similar issues, is there any documentation I should refer to in particular?</p>

```<code>"NetworkInterfaces": [
          {
            "DeleteOnTermination": "true",
            "Description": "Primary network interface",
            "DeviceIndex": 0,
            "SubnetId": "subnet-yolo",
            "PrivateIpAddresses": [
              {
                "PrivateIpAddress": "xxx.xx.xx.xx",
                "Primary": "true"
              }
            ],
            "GroupSet": [
              "xxxxxx",
              "yyyyyy"
            ]
          }
        ]
</code>```

答:
Answer was pretty basic. First we need to make a sample_ip like so

```<code>sample_ip = template.add_parameter(ec2.PrivateIpAddressSpecification(
    "PrivateIpAddress",
    Primary="true",
    PrivateIpAddress="172.168.1.1"
))
</code>```

Then do this:

```<code>PrivateIpAddresses=[Ref(sample_ip)]
</code>```

I'll keep this here in case some uber beginner like me is not able to do this on his/her own.

Body:
I am looking for the output of the troposphere to look like this(json). I could not find any examples to point me in the right direction at all. And in the future if I come across similar issues, is there any documentation I should refer to in particular?

"NetworkInterfaces": [
          {
            "DeleteOnTermination": "true",
            "Description": "Primary network interface",
            "DeviceIndex": 0,
            "SubnetId": "subnet-yolo",
            "PrivateIpAddresses": [
              {
                "PrivateIpAddress": "xxx.xx.xx.xx",
                "Primary": "true"
              }
            ],
            "GroupSet": [
              "xxxxxx",
              "yyyyyy"
            ]
          }
        ]

Body:
Answer was pretty basic. First we need to make a sample_ip like so

sample_ip = template.add_parameter(ec2.PrivateIpAddressSpecification(
    "PrivateIpAddress",
    Primary="true",
    PrivateIpAddress="172.168.1.1"
))

Then do this:

PrivateIpAddresses=[Ref(sample_ip)]

I'll keep this here in case some uber beginner like me is not able to do this on his/her own.


问:
Real world experiences with the ADO.NET Entity Framework and unit testing
I am investigating the ADO.NET Entity Framework in combination with unit testing. A recommended way is described by Scott Allan:

Testability and Entity Framework 4.0

The article involves the code generation with POCOS.

My first impression: The manual effort to introduce and maintain this architecture is high. Before a deep dive I am interested in any real world experience.

答:
Scott suggests the POCO template as an option, not a requirement. You don't need to use it. Scott's strategy also works with non-POCO entities.

The effort would be high if unit testing were the only benefit. But since you also get a well structured application organized along commonly-understood patterns, good unit testing is really just icing on the cake with Scott's architecture.


问:
Failure to find org.osgi:org.osgi.service.jaxrs:jar:1.0.0-SNAPSHOT
I wanted to analyse the samples for JAX-RS for Pax-Web.

However, I can't import it to Eclise or compile with Maven because the following maven dependency can't be found:

```<code>org.osgi:org.osgi.service.jaxrs:jar:1.0.0-SNAPSHOT
</code>```

I was trying to find the library org.osgi.service.jaxrs, but got no success with Google or Maven repository...

What is this library? Is it a project that has changed name? How to get those samples to life?

答:
It's available from the official OSGi sonatype repository.
And actually also configured in the Pax Web root pom.
See also here

It contains the following location for an extra repository:

```<code>    <repository>
        <id>osgi-releases-and-snapshots</id>
        <url>https://oss.sonatype.org/content/groups/osgi/</url>
        <layout>default</layout>
    </repository>
</code>```

Body:
I wanted to analyse the samples for JAX-RS for Pax-Web.

However, I can't import it to Eclise or compile with Maven because the following maven dependency can't be found:

org.osgi:org.osgi.service.jaxrs:jar:1.0.0-SNAPSHOT

I was trying to find the library org.osgi.service.jaxrs, but got no success with Google or Maven repository...

What is this library? Is it a project that has changed name? How to get those samples to life?

Body:
It's available from the official OSGi sonatype repository.
And actually also configured in the Pax Web root pom.
See also here

It contains the following location for an extra repository:

    <repository>
        <id>osgi-releases-and-snapshots</id>
        <url>https://oss.sonatype.org/content/groups/osgi/</url>
        <layout>default</layout>
    </repository>


问:
Using Linq for ObjectDataSource: How to transform datetime using ToShortTimeString?
I am accessing a business class using an ObjectDataSource and trying to produce output that makes sense to the user.  The return values describe a Class (as in Classroom and teaching, not software).  I would like to show the time of the class as a range like this: "9:00 AM - 10:00 AM".

This is the Linq Query I am using to pull the data:

```<code>return classQuery.Select(p => new SelectClassData
                              {
                                   ClassID = p.ClassID,
                                   Title = p.Title,
                                   StartDate = p.StartDate.ToShortDateString(),
                                   EndDate = p.EndDate.ToShortDateString(),
                                   TimeOfClass =
                                   p.StartDate.ToShortTimeString() + " - " +
                                                       p.EndDate.ToShortTimeString()
                               }).ToList();
</code>```

As you can see, I encode the start and ending times in the starting and ending dates even though these could potentially be on different dates.

When I execute this code I get:

"Could not translate expression 'p.EndDate.ToShortTimeString()' into SQL and could not treat it as a local expression."

I know that I am projecting the results but, being new to Linq, I had assumed that the C# call to ToShortTimeString happened after the projection.  Can anyone help me figure out how to get the string I'm looking for?

答:
I like Mehrdad's answer a lot.  It not only solves the problem, it also teaches me something about Linq as well.  Thank you!

I've kept banging away at the problem, though, and did come up with a different approach that I'll describe here in case someone else stumbling on this question wants to consider.  My Linq to SQL code now reads:

```<code>return classQuery.Select(p => new SelectClassData
                              {
                                   ClassID = p.ClassID,
                                   Title = p.Title,
                                   sDate = p.StartDate,
                                   eDate = p.EndDate
                              }).ToList();
</code>```

Note that sDate and eDate are now DateTime objects instead of strings.  In the "SelectClassData" object, I simply changed the declaration so that access to the StartDate, EndDate and TimeOfClass variables go through a property getter:

```<code>public class SelectClassData
{
    public int ClassID { get; set; }
    public string Title { get; set; }
    public DateTime sDate { get; set; }
    public DateTime eDate { get; set; }
    public string StartDate { get { return GetSDate(); } }
    public string EndDate { get { return GetEDate(); } }
    public string TimeOfClass { get { return GetTimeOfClass(); } }

    protected string GetSDate()
    {
        return sDate.ToShortDateString();
    }

    protected string GetEDate()
    {
        return eDate.ToShortDateString();
    }

    protected string GetTimeOfClass()
    {
        return sDate.ToShortTimeString() + " - " + eDate.ToShortTimeString();
    }
}
</code>```

That is, I set the sDate and eDate via the LinqToSql but do the "ToShortTimeString" and "ToShortDateString" transformations after the Linq retrieval by implementing it in the target data class.

OwnerDisplayName: Mark Brittingham

Body:
I am accessing a business class using an ObjectDataSource and trying to produce output that makes sense to the user.  The return values describe a Class (as in Classroom and teaching, not software).  I would like to show the time of the class as a range like this: "9:00 AM - 10:00 AM".

This is the Linq Query I am using to pull the data:

return classQuery.Select(p => new SelectClassData
                              {
                                   ClassID = p.ClassID,
                                   Title = p.Title,
                                   StartDate = p.StartDate.ToShortDateString(),
                                   EndDate = p.EndDate.ToShortDateString(),
                                   TimeOfClass =
                                   p.StartDate.ToShortTimeString() + " - " +
                                                       p.EndDate.ToShortTimeString()
                               }).ToList();

As you can see, I encode the start and ending times in the starting and ending dates even though these could potentially be on different dates.

When I execute this code I get:

"Could not translate expression 'p.EndDate.ToShortTimeString()' into SQL and could not treat it as a local expression."

I know that I am projecting the results but, being new to Linq, I had assumed that the C# call to ToShortTimeString happened after the projection.  Can anyone help me figure out how to get the string I'm looking for?

LastEditorDisplayName: Mark Brittingham

Body:
I like Mehrdad's answer a lot.  It not only solves the problem, it also teaches me something about Linq as well.  Thank you!

I've kept banging away at the problem, though, and did come up with a different approach that I'll describe here in case someone else stumbling on this question wants to consider.  My Linq to SQL code now reads:

return classQuery.Select(p => new SelectClassData
                              {
                                   ClassID = p.ClassID,
                                   Title = p.Title,
                                   sDate = p.StartDate,
                                   eDate = p.EndDate
                              }).ToList();

Note that sDate and eDate are now DateTime objects instead of strings.  In the "SelectClassData" object, I simply changed the declaration so that access to the StartDate, EndDate and TimeOfClass variables go through a property getter:

public class SelectClassData
{
    public int ClassID { get; set; }
    public string Title { get; set; }
    public DateTime sDate { get; set; }
    public DateTime eDate { get; set; }
    public string StartDate { get { return GetSDate(); } }
    public string EndDate { get { return GetEDate(); } }
    public string TimeOfClass { get { return GetTimeOfClass(); } }

    protected string GetSDate()
    {
        return sDate.ToShortDateString();
    }

    protected string GetEDate()
    {
        return eDate.ToShortDateString();
    }

    protected string GetTimeOfClass()
    {
        return sDate.ToShortTimeString() + " - " + eDate.ToShortTimeString();
    }
}

That is, I set the sDate and eDate via the LinqToSql but do the "ToShortTimeString" and "ToShortDateString" transformations after the Linq retrieval by implementing it in the target data class.


问:
SQL data retrieve - C#
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ.
For example, 1st time i want 5rd row,then 2nd, then 9...so on.

I searched it through the internet. I got only two answers.

Use several SqlConnection objects.

reader= sqlCommand.ExecuteReader();
While(reader.Read()){
    reader["Column Name"].ToString();
}

If you got my problem, please help me
Thank you.

答: What exactly are you trying to achieve? Retrieve random rows from a DS or do you have certain criteria for selecting which rows you want returned? And if so couldn't you order them before loading them into the reader?</p>

Title: SQL data retrieve - C#


问:
Including images in javadocs
I work with a lot of sample test cases that are visual. Is there any convenient way to include them in my Java source and link them in Javadocs, so my IDE can automatically show them while coding (by invoking a javadoc renderer feature in my IDE?)

I tried putting an image next to the Java source and using , but it's not taking (I used a png).

(note - it's in my test sources in this case)

答:
I stumbled upon this question as I as well wanted to show a preview of my icons. After reading the answers, I was not yet satisfied and tried it for myself. That's what I now got:

```<code>     /**
     * <img src="../../../../../../resources/com/my/project/client/images/myImage.png"><br>
     * Icon for myImage.
     *
     * @return the icon
     */
</code>```

like this I don't need to manage more images than before by simply going to the folder the actual images lie in.

Title: Including images in javadocs

Body:
I stumbled upon this question as I as well wanted to show a preview of my icons. After reading the answers, I was not yet satisfied and tried it for myself. That's what I now got:

     /**
     * <img src="../../../../../../resources/com/my/project/client/images/myImage.png"><br>
     * Icon for myImage.
     *
     * @return the icon
     */

like this I don't need to manage more images than before by simply going to the folder the actual images lie in.


问:
ERROR. 'keytool' is not recognized as an internal or external command, operable program or batch file
I try to add facebook login to my android app. I exactly followed the documentation but when I try to run a command line in Android Studio terminal to generate a development hash key, it says "'keytool' is not recognized as an internal or external command,
operable program or batch file.

This is my command code:

keytool -exportcert -alias androiddebugkey -keystore
  %HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl
  base64

What should I do?

答: You need to add <JDK location>\bin to PATH environment variable.


问:
Why is my sine wave frequency sweep not correct?
I'm trying to create a simple WAV file that emits a changing pitch. However, the waveform that gets written to the file does not correspond to the data that get_sample returns.

I expect the tone to change in a logarithmic fashion, starting at A10 (28,160 Hz) and to end at A0 (27.5 Hz). As each second passes, the pitch should smoothly drop by one octave.

What is actually happening is difficult to explain. The tone changes, but in unintended ways. And what makes my problem more peculiar is that lowering the sample rate worsens the problem. In this output at 48,000 samples per second, the pitch rapidly drops and then rises again just to slowly fall once more. In this output at 3,000 samples per second, a similar effect happens, but it is more extreme and chaotic. What am I doing wrongly?

```<code>from math import pi, sin
from sys import byteorder
import wave

def get_sample(time):
    frequency = a10 / 2.0 ** time
    # print('{:.15f} {:.15f} {:.15f}'.format(time, frequency, sin(pi2 * frequency * time)))
    return sin(pi2 * frequency * time)

pi2 = 2 * pi
a10 = 28160.0

NUMBER_OF_CHANNELS = 1
SAMPLE_RATE = 48000  # samples per second
SAMPLE_WIDTH = 3  # bytes
DURATION = 10  # seconds

MAX_SAMPLE_VALUE = 2 ** (SAMPLE_WIDTH * 8 - 1)

samples = bytearray()

for i in range(SAMPLE_RATE * DURATION):
    time = i / SAMPLE_RATE
    sample = round(get_sample(time) * MAX_SAMPLE_VALUE)

    if sample == MAX_SAMPLE_VALUE:
        sample -= 1

    samples.extend(sample.to_bytes(SAMPLE_WIDTH, byteorder, signed=True))

with wave.open('output.wav', 'wb') as output:
    output.setnchannels(NUMBER_OF_CHANNELS)
    output.setsampwidth(SAMPLE_WIDTH)
    output.setframerate(SAMPLE_RATE)
    output.setnframes(NUMBER_OF_CHANNELS * SAMPLE_RATE * DURATION)
    output.setcomptype('NONE', 'not compressed')

    output.writeframes(samples)
</code>```

答:
There are two problems.

Aliasing

A signal sampled at a rate fS can only be reconstructed correctly if it contains no components at frequencies higher than fS/2. Any signal components with frequencies outside the interval [0, fS/2] get folded into that interval when reconstructing the signal from the samples (e.g. by your soundcard).

This is called aliasing and can be avoided by either low-pass filtering a signal before sampling it or by making the sampling rate sufficiently high.

In your case, if you want to sample a sine wave with a frequency of 28160 Hz, the sampling rate must be at least 56320 Hz.

Incorrect computation of phase

```<code>def get_sample(time):
    frequency = a10 / 2.0 ** time
    return sin(pi2 * frequency * time)
</code>```

The phase is the argument to the sin function. Its derivative with respect to time is the instantaneous frequency which is the pitch of the tone we hear.

In this case, if we plug frequency = a10 / 2.0 ** time into pi2 * frequency * time, the phase is

```<code>pi2 * (a10 / 2.0 ** time) * time
</code>```

or in symbolic notation:

φ = 2π · A10 · 2−t · t

The derivative of this is then

f = 2π · A10 · 2−t · (1 − ln 2 · t),

and not 2π · A10 · 2−t as you had expected.

This is a plot of the actual frequency sweep that you get using your method (taking into account aliasing, notice how the curve is reflected at the 0 Hz and 24000 Hz lines), vs. what you had intended:

And here is the same plot with logarithmic frequency scale, which is how we perceive frequencies as pitches:

Solution

You get the correct result by making the following changes:

Use a high enough value for SAMPLE_RATE.

Don't calculate the sample directly from the given time, instead maintain a phase value which is incremented at a rate proportional to the intended frequency (wrap it at 2π so that it doesn't grow out of bounds), by replacing

```<code>def get_sample(time):
    frequency = a10 / 2.0 ** time
    return sin(pi2 * frequency * time)

[…]

for i in range(SAMPLE_RATE * DURATION):
    time = i / SAMPLE_RATE
    sample = round(get_sample(time) * MAX_SAMPLE_VALUE)
</code>```

by

```<code>def get_frequency(time):
    frequency = a10 / 2.0 ** time
    return frequency

[…]

phase = 0
for i in range(SAMPLE_RATE * DURATION):
    time = i / SAMPLE_RATE
    f = get_frequency(time)
    phase = (phase + pi2 * f / SAMPLE_RATE) % pi2
    sample = round(sin(phase) * MAX_SAMPLE_VALUE)
</code>```

Body:
I'm trying to create a simple WAV file that emits a changing pitch. However, the waveform that gets written to the file does not correspond to the data that get_sample returns.

I expect the tone to change in a logarithmic fashion, starting at A10 (28,160 Hz) and to end at A0 (27.5 Hz). As each second passes, the pitch should smoothly drop by one octave.

What is actually happening is difficult to explain. The tone changes, but in unintended ways. And what makes my problem more peculiar is that lowering the sample rate worsens the problem. In this output at 48,000 samples per second, the pitch rapidly drops and then rises again just to slowly fall once more. In this output at 3,000 samples per second, a similar effect happens, but it is more extreme and chaotic. What am I doing wrongly?

from math import pi, sin
from sys import byteorder
import wave

def get_sample(time):
    frequency = a10 / 2.0 ** time
    # print('{:.15f} {:.15f} {:.15f}'.format(time, frequency, sin(pi2 * frequency * time)))
    return sin(pi2 * frequency * time)

pi2 = 2 * pi
a10 = 28160.0

NUMBER_OF_CHANNELS = 1
SAMPLE_RATE = 48000  # samples per second
SAMPLE_WIDTH = 3  # bytes
DURATION = 10  # seconds

MAX_SAMPLE_VALUE = 2 ** (SAMPLE_WIDTH * 8 - 1)

samples = bytearray()

for i in range(SAMPLE_RATE * DURATION):
    time = i / SAMPLE_RATE
    sample = round(get_sample(time) * MAX_SAMPLE_VALUE)

    if sample == MAX_SAMPLE_VALUE:
        sample -= 1

    samples.extend(sample.to_bytes(SAMPLE_WIDTH, byteorder, signed=True))

with wave.open('output.wav', 'wb') as output:
    output.setnchannels(NUMBER_OF_CHANNELS)
    output.setsampwidth(SAMPLE_WIDTH)
    output.setframerate(SAMPLE_RATE)
    output.setnframes(NUMBER_OF_CHANNELS * SAMPLE_RATE * DURATION)
    output.setcomptype('NONE', 'not compressed')

    output.writeframes(samples)

Body:
There are two problems.

Aliasing

A signal sampled at a rate fS can only be reconstructed correctly if it contains no components at frequencies higher than fS/2. Any signal components with frequencies outside the interval [0, fS/2] get folded into that interval when reconstructing the signal from the samples (e.g. by your soundcard).

This is called aliasing and can be avoided by either low-pass filtering a signal before sampling it or by making the sampling rate sufficiently high.

In your case, if you want to sample a sine wave with a frequency of 28160 Hz, the sampling rate must be at least 56320 Hz.

Incorrect computation of phase

def get_sample(time):
    frequency = a10 / 2.0 ** time
    return sin(pi2 * frequency * time)

The phase is the argument to the sin function. Its derivative with respect to time is the instantaneous frequency which is the pitch of the tone we hear.

In this case, if we plug frequency = a10 / 2.0 ** time into pi2 * frequency * time, the phase is

pi2 * (a10 / 2.0 ** time) * time

or in symbolic notation:

φ = 2π · A10 · 2−t · t

The derivative of this is then

f = 2π · A10 · 2−t · (1 − ln 2 · t),

and not 2π · A10 · 2−t as you had expected.

This is a plot of the actual frequency sweep that you get using your method (taking into account aliasing, notice how the curve is reflected at the 0 Hz and 24000 Hz lines), vs. what you had intended:

And here is the same plot with logarithmic frequency scale, which is how we perceive frequencies as pitches:

Solution

You get the correct result by making the following changes:

Use a high enough value for SAMPLE_RATE.

Don't calculate the sample directly from the given time, instead maintain a phase value which is incremented at a rate proportional to the intended frequency (wrap it at 2π so that it doesn't grow out of bounds), by replacing

def get_sample(time):
    frequency = a10 / 2.0 ** time
    return sin(pi2 * frequency * time)

[…]

for i in range(SAMPLE_RATE * DURATION):
    time = i / SAMPLE_RATE
    sample = round(get_sample(time) * MAX_SAMPLE_VALUE)

by

def get_frequency(time):
    frequency = a10 / 2.0 ** time
    return frequency

[…]

phase = 0
for i in range(SAMPLE_RATE * DURATION):
    time = i / SAMPLE_RATE
    f = get_frequency(time)
    phase = (phase + pi2 * f / SAMPLE_RATE) % pi2
    sample = round(sin(phase) * MAX_SAMPLE_VALUE)