问:
Why can't I import * these Javascript Files?
I'm trying to import these files inside the perimeters folder

basePerimeter.js

byePerimeter.js

secretPerimeter.js

my import code:

```<code>import * as perimeters from '../perimeters'
</code>```

basePerimeter.js

```<code>import { Perimeter } from 'vue-kindergarten';

export default class BasePerimeter extends Perimeter {
  isAdmin() {
    return this.child && this.child.role === 'admin';
  }
}
</code>```

byePerimeter.js

```<code>import basePerimeter from './basePerimeter';

export default new basePerimeter({
  purpose: 'bye',
  govern: {
    'can route': () => true,
    'can viewParagraph': function () {
      return this.isAdmin();
    },
  },
});
</code>```

secretPerimeter.js

```<code>import basePerimeter from './basePerimeter';

export default new basePerimeter({
  purpose: 'secret',
  govern: {
    'can route': function () {
      return this.isAdmin();
    },
  },
});
</code>```

but if I import it individually, it works.

Like this:

```<code>import basePerimeter from '../perimeters/basePerimeter'
</code>```

I need to import via * because of this code:

```<code>router.beforeEach((to, from, next) => {
  const perimeter = perimeters[`${to.name}Perimeter`];
  if (perimeter) {
    const sandbox = createSandbox(child(store), {
      perimeters: [
        perimeter,
      ],
    });
    if (!sandbox.isAllowed('route')) {
      return next('/');
    }
  }
  return next();
});
</code>```

Why is it throwing this error:

```<code>ERROR in ./src/router/index.js
Module not found: Error: Can't resolve '../perimeters' in 'E:\my\vue\instance\src\router'
 @ ./src/router/index.js 13:0-44
 @ ./src/main.js
 @ multi ./build/dev-client ./src/main.js
</code>```

答:
I Don't know what's happening here but adding an index.js file and importing the files I needed solved my problem.

index.js

```<code>import byePerimeter from './byePerimeter'
import secretPerimeter from './secretPerimeter'

export {
    byePerimeter,
    secretPerimeter
}
</code>```

Body:
I'm trying to import these files inside the perimeters folder

basePerimeter.js

byePerimeter.js

secretPerimeter.js

my import code:

import * as perimeters from '../perimeters'

basePerimeter.js

import { Perimeter } from 'vue-kindergarten';

export default class BasePerimeter extends Perimeter {
  isAdmin() {
    return this.child && this.child.role === 'admin';
  }
}

byePerimeter.js

import basePerimeter from './basePerimeter';

export default new basePerimeter({
  purpose: 'bye',
  govern: {
    'can route': () => true,
    'can viewParagraph': function () {
      return this.isAdmin();
    },
  },
});

secretPerimeter.js

import basePerimeter from './basePerimeter';

export default new basePerimeter({
  purpose: 'secret',
  govern: {
    'can route': function () {
      return this.isAdmin();
    },
  },
});

but if I import it individually, it works.

Like this:

import basePerimeter from '../perimeters/basePerimeter'

I need to import via * because of this code:

router.beforeEach((to, from, next) => {
  const perimeter = perimeters[`${to.name}Perimeter`];
  if (perimeter) {
    const sandbox = createSandbox(child(store), {
      perimeters: [
        perimeter,
      ],
    });
    if (!sandbox.isAllowed('route')) {
      return next('/');
    }
  }
  return next();
});

Why is it throwing this error:

ERROR in ./src/router/index.js
Module not found: Error: Can't resolve '../perimeters' in 'E:\my\vue\instance\src\router'
 @ ./src/router/index.js 13:0-44
 @ ./src/main.js
 @ multi ./build/dev-client ./src/main.js

Body:
I Don't know what's happening here but adding an index.js file and importing the files I needed solved my problem.

index.js

import byePerimeter from './byePerimeter'
import secretPerimeter from './secretPerimeter'

export {
    byePerimeter,
    secretPerimeter
}


来源: stackexchange

问:
how make ng-model work separately inside array of objects?
I'm stuck with some concept while realizing checkbox system.

I've got an array of objects, it looks like this:

```<code>this.columnsGroups = [
        {
           id: 1,
           title: 'General requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        },
        {
           id: 2,
           title: 'Technical Requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        },
        {
           id: 3,
           title: 'Popular requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        },
        {
           id: 4,
           title: 'Misc requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        }
    ]
</code>```

What I'm trying to do is to parse this array into html template with checkboxes.
The structure of the template consists of: parent checkbox

```<code><div class="ln-select-columns-content" ng-if="currentTab.isAdvancedSearch" ng-repeat="group in ctrl.columnsGroups" ng-style="{'width':'25%'}">
  <div class="ln-select-column-row">
    <label>
      <span class="ln-checkbox">
                      <input type="checkbox" ng-model="allChecked" ng-checked="allSelected" ng-click="ctrl.toggleSelectAllAttributes()"/>
                      <span class="ln-bg"></span>
      </span>
      <div class="ln-select-column-name"><b>{{group.title}}:</b></div>
    </label>
    <div ng-repeat="column in group.props" class="ln-select-column-row">
      <label>
        <span class="ln-checkbox">
                                <input type="checkbox" ng-model="column.visible" />
                                <span class="ln-bg"></span>
        </span>
        <span class="ln-select-column-name">{{column.title}}</span>
      </label>
    </div>
  </div>
</div>
</code>```

Literally, the template view looks like this:
view screenshot

Now, the problem is: when I'm writing a realisation for checkboxing all the child checkboxes with parent checkbox for each column, ng-model=allChecked checks all the child checkboxes from any parent checkbox in the container.

What would be the best way to do parent checkboxing, isolated from the sibling parent checkboxes?
Or maybe the array of objects is not correctly structured?

答:
You have to modify your JSON object a little bit by adding a selected property for tracking ng-model of each checkbox. Then you can write methods in your $scope to trigger on ng-change of each checkbox and toggle checkboxes by modifying JSON object.

For complete solution please see below snippet.

angular.module('app', []).controller('HomeCtrl', function($scope) {
  $scope.toggleGroup = function(group) {
    if (group.selected) {
      group.props.forEach(function (prop) {
        prop.selected = true
      })
    } else {
       group.props.forEach(function (prop) {
        prop.selected = false
      })
    }
  }

  $scope.selectProp = function(group) {
    var allSelected = true;
    group.props.forEach(function (prop) {
      allSelected = allSelected && prop.selected;
    })
    group.selected = allSelected;
  }

  $scope.columnsGroups = [
        {
           id: 1,
           title: 'General requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        },
        {
           id: 2,
           title: 'Technical Requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        },
        {
           id: 3,
           title: 'Popular requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        },
        {
           id: 4,
           title: 'Misc requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        }
    ]

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="HomeCtrl">
    <div ng-repeat="group in columnsGroups">
      <input type="checkbox" ng-model="group.selected" ng-change="toggleGroup(group)"/> {{group.title}}
      <ul>
        <li ng-repeat="prop in group.props">
          <input ng-change="selectProp(group)" ng-model="prop.selected" type="checkbox"/> {{prop.title}}
        </li>
      </ul>
    </div>
    ```
      {{columnsGroups | json}}
    ```
  </div>
  <script src="script.js"></script>
</body></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm stuck with some concept while realizing checkbox system.

I've got an array of objects, it looks like this:

this.columnsGroups = [
        {
           id: 1,
           title: 'General requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        },
        {
           id: 2,
           title: 'Technical Requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        },
        {
           id: 3,
           title: 'Popular requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        },
        {
           id: 4,
           title: 'Misc requests',
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined
              }
           ]
        }
    ]

What I'm trying to do is to parse this array into html template with checkboxes.
The structure of the template consists of: parent checkbox

                      <input type="checkbox" ng-model="allChecked" ng-checked="allSelected" ng-click="ctrl.toggleSelectAllAttributes()"/>

{{group.title}}:

                                <input type="checkbox" ng-model="column.visible" />

        {{column.title}}

Literally, the template view looks like this:
view screenshot

Now, the problem is: when I'm writing a realisation for checkboxing all the child checkboxes with parent checkbox for each column, ng-model=allChecked checks all the child checkboxes from any parent checkbox in the container.

What would be the best way to do parent checkboxing, isolated from the sibling parent checkboxes?
Or maybe the array of objects is not correctly structured?

Body:
You have to modify your JSON object a little bit by adding a selected property for tracking ng-model of each checkbox. Then you can write methods in your $scope to trigger on ng-change of each checkbox and toggle checkboxes by modifying JSON object.

For complete solution please see below snippet.

angular.module('app', []).controller('HomeCtrl', function($scope) {
  $scope.toggleGroup = function(group) {
    if (group.selected) {
      group.props.forEach(function (prop) {
        prop.selected = true
      })
    } else {
       group.props.forEach(function (prop) {
        prop.selected = false
      })
    }
  }

  $scope.selectProp = function(group) {
    var allSelected = true;
    group.props.forEach(function (prop) {
      allSelected = allSelected && prop.selected;
    })
    group.selected = allSelected;
  }

  $scope.columnsGroups = [
        {
           id: 1,
           title: 'General requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        },
        {
           id: 2,
           title: 'Technical Requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        },
        {
           id: 3,
           title: 'Popular requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        },
        {
           id: 4,
           title: 'Misc requests',
           selected: false,
           props: [
              {
                title: 'Search level',
                filterType: 'entry',
                visible: undefined,
                selected: false
              },
              {
                title: 'ID',
                filterType: 'number',
                visible: undefined,
                selected: false
              }
           ]
        }
    ]

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="HomeCtrl">
    <div ng-repeat="group in columnsGroups">
      <input type="checkbox" ng-model="group.selected" ng-change="toggleGroup(group)"/> {{group.title}}
      <ul>
        <li ng-repeat="prop in group.props">
          <input ng-change="selectProp(group)" ng-model="prop.selected" type="checkbox"/> {{prop.title}}
        </li>
      </ul>
    </div>
    <pre>
      {{columnsGroups | json}}
    </pre>
  </div>
  <script src="script.js"></script>
</body>


问:
C++11 Magic Statics Workaround in Visual Studio 2012
I have some objects defined as global, which means their constructor are entered before program start or under DllMain(). This causes some issues, and that is why I want to move them to local static.

Our main project are mainly under Visual Studio 2012. According to the these post.

“Magic static” singleton crashing when referenced in static destruction phase of another translation unit"

Support For C++11/14/17 Features (Modern C++)

The Magic Statics is not implemented in Visual Studio 2012 (until VS 2015). So the local static variable initialization is not automatically protected from concurrent access by compiler.

What is a suitable workaround or solution for this case?

Here is what I tried:

Add a lock to protect. But if the variable initialized before the function is entered, my lock may be useless...

```<code>// data object
struct Cat
{
    Cat()
    {
        std::cout << __FUNCTION__ <<  "\n";
    }
};

// lock mutex for singleton getter
static std::mutex getcat_m;

// singleton getter
Cat& GetCat(){
    std::cout << __FUNCTION__ <<  " In\n";

    std::lock_guard<std::mutex> lk(getcat_m);
    static Cat cat;

    std::cout << __FUNCTION__ <<  " Out\n";
    return cat;
}

int main(int argc, char* argv[])
{
    std::cout << __FUNCTION__ <<  " In\n";
    Cat& cat = GetCat();
    std::cout << __FUNCTION__ <<  " Out\n";

    std::cin.ignore();
    return 0;
}
</code>```

It actually shows as expected. The constructor is called after function is entered.

```<code>main In
GetCat In
Cat::Cat
GetCat Out
main Out
</code>```

But I am not sure whether this is a suitable solution.

答:
Thanks to A. A in comment for the link 18.2.4 Use std::call_once rather than the Double-Checked Locking pattern.

I referenced the example from the Guildline, and rewrite my singleton getter code as the following.

```<code>// Cat.cpp
static std::once_flag once_Cat;
static Cat* gpCat = nullptr;
void init_Cat() { gpCat = new Cat(); }

Cat& GetCat() {
    std::call_once(once_Cat, init_Cat);
    return *gpCat;
}
</code>```

Body:
I have some objects defined as global, which means their constructor are entered before program start or under DllMain(). This causes some issues, and that is why I want to move them to local static.

Our main project are mainly under Visual Studio 2012. According to the these post.

“Magic static” singleton crashing when referenced in static destruction phase of another translation unit"

Support For C++11/14/17 Features (Modern C++)

The Magic Statics is not implemented in Visual Studio 2012 (until VS 2015). So the local static variable initialization is not automatically protected from concurrent access by compiler.

What is a suitable workaround or solution for this case?

Here is what I tried:

Add a lock to protect. But if the variable initialized before the function is entered, my lock may be useless...

// data object
struct Cat
{
    Cat()
    {
        std::cout << __FUNCTION__ <<  "\n";
    }
};

// lock mutex for singleton getter
static std::mutex getcat_m;

// singleton getter
Cat& GetCat(){
    std::cout << __FUNCTION__ <<  " In\n";

    std::lock_guard<std::mutex> lk(getcat_m);
    static Cat cat;

    std::cout << __FUNCTION__ <<  " Out\n";
    return cat;
}

int main(int argc, char* argv[])
{
    std::cout << __FUNCTION__ <<  " In\n";
    Cat& cat = GetCat();
    std::cout << __FUNCTION__ <<  " Out\n";

    std::cin.ignore();
    return 0;
}

It actually shows as expected. The constructor is called after function is entered.

main In
GetCat In
Cat::Cat
GetCat Out
main Out

But I am not sure whether this is a suitable solution.

Body:
Thanks to A. A in comment for the link 18.2.4 Use std::call_once rather than the Double-Checked Locking pattern.

I referenced the example from the Guildline, and rewrite my singleton getter code as the following.

// Cat.cpp
static std::once_flag once_Cat;
static Cat* gpCat = nullptr;
void init_Cat() { gpCat = new Cat(); }

Cat& GetCat() {
    std::call_once(once_Cat, init_Cat);
    return *gpCat;
}


问:
Trouble using plugin with Ionic 3
https://github.com/blinkmobile/cordova-plugin-sketch

i found this Little plugin and want to use it in my Ionic 3 app.
Sadly i have Trouble using it, because after succesfully installing it with

```<code>cordova plugin add https://github.com/blinkmobile/cordova-plugin-sketch.git
</code>```

VSCode says all the time: "Property 'sketch' does not exist on type 'Navigator'."

Is this maybe not compatible with Ionic or am I hopefully just missing something?

Thanks

答:
You can use window.navigator, should declare window first.

Try with:

```<code>declare const window: any;

...

window.navigator.sketch
</code>```

Title: Trouble using plugin with Ionic 3

Body:
https://github.com/blinkmobile/cordova-plugin-sketch

i found this Little plugin and want to use it in my Ionic 3 app.
Sadly i have Trouble using it, because after succesfully installing it with

cordova plugin add https://github.com/blinkmobile/cordova-plugin-sketch.git

VSCode says all the time: "Property 'sketch' does not exist on type 'Navigator'."

Is this maybe not compatible with Ionic or am I hopefully just missing something?

Thanks

Body:
You can use window.navigator, should declare window first.

Try with:

declare const window: any;

...

window.navigator.sketch


问:
slicing error in numpy array
I am trying to run the following code

```<code>fs = 1000
data = np.loadtxt("trainingdataset.txt", delimiter=",")
data1 = data[:,2]
data2 = data1.astype(int)
X,Y = data2['521']
</code>```

but it gets me the following error

```<code>Traceback (most recent call last):
  File "C:\Users\hadeer.elziaat\Desktop\testspec.py", line 58, in <module>
    X,Y = data2['521']
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

my dataset

```<code>1,4,6,10
2,100,125,10
3,100,7216,254
4,100,527,263
5,100,954,13
6,100,954,23
</code>```

答:
You're using the string '521' rather than the number 521 for indexing. Try X,Y = data2[521] instead.

If you are only given the string, you could cast it to an int first: X,Y = data2[int('521')], but this might result in some errors and/or unexpected behaviour.

Next problem, you are requiring two variable, one for X and one for Y, yet the data2[521] selection only provides you with a single variable (the number in the 3rd column, 522nd row).

Title: slicing error in numpy array

Body:
I am trying to run the following code

fs = 1000
data = np.loadtxt("trainingdataset.txt", delimiter=",")
data1 = data[:,2]
data2 = data1.astype(int)
X,Y = data2['521']

but it gets me the following error

Traceback (most recent call last):
  File "C:\Users\hadeer.elziaat\Desktop\testspec.py", line 58, in <module>
    X,Y = data2['521']
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

my dataset

1,4,6,10
2,100,125,10
3,100,7216,254
4,100,527,263
5,100,954,13
6,100,954,23


问:
Why does CSS padding increase size of element?
I am trying to give my div and textarea some padding. When I do this, it increases the size of the element, instead of shrinking the content area inside of it. Is there any way to achieve what I am trying to do?</p>

答:
It depends on the browser and it's implementation of the box model. What you are experiencing is the correct behavior.

IE traditionally got it wrong: http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
pandas.DataFrame.loc gives output for a label twice and mentions Name and dtype
I have a pandas DataFrame indexed by item_id (numbers), I tried to access an item at a location by using DataFrame.loc[str(item_id),word] where word is the label of the column I want to access. Word is a string:

```<code>print(output.loc[str(df.loc[i,'item_id']),word])
</code>```

The output I get is the following:

```<code>hu    0.0
hu    0.0
Name: 17349826, dtype: float64
</code>```

here word has value hu and item_id had 17349826.

I want the output as just:

```<code>0.0
</code>```

答:
I think you need select fist value of Series by iat for scalar output:

```<code>print(output.loc[str(df.loc[i,'item_id']),word]).iat[0]
</code>```

And reason for duplicated output is duplicates in index values.

Body:
I have a pandas DataFrame indexed by item_id (numbers), I tried to access an item at a location by using DataFrame.loc[str(item_id),word] where word is the label of the column I want to access. Word is a string:

print(output.loc[str(df.loc[i,'item_id']),word])

The output I get is the following:

hu    0.0
hu    0.0
Name: 17349826, dtype: float64

here word has value hu and item_id had 17349826.

I want the output as just:

0.0

Body:
I think you need select fist value of Series by iat for scalar output:

print(output.loc[str(df.loc[i,'item_id']),word]).iat[0]

And reason for duplicated output is duplicates in index values.


问:
Declare array of lambdas in Java
I'd like to create an array of lambda. The problem is that the lambda could be different from each other. Example:

```<code>private interface I0 {
    int interface0(int a, int b);
}

private interface I1 {
    int interface1(double d);
}
</code>```

Now, how can I declare a list which can contain both I0 and I1?

```<code>List<Object> test = Arrays.asList(
        (int a, int b) -> a + b,
        (double d) -> d * 2
);
</code>```

Obviously Object does not work.

答:
You could make your interfaces use vararg typing:</p>

```<code>public class NaryFunctionTest {

    interface NaryFunction<R extends Number> {
        R run(R... args);
    }

    @Test
    public void test() {
        NaryFunction<Integer> f1 = (Integer[] o) -> o[0] + o[1];
        NaryFunction<Double> f2 = (Double[] o) -> o[0] *2;
        List<NaryFunction<?>> test = Arrays.asList(
            f1,
            f2
        );
    }
}
</code>```

Title: Declare array of lambdas in Java

Body:
I'd like to create an array of lambda. The problem is that the lambda could be different from each other. Example:

private interface I0 {
    int interface0(int a, int b);
}

private interface I1 {
    int interface1(double d);
}

Now, how can I declare a list which can contain both I0 and I1?

List<Object> test = Arrays.asList(
        (int a, int b) -> a + b,
        (double d) -> d * 2
);

Obviously Object does not work.

Body:
You could make your interfaces use vararg typing:

public class NaryFunctionTest {

    interface NaryFunction<R extends Number> {
        R run(R... args);
    }

    @Test
    public void test() {
        NaryFunction<Integer> f1 = (Integer[] o) -> o[0] + o[1];
        NaryFunction<Double> f2 = (Double[] o) -> o[0] *2;
        List<NaryFunction<?>> test = Arrays.asList(
            f1,
            f2
        );
    }
}


问:
ASP.NET control rendering
I'm wondering how the HyperLink control used in the following code example renderes to html displaying the text contained in the welcome.Text variable.

The same thing for the link to the sign-up page.

Since I assume this script doesn't run every time a page request is made, I also wonder in which cases this script gets run in the sample application.

<asp:HyperLink id="welcome" runat="server" maintainstate="false">
</asp:HyperLink>
```

Edit.

To be more precise, how does the HyperLink control know how to render the variable welcome.Text?

Is it the case that when a control is declared, the ControlName.Text, if declared, is always rendered?

答:
Page_Load should run every time the page is requested. Your HyperLink will be rendered as please sign in! for unauthenticated user and where as Welcome LoginUserName for authenticated login.
Is it what you are looking for. If not please describe more details.

Title: ASP.NET control rendering

Body:
I'm wondering how the HyperLink control used in the following code example renderes to html displaying the text contained in the welcome.Text variable.

The same thing for the link to the sign-up page.

Since I assume this script doesn't run every time a page request is made, I also wonder in which cases this script gets run in the sample application.

<asp:HyperLink id="welcome" runat="server" maintainstate="false">
</asp:HyperLink>

Edit.

To be more precise, how does the HyperLink control know how to render the variable welcome.Text?

Is it the case that when a control is declared, the ControlName.Text, if declared, is always rendered?

Body:
Page_Load should run every time the page is requested. Your HyperLink will be rendered as <a href="signin.aspx">please sign in!</a> for unauthenticated user and where as <a href="">Welcome LoginUserName</a> for authenticated login.
Is it what you are looking for. If not please describe more details.


问:
What is the fastest way to get the value of e?
What is the most optimised algorithm which finds the value of e with moderate accuracy?

I am looking for a comparison between optimised approaches giving more importance to speed than high precision.

Edit: By moderate accuracy I mean upto 6-7 decimal places.
But if there is a HUGE difference in speed, then I can settle with 4-5 places.

答:
basic datatype

As mentioned in the comments 6-7 decimal places is too small accuracy to do this by an algorithm. Instead use a constant which is the fastest way anyway for this.

```<code>const double e=2.7182818284590452353602874713527;
</code>```

If FPU is involved the constant is usually stored there too... Also having single constant occupies much less space than a function that computes it ...

finite accuracy

Only once bignums are involved then has any merit to use algorithm to compute e. The algo depends on target accuracy. Again for smaller accuracies are predefined constants used:

```<code>e=2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170189
</code>```

but usually in hex format for faster and more precise manipulation:

```<code>e=2.B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF324E7738926CFBE5F4BF8D8D8C31D763DA06C80ABB1185EB4F7C7B5757F5958490CFD47D7C19BB42158D9554F7B46BCED55C4D79FD5F24D6613C31C3839A2DDF8A9A276BCFBFA1C877C56284DAB79CD4C2B3293D20E9E5EAF02AC60ACC93ECEBh
</code>```

For limited/finite accuracy and best speed is the PSLQ algorithm best. My understanding is that it is algorithm to find relation between real number and integer iterations.

here is my favourite PSLQ up to 800 digits of Pi PSLQ example

arbitrary accuracy

For arbitrary or "fixed" precision you need algorithm that is with variable precision. This is what I use in my arbnum class:

```<code>e=(1+1/x)^x where x -> +infinity
</code>```

If you chose x as power of 2 realize that x is just single set bit of the number and 1/x has predictable bit-width. So the e will be obtained with single division and pow. Here an example:

arbnum arithmetics_e()          // e computation min(_arbnum_max_a,arbnum_max_b)*5 decimals
    {                           // e=(1+1/x)^x  ... x -> +inf
    int i; arbnum c,x;
    i=_arbnum_bits_a; if (i>_arbnum_bits_b) i=_arbnum_bits_b; i>>=1;
    c.zero(); c.bitset(_arbnum_bits_b-i); x.one(); x/=c; c++;
    for (;!x.bitget(_arbnum_bits_b);x>>=1) c*=c;    //=pow(c,x);
    return c;
    }
```

Where _arbnum_bits_a,_arbnum_bits_b is the number of bits before and after decimal point in binary. So it break down to some bit operations, one bignum division and single power by squaring. Beware that multiplication and division is not that simple with bignums and usually involves Karatsuba or worse ...

There are also polynomial approaches out there that does not require bignum arithmetics similar to compute Pi. The idea is to compute chunk of binary bits per iteration without affecting the previously computed bits (too much). They should be faster but as usual for any optimizations that depends on the implementation and HW it runs on.

Body:
basic datatype

As mentioned in the comments 6-7 decimal places is too small accuracy to do this by an algorithm. Instead use a constant which is the fastest way anyway for this.

const double e=2.7182818284590452353602874713527;

If FPU is involved the constant is usually stored there too... Also having single constant occupies much less space than a function that computes it ...

finite accuracy

Only once bignums are involved then has any merit to use algorithm to compute e. The algo depends on target accuracy. Again for smaller accuracies are predefined constants used:

e=2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170189

but usually in hex format for faster and more precise manipulation:

e=2.B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF324E7738926CFBE5F4BF8D8D8C31D763DA06C80ABB1185EB4F7C7B5757F5958490CFD47D7C19BB42158D9554F7B46BCED55C4D79FD5F24D6613C31C3839A2DDF8A9A276BCFBFA1C877C56284DAB79CD4C2B3293D20E9E5EAF02AC60ACC93ECEBh

For limited/finite accuracy and best speed is the PSLQ algorithm best. My understanding is that it is algorithm to find relation between real number and integer iterations.

here is my favourite PSLQ up to 800 digits of Pi PSLQ example

arbitrary accuracy

For arbitrary or "fixed" precision you need algorithm that is with variable precision. This is what I use in my arbnum class:

e=(1+1/x)^x where x -> +infinity

If you chose x as power of 2 realize that x is just single set bit of the number and 1/x has predictable bit-width. So the e will be obtained with single division and pow. Here an example:

arbnum arithmetics_e()          // e computation min(_arbnum_max_a,arbnum_max_b)*5 decimals
    {                           // e=(1+1/x)^x  ... x -> +inf
    int i; arbnum c,x;
    i=_arbnum_bits_a; if (i>_arbnum_bits_b) i=_arbnum_bits_b; i>>=1;
    c.zero(); c.bitset(_arbnum_bits_b-i); x.one(); x/=c; c++;
    for (;!x.bitget(_arbnum_bits_b);x>>=1) c*=c;    //=pow(c,x);
    return c;
    }

Where _arbnum_bits_a,_arbnum_bits_b is the number of bits before and after decimal point in binary. So it break down to some bit operations, one bignum division and single power by squaring. Beware that multiplication and division is not that simple with bignums and usually involves Karatsuba or worse ...

There are also polynomial approaches out there that does not require bignum arithmetics similar to compute Pi. The idea is to compute chunk of binary bits per iteration without affecting the previously computed bits (too much). They should be faster but as usual for any optimizations that depends on the implementation and HW it runs on.


问:
How to remove EXIF (camera) data from image with carrierwave?
Does anybody know?
With paperclip there was a special config command.

Removing camera data from image keeps 25-30 Kb per file. It's very sensitive if we make a lot of versions (thumb, small...). In small images the actual size of file without this information can be 5-6 times less.

Thanks in advance!

答:
Carrierwave is very flexible and it's possible to make own processors. With MiniMagick we can use a bunch of options of mogrify command-line utility, one of them is strip:

```<code>class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  version :small do
    process :resize_to_fill => [100, 100]
    process :strip
  end

  def strip
    manipulate! do |img|
      img.strip
      img = yield(img) if block_given?
      img
    end
  end
end
</code>```

Body:
Carrierwave is very flexible and it's possible to make own processors. With MiniMagick we can use a bunch of options of mogrify command-line utility, one of them is strip:

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  version :small do
    process :resize_to_fill => [100, 100]
    process :strip
  end

  def strip
    manipulate! do |img|
      img.strip
      img = yield(img) if block_given?
      img
    end
  end
end


问:
Neural network specified with tf.layers inserting undesired reshape operations
This simple neural network defined in python:

```<code>input_layer = tf.placeholder(tf.float32, shape=[1, 1, 8000, 1], name='input_layer')

# Convolutional Layer
conv = tf.layers.conv2d(
        inputs=input_layer,
        filters=32,
        kernel_size=[1,11],
        padding="same",
        strides=1,
        activation=tf.nn.relu)

# Output layer
logits = tf.layers.dense(inputs=conv, units=5, name='logit')
</code>```

Results the following graph topology:

```<code>0 input_layer Placeholder
1 conv2d/kernel/Initializer/random_uniform/shape Const
2 conv2d/kernel/Initializer/random_uniform/min Const
3 conv2d/kernel/Initializer/random_uniform/max Const
4 conv2d/kernel/Initializer/random_uniform/RandomUniform RandomUniform
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/shape
5 conv2d/kernel/Initializer/random_uniform/sub Sub
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/max
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform/min
6 conv2d/kernel/Initializer/random_uniform/mul Mul
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/RandomUniform
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform/sub
7 conv2d/kernel/Initializer/random_uniform Add
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/mul
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform/min
8 conv2d/kernel VariableV2
9 conv2d/kernel/Assign Assign
└─── Input0 ─ conv2d/kernel
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform
10 conv2d/kernel/read Identity
└─── Input0 ─ conv2d/kernel
11 conv2d/bias/Initializer/zeros Const
12 conv2d/bias VariableV2
13 conv2d/bias/Assign Assign
└─── Input0 ─ conv2d/bias
└─── Input1 ─ conv2d/bias/Initializer/zeros
14 conv2d/bias/read Identity
└─── Input0 ─ conv2d/bias
15 conv2d/convolution/Shape Const
16 conv2d/convolution/dilation_rate Const
17 conv2d/convolution Conv2D
└─── Input0 ─ input_layer
└─── Input1 ─ conv2d/kernel/read
18 conv2d/BiasAdd BiasAdd
└─── Input0 ─ conv2d/convolution
└─── Input1 ─ conv2d/bias/read
19 conv2d/Relu Relu
└─── Input0 ─ conv2d/BiasAdd
20 logit/kernel/Initializer/random_uniform/shape Const
21 logit/kernel/Initializer/random_uniform/min Const
22 logit/kernel/Initializer/random_uniform/max Const
23 logit/kernel/Initializer/random_uniform/RandomUniform RandomUniform
└─── Input0 ─ logit/kernel/Initializer/random_uniform/shape
24 logit/kernel/Initializer/random_uniform/sub Sub
└─── Input0 ─ logit/kernel/Initializer/random_uniform/max
└─── Input1 ─ logit/kernel/Initializer/random_uniform/min
25 logit/kernel/Initializer/random_uniform/mul Mul
└─── Input0 ─ logit/kernel/Initializer/random_uniform/RandomUniform
└─── Input1 ─ logit/kernel/Initializer/random_uniform/sub
26 logit/kernel/Initializer/random_uniform Add
└─── Input0 ─ logit/kernel/Initializer/random_uniform/mul
└─── Input1 ─ logit/kernel/Initializer/random_uniform/min
27 logit/kernel VariableV2
28 logit/kernel/Assign Assign
└─── Input0 ─ logit/kernel
└─── Input1 ─ logit/kernel/Initializer/random_uniform
29 logit/kernel/read Identity
└─── Input0 ─ logit/kernel
30 logit/bias/Initializer/zeros Const
31 logit/bias VariableV2
32 logit/bias/Assign Assign
└─── Input0 ─ logit/bias
└─── Input1 ─ logit/bias/Initializer/zeros
33 logit/bias/read Identity
└─── Input0 ─ logit/bias
34 logit/Tensordot/transpose/perm Const
35 logit/Tensordot/transpose Transpose
└─── Input0 ─ conv2d/Relu
└─── Input1 ─ logit/Tensordot/transpose/perm
36 logit/Tensordot/Reshape/shape Const
37 logit/Tensordot/Reshape Reshape
└─── Input0 ─ logit/Tensordot/transpose
└─── Input1 ─ logit/Tensordot/Reshape/shape
38 logit/Tensordot/transpose_1/perm Const
39 logit/Tensordot/transpose_1 Transpose
└─── Input0 ─ logit/kernel/read
└─── Input1 ─ logit/Tensordot/transpose_1/perm
40 logit/Tensordot/Reshape_1/shape Const
41 logit/Tensordot/Reshape_1 Reshape
└─── Input0 ─ logit/Tensordot/transpose_1
└─── Input1 ─ logit/Tensordot/Reshape_1/shape
42 logit/Tensordot/MatMul MatMul
└─── Input0 ─ logit/Tensordot/Reshape
└─── Input1 ─ logit/Tensordot/Reshape_1
43 logit/Tensordot/shape Const
44 logit/Tensordot Reshape
└─── Input0 ─ logit/Tensordot/MatMul
└─── Input1 ─ logit/Tensordot/shape
45 logit/BiasAdd BiasAdd
└─── Input0 ─ logit/Tensordot
└─── Input1 ─ logit/bias/read
</code>```

What is the purpose of the reshape operations between nodes 36 and 44? I am working with the Snapdragon Neural Processing Engine (SNPE) which does not permit reshape operations. Is there any way to express this model without the reshape ops?

答: SNPE supports reshape in v1.8.0

Body:
This simple neural network defined in python:

input_layer = tf.placeholder(tf.float32, shape=[1, 1, 8000, 1], name='input_layer')

# Convolutional Layer
conv = tf.layers.conv2d(
        inputs=input_layer,
        filters=32,
        kernel_size=[1,11],
        padding="same",
        strides=1,
        activation=tf.nn.relu)

# Output layer
logits = tf.layers.dense(inputs=conv, units=5, name='logit')

Results the following graph topology:

0 input_layer Placeholder
1 conv2d/kernel/Initializer/random_uniform/shape Const
2 conv2d/kernel/Initializer/random_uniform/min Const
3 conv2d/kernel/Initializer/random_uniform/max Const
4 conv2d/kernel/Initializer/random_uniform/RandomUniform RandomUniform
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/shape
5 conv2d/kernel/Initializer/random_uniform/sub Sub
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/max
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform/min
6 conv2d/kernel/Initializer/random_uniform/mul Mul
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/RandomUniform
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform/sub
7 conv2d/kernel/Initializer/random_uniform Add
└─── Input0 ─ conv2d/kernel/Initializer/random_uniform/mul
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform/min
8 conv2d/kernel VariableV2
9 conv2d/kernel/Assign Assign
└─── Input0 ─ conv2d/kernel
└─── Input1 ─ conv2d/kernel/Initializer/random_uniform
10 conv2d/kernel/read Identity
└─── Input0 ─ conv2d/kernel
11 conv2d/bias/Initializer/zeros Const
12 conv2d/bias VariableV2
13 conv2d/bias/Assign Assign
└─── Input0 ─ conv2d/bias
└─── Input1 ─ conv2d/bias/Initializer/zeros
14 conv2d/bias/read Identity
└─── Input0 ─ conv2d/bias
15 conv2d/convolution/Shape Const
16 conv2d/convolution/dilation_rate Const
17 conv2d/convolution Conv2D
└─── Input0 ─ input_layer
└─── Input1 ─ conv2d/kernel/read
18 conv2d/BiasAdd BiasAdd
└─── Input0 ─ conv2d/convolution
└─── Input1 ─ conv2d/bias/read
19 conv2d/Relu Relu
└─── Input0 ─ conv2d/BiasAdd
20 logit/kernel/Initializer/random_uniform/shape Const
21 logit/kernel/Initializer/random_uniform/min Const
22 logit/kernel/Initializer/random_uniform/max Const
23 logit/kernel/Initializer/random_uniform/RandomUniform RandomUniform
└─── Input0 ─ logit/kernel/Initializer/random_uniform/shape
24 logit/kernel/Initializer/random_uniform/sub Sub
└─── Input0 ─ logit/kernel/Initializer/random_uniform/max
└─── Input1 ─ logit/kernel/Initializer/random_uniform/min
25 logit/kernel/Initializer/random_uniform/mul Mul
└─── Input0 ─ logit/kernel/Initializer/random_uniform/RandomUniform
└─── Input1 ─ logit/kernel/Initializer/random_uniform/sub
26 logit/kernel/Initializer/random_uniform Add
└─── Input0 ─ logit/kernel/Initializer/random_uniform/mul
└─── Input1 ─ logit/kernel/Initializer/random_uniform/min
27 logit/kernel VariableV2
28 logit/kernel/Assign Assign
└─── Input0 ─ logit/kernel
└─── Input1 ─ logit/kernel/Initializer/random_uniform
29 logit/kernel/read Identity
└─── Input0 ─ logit/kernel
30 logit/bias/Initializer/zeros Const
31 logit/bias VariableV2
32 logit/bias/Assign Assign
└─── Input0 ─ logit/bias
└─── Input1 ─ logit/bias/Initializer/zeros
33 logit/bias/read Identity
└─── Input0 ─ logit/bias
34 logit/Tensordot/transpose/perm Const
35 logit/Tensordot/transpose Transpose
└─── Input0 ─ conv2d/Relu
└─── Input1 ─ logit/Tensordot/transpose/perm
36 logit/Tensordot/Reshape/shape Const
37 logit/Tensordot/Reshape Reshape
└─── Input0 ─ logit/Tensordot/transpose
└─── Input1 ─ logit/Tensordot/Reshape/shape
38 logit/Tensordot/transpose_1/perm Const
39 logit/Tensordot/transpose_1 Transpose
└─── Input0 ─ logit/kernel/read
└─── Input1 ─ logit/Tensordot/transpose_1/perm
40 logit/Tensordot/Reshape_1/shape Const
41 logit/Tensordot/Reshape_1 Reshape
└─── Input0 ─ logit/Tensordot/transpose_1
└─── Input1 ─ logit/Tensordot/Reshape_1/shape
42 logit/Tensordot/MatMul MatMul
└─── Input0 ─ logit/Tensordot/Reshape
└─── Input1 ─ logit/Tensordot/Reshape_1
43 logit/Tensordot/shape Const
44 logit/Tensordot Reshape
└─── Input0 ─ logit/Tensordot/MatMul
└─── Input1 ─ logit/Tensordot/shape
45 logit/BiasAdd BiasAdd
└─── Input0 ─ logit/Tensordot
└─── Input1 ─ logit/bias/read

What is the purpose of the reshape operations between nodes 36 and 44? I am working with the Snapdragon Neural Processing Engine (SNPE) which does not permit reshape operations. Is there any way to express this model without the reshape ops?

Body: SNPE supports reshape in v1.8.0


问:
Load a hidden div with jquery - detect which div
I have a page with some hidden divs and they will show only when their links are clicked.

It will start with this blank summary page

And when About is click it will load about content

And so on.. however, my script right now is not as dynamic as I want it to be. How can I hide which ever div that's currently showing and load the div that is being clicked by user? As for now the script is as if each link is  going to be first clicked by user when page is loaded...

$(function() {
  $.ajaxSetup({
    cache: false
  });

  var ajax_load = "";

  $("#abt-ctrl").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');

    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#about-content').fadeIn();
      });
    });
  });

  $("#more").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');
    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#more-content').fadeIn();
      });
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper wrapper-content content-bg content-left-padding">
  <div id="service-content" class="row">
    <h2 style="margin-top: 22px; margin-left: 40px;max-width: 700px;margin-right: 50px;">Summary</h2>
    <p style="margin-left: 40px;max-width: 700px;margin-right: 50px;"></p>

  </div>
  <div id="about-content" class="hideme row">
    <div class="col-lg-12">
      <h2 style="margin-top: 22px; margin-left: 40px;max-width: 700px;margin-right: 50px;">About </h2>
      <p style="margin-top: 41px; margin-left: 40px;max-width: 700px;margin-right: 50px;">
        Gummi bears chocolate caramels biscuit bonbon. Candy donut apple pie. Bear claw apple pie sugar plum tiramisu jelly donut. Liquorice marzipan biscuit gummi bears dragée marshmallow. Jelly-o marshmallow candy pie gummi bears jujubes candy canes pie. Pastry
        gummi bears gummies cheesecake biscuit fruitcake candy canes soufflé soufflé. Chocolate bar apple pie jelly. Jelly croissant chocolate bar icing tart apple pie candy bonbon jelly beans. Chocolate lollipop soufflé tiramisu carrot cake danish sesame
        snaps soufflé.

      </p>
    </div>
  </div>
  <div id="more-content" class="hideme row">
    <div class="col-lg-12">
      <h2 style="margin-top: 22px; margin-left: 40px;max-width: 700px;margin-right: 50px;">More</h2>
      <p style="margin-top: 41px; margin-left: 40px;max-width: 700px;margin-right: 50px;">
        Croissant tart donut bear claw soufflé halvah. Brownie croissant chocolate. Pudding fruitcake gingerbread biscuit chocolate croissant gummi bears. Jujubes powder sugar plum tootsie roll caramels carrot cake tart icing. Cake oat cake chocolate cake gummies
        carrot cake jujubes carrot cake. Sweet cake chocolate cake fruitcake cookie pie gingerbread cupcake cookie. Marshmallow tiramisu wafer croissant tootsie roll. Wafer sweet roll cupcake chocolate cake apple pie croissant marshmallow muffin.
      </p>
    </div>
  </div>
</div></code>```

答:
You can hide all the divs while loading the page and show the content only while clicking on the link.

When you tap on another link, hide the current content and show the selected link's content. I have created a [fiddle][1] for you.

```<code> [1]: https://jsfiddle.net/oxxLnk7s/1/
</code>```

Body:
I have a page with some hidden divs and they will show only when their links are clicked.

It will start with this blank summary page

And when About is click it will load about content

And so on.. however, my script right now is not as dynamic as I want it to be. How can I hide which ever div that's currently showing and load the div that is being clicked by user? As for now the script is as if each link is  going to be first clicked by user when page is loaded...

$(function() {
  $.ajaxSetup({
    cache: false
  });

  var ajax_load = "";

  $("#abt-ctrl").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');

    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#about-content').fadeIn();
      });
    });
  });

  $("#more").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');
    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#more-content').fadeIn();
      });
    });
  });
});

Summary

About

        Gummi bears chocolate caramels biscuit bonbon. Candy donut apple pie. Bear claw apple pie sugar plum tiramisu jelly donut. Liquorice marzipan biscuit gummi bears dragée marshmallow. Jelly-o marshmallow candy pie gummi bears jujubes candy canes pie. Pastry
        gummi bears gummies cheesecake biscuit fruitcake candy canes soufflé soufflé. Chocolate bar apple pie jelly. Jelly croissant chocolate bar icing tart apple pie candy bonbon jelly beans. Chocolate lollipop soufflé tiramisu carrot cake danish sesame
        snaps soufflé.

More

        Croissant tart donut bear claw soufflé halvah. Brownie croissant chocolate. Pudding fruitcake gingerbread biscuit chocolate croissant gummi bears. Jujubes powder sugar plum tootsie roll caramels carrot cake tart icing. Cake oat cake chocolate cake gummies
        carrot cake jujubes carrot cake. Sweet cake chocolate cake fruitcake cookie pie gingerbread cupcake cookie. Marshmallow tiramisu wafer croissant tootsie roll. Wafer sweet roll cupcake chocolate cake apple pie croissant marshmallow muffin.

Body:
You can hide all the divs while loading the page and show the content only while clicking on the link.

When you tap on another link, hide the current content and show the selected link's content. I have created a [fiddle][1] for you.

 [1]: https://jsfiddle.net/oxxLnk7s/1/


问:
Detecting a change in UISwitch
This sounds trivial but I'm noticing some weirdness. I've wired up a handler for the Value Changed event of a UISwitch. What I would expect is that each time the handler is called the value of the switch would change. But that's actually not always the case. If you press the switch rapidly on/off the handler can get called consecutively with the SAME state for the switch (in my specific application this is an issue). So I'm wondering if anyone else has noticed this behavior and has figured out a good solution.

答:
In iOS 11 a new UISwitch bug was introduced so I don't recommend subscribing to value changed events. Otherwise your callback will be triggered every time UISwitch's isOn attribute changes programmatically.

Instead:

Subscribe for touch up inside event:

```<code>let switch = UISwitch()
switch.addTarget(self, action: #selector(onSwitchValueChanged), for: .valueChanged)
</code>```

Implement the callback method:

```<code>func onSwitchValueChanged(_ switch: UISwitch) {

}
</code>```

And now when you programmatically change isOn value, it won't trigger onSwitchValueChanged method.

switch.isOn = !switch.isOn // 'onSwitchValueChanged' is not triggered

Title: Detecting a change in UISwitch

Body:
In iOS 11 a new UISwitch bug was introduced so I don't recommend subscribing to value changed events. Otherwise your callback will be triggered every time UISwitch's isOn attribute changes programmatically.

Instead:

Subscribe for touch up inside event:

let switch = UISwitch()
switch.addTarget(self, action: #selector(onSwitchValueChanged), for: .valueChanged)

Implement the callback method:

func onSwitchValueChanged(_ switch: UISwitch) {

}

And now when you programmatically change isOn value, it won't trigger onSwitchValueChanged method.

switch.isOn = !switch.isOn // 'onSwitchValueChanged' is not triggered


问:
Watch $scope on factory using $http angularjs
I am trying to watch a change of value that is fetched from a factory using $http.

Here is my factory: (it simply returns a list of videos from the backend)

```<code>app.factory('videoHttpService', ['$http', function ($http) {
    var service = {};

    service.getEducationalVideos = getEducationalVideos;

    return service;

    function getEducationalVideos() {
        return $http({
            url: 'api/video/educational',
            method: 'GET'
        }).then(function (result) {
            return result.data;
        });
    }
}]);
</code>```

Here is my controller:

```<code>app.controller('videoCtrl', ['$scope', 'videoHttpService',
                         function ($scope, videoHttpService) {

    videoHttpService.getEducationalVideos().then(function (result) {
        $scope.educationalVideos = result;
    });

    $scope.$watch($scope.educationalVideos, function (newValue, oldValue) {
        console.log(oldValue, newValue);
        if (newValue !== oldValue) {
            $scope.educationalVideos = newValue;
        }
    });

}]);
</code>```

This does not work. I get undefined, undefined in the console.log.

Any insight of what I am doing wrong?

答:
In order to watch a $scope element, you have to do:

```<code>$scope.$watch('educationalVideos', function (newValue, oldValue) {
    console.log(oldValue, newValue);
    if (newValue !== oldValue) {
        $scope.educationalVideos = newValue;
    }
});
</code>```

Body:
I am trying to watch a change of value that is fetched from a factory using $http.

Here is my factory: (it simply returns a list of videos from the backend)

app.factory('videoHttpService', ['$http', function ($http) {
    var service = {};

    service.getEducationalVideos = getEducationalVideos;

    return service;

    function getEducationalVideos() {
        return $http({
            url: 'api/video/educational',
            method: 'GET'
        }).then(function (result) {
            return result.data;
        });
    }
}]);

Here is my controller:

app.controller('videoCtrl', ['$scope', 'videoHttpService',
                         function ($scope, videoHttpService) {

    videoHttpService.getEducationalVideos().then(function (result) {
        $scope.educationalVideos = result;
    });

    $scope.$watch($scope.educationalVideos, function (newValue, oldValue) {
        console.log(oldValue, newValue);
        if (newValue !== oldValue) {
            $scope.educationalVideos = newValue;
        }
    });

}]);

This does not work. I get undefined, undefined in the console.log.

Any insight of what I am doing wrong?

Body:
In order to watch a $scope element, you have to do:

$scope.$watch('educationalVideos', function (newValue, oldValue) {
    console.log(oldValue, newValue);
    if (newValue !== oldValue) {
        $scope.educationalVideos = newValue;
    }
});


问:
Setting backgroundcolor not possible
I'm filling a grid with views.
This takes some time.
During the filling, the background stays black.
When views are added, the black background goes aways accordingly.

However, I would like the grid's backgroundcolor to be White instead of Black.

No matter what I do, I just don't seem to be able to set the backgroundcolor.

I've set the NavigationPage's backgroundcolor to Color.White, and I've set the Grid's backgroundcolor to Color.White.

What else could I do to make the backgroundcolor white?

I'm not sure if the mistake is really on my side.

Here you can see what's happening:

First the grid's background is black. When views are added, the black background is overdrawn by the views.

On the right side you can see that 5 views have already loaded.
The 6nd view has not yet loaded, so the background is still black.
[![enter image description here][1]][1]

Edit:

In the NavigationPage / ContentPage I have this:

```<code> public MainPage()
    {
       this.BackgroundColor = Color.White;
</code>```

In this MainPage, I have a Grid ("_BigGridAsLayout") in which a custom bottom navbar is placed. This "_BigGridAsLayout" occupies the entire page:

```<code>        _BigGridAsLayout = new Grid()
        {
            BackgroundColor = Color.White,
        }
        (...)
        _BigGridAsLayout.Children.Add(_CellGrid,0,0);
        _BigGridAsLayout.Children.Add(_NavBar,0,1);

        this.Content = _BigGridAsLayout;
</code>```

Then I add "clsGridCell" views to the "_CellGrid".
"clsGridCell" looks like this:

```<code>    public clsGridCell(eImageAlignment uImageAlignment)
    {
        this.BackgroundColor = Color.White;
        BackgroundColor = Color.White;
</code>```

答: Add the background color of the view (added in the grid ) to whatever color you want .</p>

Title: Setting backgroundcolor not possible

Body:
I'm filling a grid with views.
This takes some time.
During the filling, the background stays black.
When views are added, the black background goes aways accordingly.

However, I would like the grid's backgroundcolor to be White instead of Black.

No matter what I do, I just don't seem to be able to set the backgroundcolor.

I've set the NavigationPage's backgroundcolor to Color.White, and I've set the Grid's backgroundcolor to Color.White.

What else could I do to make the backgroundcolor white?

I'm not sure if the mistake is really on my side.

Here you can see what's happening:

First the grid's background is black. When views are added, the black background is overdrawn by the views.

On the right side you can see that 5 views have already loaded.
The 6nd view has not yet loaded, so the background is still black.
[![enter image description here][1]][1]

Edit:

In the NavigationPage / ContentPage I have this:

 public MainPage()
    {
       this.BackgroundColor = Color.White;

In this MainPage, I have a Grid ("_BigGridAsLayout") in which a custom bottom navbar is placed. This "_BigGridAsLayout" occupies the entire page:

        _BigGridAsLayout = new Grid()
        {
            BackgroundColor = Color.White,
        }
        (...)
        _BigGridAsLayout.Children.Add(_CellGrid,0,0);
        _BigGridAsLayout.Children.Add(_NavBar,0,1);

        this.Content = _BigGridAsLayout;

Then I add "clsGridCell" views to the "_CellGrid".
"clsGridCell" looks like this:

    public clsGridCell(eImageAlignment uImageAlignment)
    {
        this.BackgroundColor = Color.White;
        BackgroundColor = Color.White;


问:
Iterate through two dimensional array while changing each element
I want to fill a two dimensional array with certain values. I want to get:

```<code>[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]
</code>```

How can I do it?

This is my code:

```<code>game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field
</code>```

答:
Array.new accepts a block in which you can define the element directly:

```<code>Array.new(3){|i| Array.new(3){|j| "Num#{i}#{j}" } }
# [["Num00", "Num01", "Num02"], ["Num10", "Num11", "Num12"], ["Num20", "Num21", "Num22"]]
</code>```

When you call Array.new(3, Array.new(3)), you create an array which contains 3 times the exact same object : Array.new(3). When you modify an element in an inner-array, you modify it on every array!

If you initialize game_field like this : game_field = Array.new(3){ Array.new(3) }, your code works fine.

Body:
I want to fill a two dimensional array with certain values. I want to get:

[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]

How can I do it?

This is my code:

game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field

Body:
Array.new accepts a block in which you can define the element directly:

Array.new(3){|i| Array.new(3){|j| "Num#{i}#{j}" } }
# [["Num00", "Num01", "Num02"], ["Num10", "Num11", "Num12"], ["Num20", "Num21", "Num22"]]

When you call Array.new(3, Array.new(3)), you create an array which contains 3 times the exact same object : Array.new(3). When you modify an element in an inner-array, you modify it on every array!

If you initialize game_field like this : game_field = Array.new(3){ Array.new(3) }, your code works fine.


问:
How can I rewrite a code for php server to a code for Apache?
Is it possible that a code written for php server could be rewritten for apache server? Is it even a legal question in the first place? I have very little experience on server-side technologies.
THanks</p>

答:
You do not have to rewrite anything. Php is a language which can be processed by Apache server.

Php is a language as is say ASP among others,
Apache is a web server as is say IIS among others

Apache and IIS can understand and process PHP coded sites.

You seem to discover the field, you should start by reading this kind of articles that will demistify the all the thing for you :

http://www.webdevelopersnotes.com/basics/client_server_architecture.php3

Good luck


问:
jQuery addClass and removeClass not working
currently working on a simple script that displays a nightime background if it's a certain time in the day and a daytime image if it's a different time of day. I am using jQuery to achieve this by adding a class if one is true, and adding a class if the other is true. Issue is... the code simply won't function properly. Curious about any possible solutions... thanks!

$(document).ready(function() {
  var currentTime = new Date().getHours();
  if (7 <= currentTime && currentTime < 20) {
    $("document.body").addClass("day");
    $("document.body").removeClass("night");
  } else {
    $("document.body").addClass("night");
    $("document.body").removeClass("day");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.night {
  background-image: url('images/night.jpg');
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}</code>```

```

答: You need to replace $("document.body") with $("body")

Body:
currently working on a simple script that displays a nightime background if it's a certain time in the day and a daytime image if it's a different time of day. I am using jQuery to achieve this by adding a class if one is true, and adding a class if the other is true. Issue is... the code simply won't function properly. Curious about any possible solutions... thanks!

$(document).ready(function() {
  var currentTime = new Date().getHours();
  if (7 <= currentTime && currentTime < 20) {
    $("document.body").addClass("day");
    $("document.body").removeClass("night");
  } else {
    $("document.body").addClass("night");
    $("document.body").removeClass("day");
  }
});

.night {
  background-image: url('images/night.jpg');
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}


问:
How to position the legend to the right of the donut chart
Here is my plunkr code, in this position of the legend is at center, how do I position it to the right of the donut chart?

```<code>var svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', 'translate(' + (width / 2 - radius) +
        ',' + (height / 2 - radius) + ')');
</code>```

I tried with the above code but it's not working.

答:
Define new variable and set your legend width in pixels:

```<code>var legendWidth = 150;
</code>```

Use this variable for svg element width:

```<code>var svg = d3.select('#chart')
  .append('svg')
  .attr('width', width + legendWidth) // <== !!!
  .attr('height', height)
  .append('g')
  .attr('transform', 'translate(' + (width / 2) +
    ',' + (height / 2) + ')');
</code>```

Rewrite your function for legend transform attribute this way:

```<code>var legend = svg.selectAll('.legend')
  .data(color.domain())
  .enter()
  .append('g')
  .attr('class', 'legend')
  .attr('transform', function(d, i) {
    var height = legendRectSize + legendSpacing;
    var offset =  height * color.domain().length / 2;
    var vert = i * height - offset;
    return 'translate(' + width / 2 + ',' + vert + ')'; // <== move every legend item on half of width
  });
</code>```

Check working example here.

Body:
Here is my plunkr code, in this position of the legend is at center, how do I position it to the right of the donut chart?

var svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', 'translate(' + (width / 2 - radius) +
        ',' + (height / 2 - radius) + ')');

I tried with the above code but it's not working.

Body:
Define new variable and set your legend width in pixels:

var legendWidth = 150;

Use this variable for svg element width:

var svg = d3.select('#chart')
  .append('svg')
  .attr('width', width + legendWidth) // <== !!!
  .attr('height', height)
  .append('g')
  .attr('transform', 'translate(' + (width / 2) +
    ',' + (height / 2) + ')');

Rewrite your function for legend transform attribute this way:

var legend = svg.selectAll('.legend')
  .data(color.domain())
  .enter()
  .append('g')
  .attr('class', 'legend')
  .attr('transform', function(d, i) {
    var height = legendRectSize + legendSpacing;
    var offset =  height * color.domain().length / 2;
    var vert = i * height - offset;
    return 'translate(' + width / 2 + ',' + vert + ')'; // <== move every legend item on half of width
  });

Check working example here.


问:
Error while connecting MYSQL with asp.net core

Problem

I am trying to conect MY SQL with my asp.net core 2.0 web application. But it throug me this error

Method 'Clone' in type 'MySql.Data.EntityFrameworkCore.Infraestructure.Internal.MySQLOptionsExtension' from assembly 'MySql.Data.EntityFrameworkCore, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation.

I am using Repository pattern  in asp.net core 2.0 with EF 2.0

startup.cs

here the error occurs

```<code>services.AddDbContext<MyContext>(options =>
            options.UseMySQL(
                Configuration.GetConnectionString("DefaultConnection"),
                b=>b.MigrationsAssembly("AspNetCoreMultipleProject")
                ));
</code>```

答:
It looks like this could be because the official MySQL provider doesn't work with EF core 2.0 - GitHub issue.

The suggested workaround is to use the Pomelo provider - MS documentation

Body:
Problem

I am trying to conect MY SQL with my asp.net core 2.0 web application. But it throug me this error

Method 'Clone' in type 'MySql.Data.EntityFrameworkCore.Infraestructure.Internal.MySQLOptionsExtension' from assembly 'MySql.Data.EntityFrameworkCore, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation.

I am using Repository pattern  in asp.net core 2.0 with EF 2.0

startup.cs

here the error occurs

services.AddDbContext<MyContext>(options =>
            options.UseMySQL(
                Configuration.GetConnectionString("DefaultConnection"),
                b=>b.MigrationsAssembly("AspNetCoreMultipleProject")
                ));


问:
Selecting columns based on row values in multiple columns using dplyr
I am trying to select columns where at least one row equals 1, only if the same row also has a certain value in a second column. I would prefer to achieve this using dplyr, but any computationally efficient solution is welcome.

Example:

Select columns among a1, a2, a3 containing at least one row where the value is 1 AND where column b=="B"

Example data:

```<code>rand <- function(S) {set.seed(S); sample(x = c(0,1),size = 3, replace=T)}
df <- data.frame(a1=rand(1),a2=rand(2),a3=rand(3),b=c("A","B","A"))
</code>```

Input data:

```<code>  a1 a2 a3 b
1  0  0  0 A
2  0  1  1 B
3  1  1  0 A
</code>```

Desired output:

```<code>  a2 a3
1  0  0
2  1  1
3  1  0
</code>```

I managed to obtain the correct output with the following code, however this is a very inefficient solution and I need to run it on a very large dataframe (365,000 rows X 314 columns).

```<code>df %>% select_if(function(x) any(paste0(x,.$b) == '1B'))
</code>```

答:
Here is my dplyr solution:

```<code>ids <- df %>%
  reshape2::melt(id.vars = "b") %>%
  filter(value == 1 & b == "B") %>%
  select(variable)

df[,unlist(ids)]

#  a2 a3
#1  0  0
#2  1  1
#3  1  0
</code>```

As suggested by @docendo-discimus it is easier to convert to long format

Body:
I am trying to select columns where at least one row equals 1, only if the same row also has a certain value in a second column. I would prefer to achieve this using dplyr, but any computationally efficient solution is welcome.

Example:

Select columns among a1, a2, a3 containing at least one row where the value is 1 AND where column b=="B"

Example data:

rand <- function(S) {set.seed(S); sample(x = c(0,1),size = 3, replace=T)}
df <- data.frame(a1=rand(1),a2=rand(2),a3=rand(3),b=c("A","B","A"))

Input data:

  a1 a2 a3 b
1  0  0  0 A
2  0  1  1 B
3  1  1  0 A

Desired output:

  a2 a3
1  0  0
2  1  1
3  1  0

I managed to obtain the correct output with the following code, however this is a very inefficient solution and I need to run it on a very large dataframe (365,000 rows X 314 columns).

df %>% select_if(function(x) any(paste0(x,.$b) == '1B'))

Body:
Here is my dplyr solution:

ids <- df %>%
  reshape2::melt(id.vars = "b") %>%
  filter(value == 1 & b == "B") %>%
  select(variable)

df[,unlist(ids)]

#  a2 a3
#1  0  0
#2  1  1
#3  1  0

As suggested by @docendo-discimus it is easier to convert to long format


问:
VBA: InStr "OR" issue
I am having issue with my InStr "OR" code. This code: If InStr(items, "harmo") Or InStr(items, "pointt") Then count_of_Harmo = count_of_Harmo + 1
is able to execute well (Highlighted in red below) but this one doesn't ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then count_of_Addi = count_of_Addi + 1(Highlighted in blue below). Please don't mind the other results/counts on the image below as i was not able to capture the whole page as it I think it is relevant to the case. Please see the full code below too. Thank you.

```<code>Option Compare Text

Public Sub Keywords_Outlook()

Dim row_number As Long
Dim count_of_Harmo As Long
Dim count_of_Room As Long
Dim count_of_Skyp As Long
Dim count_of_Detach As Long
Dim count_of_Wire As Long
Dim count_of_Addi As Long
Dim count_of_crash As Long
Dim count_of_share As Long
Dim count_of_signa As Long
Dim count_of_passw As Long
Dim count_of_follo_and_ops As Long
Dim count_of_follo_and_req As Long
Dim count_of_others As Long
Dim items As Variant
Dim cursht As String 'for the macro to run in any sheet
cursht = ActiveSheet.Name 'for the macro to run in any sheet

row_number = 1
count_of_Harmo = 0
count_of_Room = 0
count_of_Skyp = 0
count_of_Detach = 0
count_of_Wire = 0
count_of_Addi = 0
count_of_crash = 0
count_of_share = 0
count_of_signa = 0
count_of_passw = 0
count_of_follo_and_ops = 0
count_of_follo_and_req = 0
count_of_others = 0
count_of_all = 0

Do

row_number = row_number + 1
items = Sheets(cursht).Range("N" & row_number)

    If InStr(items, "harmo") Or InStr(items, "pointt") Then
        count_of_Harmo = count_of_Harmo + 1
    ElseIf InStr(items, "room") Then
        count_of_Room = count_of_Room + 1
    ElseIf InStr(items, "skyp") Then
        count_of_Skyp = count_of_Skyp + 1
    ElseIf InStr(items, "detach") Then
        count_of_Detach = count_of_Detach + 1
    ElseIf InStr(items, "wire") Then
        count_of_Wire = count_of_Wire + 1
    ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then
        count_of_Addi = count_of_Addi + 1
    ElseIf InStr(items, "crash") Or InStr(items, "car") Then
        count_of_crash = count_of_crash + 1
    ElseIf InStr(items, "share") Then
        count_of_share = count_of_share + 1
    ElseIf InStr(items, "signa") Then
        count_of_signa = count_of_signa + 1
    ElseIf InStr(items, "passw") Then
        count_of_passw = count_of_passw + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*ops*" Then
        count_of_follo_and_ops = count_of_follo_and_ops + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*req*" Then
        count_of_follo_and_req = count_of_follo_and_req + 1

    ElseIf items <> "" Then
        count_of_others = count_of_others + 1
    End If

Loop Until items = ""

count_of_all = count_of_Harmo + count_of_Room + count_of_Skyp + count_of_Detach + count_of_Wire + count_of_Addi + count_of_crash + count_of_signa + count_of_passw + count_of_follo_and_ops + count_of_follo_and_req + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_Harmo
ActiveCell.Offset(5, 0).Value = count_of_Room
ActiveCell.Offset(6, 0).Value = count_of_Skyp
ActiveCell.Offset(7, 0).Value = count_of_Detach
ActiveCell.Offset(8, 0).Value = count_of_Wire
ActiveCell.Offset(9, 0).Value = count_of_Addi
ActiveCell.Offset(10, 0).Value = count_of_crash
ActiveCell.Offset(11, 0).Value = count_of_share
ActiveCell.Offset(12, 0).Value = count_of_signa
ActiveCell.Offset(13, 0).Value = count_of_passw
ActiveCell.Offset(14, 0).Value = count_of_follo_and_ops
ActiveCell.Offset(15, 0).Value = count_of_follo_and_req
ActiveCell.Offset(16, 0).Value = count_of_others
ActiveCell.Offset(18, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Outlook Keywords"
ActiveCell.Offset(4, 1).Value = "Harmo"
ActiveCell.Offset(5, 1).Value = "Room"
ActiveCell.Offset(6, 1).Value = "Skyp"
ActiveCell.Offset(7, 1).Value = "Detach"
ActiveCell.Offset(8, 1).Value = "Wire"
ActiveCell.Offset(9, 1).Value = "Addi or add-i or plug"
ActiveCell.Offset(10, 1).Value = "Crash"
ActiveCell.Offset(11, 1).Value = "Share"
ActiveCell.Offset(12, 1).Value = "Signa"
ActiveCell.Offset(13, 1).Value = "passw"
ActiveCell.Offset(14, 1).Value = "FollowU and ops"
ActiveCell.Offset(15, 1).Value = "FollowU and req"
ActiveCell.Offset(16, 1).Value = "Others"
ActiveCell.Offset(18, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_Harmo / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_Room / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_Skyp / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_Detach / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_Wire / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_Addi / count_of_all
ActiveCell.Offset(10, -1).Value = count_of_crash / count_of_all
ActiveCell.Offset(11, -1).Value = count_of_share / count_of_all
ActiveCell.Offset(12, -1).Value = count_of_signa / count_of_all
ActiveCell.Offset(13, -1).Value = count_of_passw / count_of_all
ActiveCell.Offset(14, -1).Value = count_of_follo_and_ops / count_of_all
ActiveCell.Offset(15, -1).Value = count_of_follo_and_req / count_of_all
ActiveCell.Offset(16, -1).Value = count_of_others / count_of_all

End Sub
</code>```

答:
Looking at your code, there is a much more efficient and shorter (code wise) to go.

Switch your multiple ElseIf with Select Case, and instead of having 14 counters, why not use an array of counters CountofArr ?

See sample code below, you can continue the implementation easily :

```<code>Option Compare Text

Public Sub Keywords_Outlook()

Dim row_number As Long, LastRow As Long

' use an array that will have multiple counters
Dim CountofArr() As Long

ReDim CountofArr(0 To 14)

Dim items As Variant
Dim cursht As String 'for the macro to run in any sheet

cursht = ActiveSheet.Name ' for the macro to run in any sheet

With Sheets(cursht)
    LastRow = .Cells(.Rows.Count, "N").End(xlUp).Row ' get last row with data in column "N"

    For row_number = 1 To LastRow
        items = .Range("N" & row_number).Value2

        Select Case True
            Case items Like "*harmo*", items Like "*pointt*"
                CountofArr(0) = CountofArr(0) + 1

            Case items Like "*room*"
                CountofArr(1) = CountofArr(1) + 1

            ' add the rest of your cases below

        End Select
    Next row_number

    ' read the array direclty to the cells
    For row_number = 4 To 18
        .Range("O" & row_number).Value = CountofArr(row_number - 4)
    Next row_number

    ' rest of your code

End With

End Sub
</code>```

Title: VBA: InStr "OR" issue

Body:
I am having issue with my InStr "OR" code. This code: If InStr(items, "harmo") Or InStr(items, "pointt") Then count_of_Harmo = count_of_Harmo + 1
is able to execute well (Highlighted in red below) but this one doesn't ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then count_of_Addi = count_of_Addi + 1(Highlighted in blue below). Please don't mind the other results/counts on the image below as i was not able to capture the whole page as it I think it is relevant to the case. Please see the full code below too. Thank you.

Option Compare Text

Public Sub Keywords_Outlook()

Dim row_number As Long
Dim count_of_Harmo As Long
Dim count_of_Room As Long
Dim count_of_Skyp As Long
Dim count_of_Detach As Long
Dim count_of_Wire As Long
Dim count_of_Addi As Long
Dim count_of_crash As Long
Dim count_of_share As Long
Dim count_of_signa As Long
Dim count_of_passw As Long
Dim count_of_follo_and_ops As Long
Dim count_of_follo_and_req As Long
Dim count_of_others As Long
Dim items As Variant
Dim cursht As String 'for the macro to run in any sheet
cursht = ActiveSheet.Name 'for the macro to run in any sheet

row_number = 1
count_of_Harmo = 0
count_of_Room = 0
count_of_Skyp = 0
count_of_Detach = 0
count_of_Wire = 0
count_of_Addi = 0
count_of_crash = 0
count_of_share = 0
count_of_signa = 0
count_of_passw = 0
count_of_follo_and_ops = 0
count_of_follo_and_req = 0
count_of_others = 0
count_of_all = 0

Do

row_number = row_number + 1
items = Sheets(cursht).Range("N" & row_number)

    If InStr(items, "harmo") Or InStr(items, "pointt") Then
        count_of_Harmo = count_of_Harmo + 1
    ElseIf InStr(items, "room") Then
        count_of_Room = count_of_Room + 1
    ElseIf InStr(items, "skyp") Then
        count_of_Skyp = count_of_Skyp + 1
    ElseIf InStr(items, "detach") Then
        count_of_Detach = count_of_Detach + 1
    ElseIf InStr(items, "wire") Then
        count_of_Wire = count_of_Wire + 1
    ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then
        count_of_Addi = count_of_Addi + 1
    ElseIf InStr(items, "crash") Or InStr(items, "car") Then
        count_of_crash = count_of_crash + 1
    ElseIf InStr(items, "share") Then
        count_of_share = count_of_share + 1
    ElseIf InStr(items, "signa") Then
        count_of_signa = count_of_signa + 1
    ElseIf InStr(items, "passw") Then
        count_of_passw = count_of_passw + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*ops*" Then
        count_of_follo_and_ops = count_of_follo_and_ops + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*req*" Then
        count_of_follo_and_req = count_of_follo_and_req + 1

    ElseIf items <> "" Then
        count_of_others = count_of_others + 1
    End If

Loop Until items = ""

count_of_all = count_of_Harmo + count_of_Room + count_of_Skyp + count_of_Detach + count_of_Wire + count_of_Addi + count_of_crash + count_of_signa + count_of_passw + count_of_follo_and_ops + count_of_follo_and_req + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_Harmo
ActiveCell.Offset(5, 0).Value = count_of_Room
ActiveCell.Offset(6, 0).Value = count_of_Skyp
ActiveCell.Offset(7, 0).Value = count_of_Detach
ActiveCell.Offset(8, 0).Value = count_of_Wire
ActiveCell.Offset(9, 0).Value = count_of_Addi
ActiveCell.Offset(10, 0).Value = count_of_crash
ActiveCell.Offset(11, 0).Value = count_of_share
ActiveCell.Offset(12, 0).Value = count_of_signa
ActiveCell.Offset(13, 0).Value = count_of_passw
ActiveCell.Offset(14, 0).Value = count_of_follo_and_ops
ActiveCell.Offset(15, 0).Value = count_of_follo_and_req
ActiveCell.Offset(16, 0).Value = count_of_others
ActiveCell.Offset(18, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Outlook Keywords"
ActiveCell.Offset(4, 1).Value = "Harmo"
ActiveCell.Offset(5, 1).Value = "Room"
ActiveCell.Offset(6, 1).Value = "Skyp"
ActiveCell.Offset(7, 1).Value = "Detach"
ActiveCell.Offset(8, 1).Value = "Wire"
ActiveCell.Offset(9, 1).Value = "Addi or add-i or plug"
ActiveCell.Offset(10, 1).Value = "Crash"
ActiveCell.Offset(11, 1).Value = "Share"
ActiveCell.Offset(12, 1).Value = "Signa"
ActiveCell.Offset(13, 1).Value = "passw"
ActiveCell.Offset(14, 1).Value = "FollowU and ops"
ActiveCell.Offset(15, 1).Value = "FollowU and req"
ActiveCell.Offset(16, 1).Value = "Others"
ActiveCell.Offset(18, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_Harmo / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_Room / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_Skyp / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_Detach / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_Wire / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_Addi / count_of_all
ActiveCell.Offset(10, -1).Value = count_of_crash / count_of_all
ActiveCell.Offset(11, -1).Value = count_of_share / count_of_all
ActiveCell.Offset(12, -1).Value = count_of_signa / count_of_all
ActiveCell.Offset(13, -1).Value = count_of_passw / count_of_all
ActiveCell.Offset(14, -1).Value = count_of_follo_and_ops / count_of_all
ActiveCell.Offset(15, -1).Value = count_of_follo_and_req / count_of_all
ActiveCell.Offset(16, -1).Value = count_of_others / count_of_all

End Sub

Body:
Looking at your code, there is a much more efficient and shorter (code wise) to go.

Switch your multiple ElseIf with Select Case, and instead of having 14 counters, why not use an array of counters CountofArr ?

See sample code below, you can continue the implementation easily :

Option Compare Text

Public Sub Keywords_Outlook()

Dim row_number As Long, LastRow As Long

' use an array that will have multiple counters
Dim CountofArr() As Long

ReDim CountofArr(0 To 14)

Dim items As Variant
Dim cursht As String 'for the macro to run in any sheet

cursht = ActiveSheet.Name ' for the macro to run in any sheet

With Sheets(cursht)
    LastRow = .Cells(.Rows.Count, "N").End(xlUp).Row ' get last row with data in column "N"

    For row_number = 1 To LastRow
        items = .Range("N" & row_number).Value2

        Select Case True
            Case items Like "*harmo*", items Like "*pointt*"
                CountofArr(0) = CountofArr(0) + 1

            Case items Like "*room*"
                CountofArr(1) = CountofArr(1) + 1

            ' add the rest of your cases below

        End Select
    Next row_number

    ' read the array direclty to the cells
    For row_number = 4 To 18
        .Range("O" & row_number).Value = CountofArr(row_number - 4)
    Next row_number

    ' rest of your code

End With

End Sub


问:
onselectedindexchanged() not being called and confirm box clears text even when cancel button is clicked
I am trying to clear the content of the RadEdiotors when different item is selected from the drop down list. The following script does clear the editors' content when OK is clicked but it also clears the content when even cancle button is clicked in the Confirm box that shows up. What is wrong with the following script? Also,
in code behind, the onselectedindexchanged() event of this dropdown is also not being called when a different item is selecetd from the list.
How do I make it work? Please help.Thanks.

```<code><script type="text/javascript">

        var showConfirm = 1;

   function onClientSelectedIndexChanging(item) {
    var editor1 = $find("<%= Editor1.ClientID %>");
    var editor2 = $find("<%= Editor2.ClientID %>");
    var content= editor.get_html();
    var callBackFn = function (arg)
    {
        if (arg == true && showConfirm == 1)
        {
            var combo = item.ComboBox;
            combo.ClearSelection();

            showConfirm = 0;

            combo.FindItemByText(item.Text).Select();
            combo.SetText(item.Text);

            __doPostBack("cboxLanguage", '{\"Command\":\"Select\"}');

            showConfirm = 1;
        }
    }

    if (showConfirm == 1 && content != '')
    {

        confirm('Changing the language will clear the content of the ediotrs. Click OK to proceed.', callBackFn);

        alert(confirm);
         if (content != null)

         {
                 editor1.set_html("");
                 editor2.set_html("");
                 return true
          }
          else
          {
              return false;
          }
    }
    return false;
}
</script>
</code>```

Its telerik's Radcombobox that I am using and RadEditor.

This is my combobox :-

```<code>   <telerik:RadComboBox ID="cboxLanguage" TabIndex="2" runat="server" AutoPostBack="false" OnSelectedIndexChanged="cboxLanguage_OnSelectedIndexChanged" OnClientSelectedIndexChanging="onClientSelectedIndexChanging">
</telerik:RadComboBox>
</code>```

I want if confirm==true then clear editors' content otherwise not. How do I get the "true" value of this confirm box? Also, how do I get the OnSelectedIndexChanged() event to be called?

Can anyone please help? What am I doing wrong here?

edit
alert(confirm); returns the complete function code. How do I fetch the true/false values and clear editors' content based on that?

答:
Try replacing your confirm statement with this:

```<code> var c = confirm('Changing the language will clear the content of the ediotrs. Click OK to proceed.', callBackFn);
</code>```

Doing that will assign the result of the confirm function to the variable called 'c' and you can use that variable as a boolean.

Also, instead of alert(confirm); you would do alert(c);

Body:
I am trying to clear the content of the RadEdiotors when different item is selected from the drop down list. The following script does clear the editors' content when OK is clicked but it also clears the content when even cancle button is clicked in the Confirm box that shows up. What is wrong with the following script? Also,
in code behind, the onselectedindexchanged() event of this dropdown is also not being called when a different item is selecetd from the list.
How do I make it work? Please help.Thanks.

Its telerik's Radcombobox that I am using and RadEditor.

This is my combobox :-

   <telerik:RadComboBox ID="cboxLanguage" TabIndex="2" runat="server" AutoPostBack="false" OnSelectedIndexChanged="cboxLanguage_OnSelectedIndexChanged" OnClientSelectedIndexChanging="onClientSelectedIndexChanging">
</telerik:RadComboBox>

I want if confirm==true then clear editors' content otherwise not. How do I get the "true" value of this confirm box? Also, how do I get the OnSelectedIndexChanged() event to be called?

Can anyone please help? What am I doing wrong here?

edit
alert(confirm); returns the complete function code. How do I fetch the true/false values and clear editors' content based on that?

Body:
Try replacing your confirm statement with this:

 var c = confirm('Changing the language will clear the content of the ediotrs. Click OK to proceed.', callBackFn);

Doing that will assign the result of the confirm function to the variable called 'c' and you can use that variable as a boolean.

Also, instead of alert(confirm); you would do alert(c);


问:
Retraining Inception v3 model without reshape layer
I had retrained inception v3 model for a custom dataset.
But after retraining when i look at the TenosorGraph i found that a layer named as reshape followed by a fully connected layer is added.
I have to run the model on an embedded device using snapdragonneural processing engine(SNPE) but it doesnt support reshape layer as of now to run on DSP.

Is there a possible way of retraining inception v3 without adding reshape layer.
Below is the retrain code where the reshape layer is added.

```<code>enter code here
              def create_model_info(architecture):
  """Given the name of a model architecture, returns information about it.

  There are different base image recognition pretrained models that can be
  retrained using transfer learning, and this function translates from the name
  of a model to the attributes that are needed to download and train with it.

  Args:
    architecture: Name of a model architecture.

  Returns:
    Dictionary of information about the model, or None if the name isn't
    recognized

  Raises:
    ValueError: If architecture name is unknown.
  """
  architecture = architecture.lower()
  if architecture == 'inception_v3':
    # pylint: disable=line-too-long
    data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
    # pylint: enable=line-too-long
    bottleneck_tensor_name = 'pool_3/_reshape:0'
    bottleneck_tensor_size = 2048
    input_width = 299
    input_height = 299
    input_depth = 3
    resized_input_tensor_name = 'Mul:0'
    model_file_name = 'classify_image_graph_def.pb'
    input_mean = 128
    input_std = 128
      elif architecture.startswith('mobilenet_'):
        parts = architecture.split('_')
        if len(parts) != 3 and len(parts) != 4:
          tf.logging.error("Couldn't understand architecture name '%s'",
                           architecture)
          return None
        version_string = parts[1]
        if (version_string != '1.0' and version_string != '0.75' and
            version_string != '0.50' and version_string != '0.25'):
          tf.logging.error(
              """"The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25',
      but found '%s' for architecture '%s'""",
              version_string, architecture)
          return None
        size_string = parts[2]
        if (size_string != '224' and size_string != '192' and
            size_string != '160' and size_string != '128'):
          tf.logging.error(
              """The Mobilenet input size should be '224', '192', '160', or '128',
     but found '%s' for architecture '%s'""",
              size_string, architecture)
          return None
        if len(parts) == 3:
          is_quantized = False
        else:
          if parts[3] != 'quantized':
            tf.logging.error(
                "Couldn't understand architecture suffix '%s' for '%s'", parts[3],
                architecture)
            return None
          is_quantized = True
        data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'
        data_url += version_string + '_' + size_string + '_frozen.tgz'
        bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'
        bottleneck_tensor_size = 1001
        input_width = int(size_string)
        input_height = int(size_string)
        input_depth = 3
        resized_input_tensor_name = 'input:0'
        if is_quantized:
          model_base_name = 'quantized_graph.pb'
        else:
          model_base_name = 'frozen_graph.pb'
        model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string
        model_file_name = os.path.join(model_dir_name, model_base_name)
        input_mean = 127.5
        input_std = 127.5
      else:
        tf.logging.error("Couldn't understand architecture name '%s'", architecture)
        raise ValueError('Unknown architecture', architecture)

      return {
          'data_url': data_url,
          'bottleneck_tensor_name': bottleneck_tensor_name,
          'bottleneck_tensor_size': bottleneck_tensor_size,
          'input_width': input_width,
          'input_height': input_height,
          'input_depth': input_depth,
          'resized_input_tensor_name': resized_input_tensor_name,
          'model_file_name': model_file_name,
          'input_mean': input_mean,
          'input_std': input_std,
      }
</code>```

The compelete code is available here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py

答: From SNPE SDK v1.8.0, TensorFlow's reshape layer get supported.

Body:
I had retrained inception v3 model for a custom dataset.
But after retraining when i look at the TenosorGraph i found that a layer named as reshape followed by a fully connected layer is added.
I have to run the model on an embedded device using snapdragonneural processing engine(SNPE) but it doesnt support reshape layer as of now to run on DSP.

Is there a possible way of retraining inception v3 without adding reshape layer.
Below is the retrain code where the reshape layer is added.

enter code here
              def create_model_info(architecture):
  """Given the name of a model architecture, returns information about it.

  There are different base image recognition pretrained models that can be
  retrained using transfer learning, and this function translates from the name
  of a model to the attributes that are needed to download and train with it.

  Args:
    architecture: Name of a model architecture.

  Returns:
    Dictionary of information about the model, or None if the name isn't
    recognized

  Raises:
    ValueError: If architecture name is unknown.
  """
  architecture = architecture.lower()
  if architecture == 'inception_v3':
    # pylint: disable=line-too-long
    data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
    # pylint: enable=line-too-long
    bottleneck_tensor_name = 'pool_3/_reshape:0'
    bottleneck_tensor_size = 2048
    input_width = 299
    input_height = 299
    input_depth = 3
    resized_input_tensor_name = 'Mul:0'
    model_file_name = 'classify_image_graph_def.pb'
    input_mean = 128
    input_std = 128
      elif architecture.startswith('mobilenet_'):
        parts = architecture.split('_')
        if len(parts) != 3 and len(parts) != 4:
          tf.logging.error("Couldn't understand architecture name '%s'",
                           architecture)
          return None
        version_string = parts[1]
        if (version_string != '1.0' and version_string != '0.75' and
            version_string != '0.50' and version_string != '0.25'):
          tf.logging.error(
              """"The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25',
      but found '%s' for architecture '%s'""",
              version_string, architecture)
          return None
        size_string = parts[2]
        if (size_string != '224' and size_string != '192' and
            size_string != '160' and size_string != '128'):
          tf.logging.error(
              """The Mobilenet input size should be '224', '192', '160', or '128',
     but found '%s' for architecture '%s'""",
              size_string, architecture)
          return None
        if len(parts) == 3:
          is_quantized = False
        else:
          if parts[3] != 'quantized':
            tf.logging.error(
                "Couldn't understand architecture suffix '%s' for '%s'", parts[3],
                architecture)
            return None
          is_quantized = True
        data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'
        data_url += version_string + '_' + size_string + '_frozen.tgz'
        bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'
        bottleneck_tensor_size = 1001
        input_width = int(size_string)
        input_height = int(size_string)
        input_depth = 3
        resized_input_tensor_name = 'input:0'
        if is_quantized:
          model_base_name = 'quantized_graph.pb'
        else:
          model_base_name = 'frozen_graph.pb'
        model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string
        model_file_name = os.path.join(model_dir_name, model_base_name)
        input_mean = 127.5
        input_std = 127.5
      else:
        tf.logging.error("Couldn't understand architecture name '%s'", architecture)
        raise ValueError('Unknown architecture', architecture)

      return {
          'data_url': data_url,
          'bottleneck_tensor_name': bottleneck_tensor_name,
          'bottleneck_tensor_size': bottleneck_tensor_size,
          'input_width': input_width,
          'input_height': input_height,
          'input_depth': input_depth,
          'resized_input_tensor_name': resized_input_tensor_name,
          'model_file_name': model_file_name,
          'input_mean': input_mean,
          'input_std': input_std,
      }

The compelete code is available here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py