问:
Warning: touchID deprecated in iOS 11.0
I'm supporting Touch ID and Face ID within my app. To support older versions of iOS I'm using the following code:

```<code>if #available(iOS 11.0, *) {
    biometricsNotEnrolled = LAError.biometryNotEnrolled
    biometricsLocked = LAError.biometryLockout
} else {
    biometricsNotEnrolled = LAError.touchIDNotEnrolled
    biometricsLocked = LAError.touchIDLockout
}

switch(error) {
case biometricsNotEnrolled:
    // Do stuff
case LAError.passcodeNotSet:
    // Do stuff
case biometricsLocked:
    // Do stuff
default:
    // Do stuff
}
</code>```

But when I compile I will get the following warnings:

```<code>warning: 'touchIDLockout' was deprecated in iOS 11.0: use LAErrorBiometryLockout

warning: 'touchIDNotEnrolled' was deprecated in iOS 11.0: use LAErrorBiometryNotEnrolled

warning: 'touchIDNotAvailable' was deprecated in iOS 11.0: use LAErrorBiometryNotAvailable
</code>```

How can I get rid of the warning?

答:
Your project or target version can solve this problem.

Here are tested you code in both versions - iOS 11.x & iOS 10.x

If your project target version is iOS 11+ then it will show your this warning as according Apple Document for LAError.Code, these values are deprecated in iOS 11.0.

Test Result - iOS 11.x

Test Result - iOS 10.x

Title: Warning: touchID deprecated in iOS 11.0

Body:
I'm supporting Touch ID and Face ID within my app. To support older versions of iOS I'm using the following code:

if #available(iOS 11.0, *) {
    biometricsNotEnrolled = LAError.biometryNotEnrolled
    biometricsLocked = LAError.biometryLockout
} else {
    biometricsNotEnrolled = LAError.touchIDNotEnrolled
    biometricsLocked = LAError.touchIDLockout
}

switch(error) {
case biometricsNotEnrolled:
    // Do stuff
case LAError.passcodeNotSet:
    // Do stuff
case biometricsLocked:
    // Do stuff
default:
    // Do stuff
}

But when I compile I will get the following warnings:

warning: 'touchIDLockout' was deprecated in iOS 11.0: use LAErrorBiometryLockout

warning: 'touchIDNotEnrolled' was deprecated in iOS 11.0: use LAErrorBiometryNotEnrolled

warning: 'touchIDNotAvailable' was deprecated in iOS 11.0: use LAErrorBiometryNotAvailable

How can I get rid of the warning?


来源: stackexchange

问:
Python - create several CSV files
let's assume I have some code which creates some data, which I want to put in a csv-file. Therefore I'm using "to_csv". Now, I want to run the code several times, and want to have several csv files.

```<code>for i in xrange(1000):
     code
     to_csv("csv[i].csv")
</code>```

How can I do something like that?

答:
This doesn't really have anything to do with pandas. You simply use string formatting to generate a different file name.

```<code>for i in xrange(1000):  # should be xrange, not xrang
     # code
     df.to_csv('csv{}.csv'.format(i))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python - create several CSV files

Body:
let's assume I have some code which creates some data, which I want to put in a csv-file. Therefore I'm using "to_csv". Now, I want to run the code several times, and want to have several csv files.

for i in xrange(1000):
     code
     to_csv("csv[i].csv")

How can I do something like that?

Body:
This doesn't really have anything to do with pandas. You simply use string formatting to generate a different file name.

for i in xrange(1000):  # should be xrange, not xrang
     # code
     df.to_csv('csv{}.csv'.format(i))


问:
Selecting non-nested subnodes with JQuery
I have a HTML structure that contains nested divs with the container class:

```<code><div class="container" id="0">
  <div id="1">
    <div class="container" id="2">
      <div class="container" id="3"></div>
    </div>
    <div id="4">
      <div class="container" id="5"></div>
    </div>
  </div>
</div>
</code>```

This could include more divs and deeper/different nesting.

Starting from some point in the tree I'd like to find all containers in that subtree that are not nested within other containers. So for example from div #1 I'd like to find the divs #2 and #5, but not #3 (since it is nested in container #2 already found).

What would be the best way to accomplish this?

答:
```<code>function getOuterContainers(el) {

    if (el.length == 0)
        return $([]);
    else
        return el.children('.container').add( getOuterContainers(el.children(':not(.container)')) );

}
</code>```

check it out: http://jsfiddle.net/GZ3Tx/

ContentLicense: CC BY-SA 2.5

Body:
I have a HTML structure that contains nested divs with the container class:

This could include more divs and deeper/different nesting.

Starting from some point in the tree I'd like to find all containers in that subtree that are not nested within other containers. So for example from div #1 I'd like to find the divs #2 and #5, but not #3 (since it is nested in container #2 already found).

What would be the best way to accomplish this?

Body:
function getOuterContainers(el) {

    if (el.length == 0)
        return $([]);
    else
        return el.children('.container').add( getOuterContainers(el.children(':not(.container)')) );

}

check it out: http://jsfiddle.net/GZ3Tx/


问:
Get the sequence with existing field in odoo 10
I need to get the order number related with its service order. Each service order has many bench orders. E.g.: If the service order number is 223 the bench orders related to that are 223-1, 223-2, 223-3... if SO number is 553, bench order numbers must be 553-1, 553-2, 553-3, etc.

I tried it several ways and I failed to do it. Please help me. I used Odoo sequence to do that, but it did not give the output as I want. Here is my code: (E.g.: 223 means work authorization number).

```<code>class MyDepots_so(models.Model):
    _name = 'my_depots_so'

    so_parts_ids = fields.One2many('tiq_so_parts', 'so_p_id', string='Add Part Details', invisible='1')
    so_bo_ids  = fields.One2many('my_depots.so_bo',
    so_work_authorization = fields.Integer("Work Authorization#")

class SO_Parts(models.Model):
    _name = 'tiq_so_parts'

    so_p_id = fields.Many2one('my_depots_so',string='Add Service Order Part', invisible='1')

    @api.model
    def create(self, vals):
        sequence     = self.env['ir.sequence'].next_by_code('so.benchorder') or '/'
        str_sequence = str(sequence)

        query = """SELECT so_work_authorization FROM my_depots_so WHERE id=%d """ % (so_p_id)
        self.env.cr.execute(query)
        result = self.env.cr.fetchall()
        result_number = json.dumps(result, ensure_ascii=False)
        strip_number = result_number.strip('\' \" [] ')
        work_auth_no = str(strip_number)
        work_auth_no += "-"
        work_auth_no += str_sequence
</code>```

答:
Ok, I think you are looking for something like this (I added a field to your tiq_so_parts model since you have to store the subsequence somewhere -where were you storing the 223-1, 223-2, 223-3... values?
 I created the field part_sequence to store these values-).

```<code>class MyDepots_so(models.Model):
    _name = 'my_depots_so'

    so_parts_ids = fields.One2many('tiq_so_parts', 'so_p_id', string='Add Part Details', invisible='1')
    so_bo_ids = fields.One2many('my_depots.so_bo',
    so_work_authorization = fields.Integer("Work Authorization#")

class SO_Parts(models.Model):
    _name = 'tiq_so_parts'

    so_p_id = fields.Many2one('my_depots_so',string='Add Service Order Part', invisible='1')
    part_sequence = fields.Char(string='Part Sequence')

    @api.model
    def create(self, vals):
        so_part = super(SO_Parts, self).create(vals)
        so_p_id = so_part.so_p_id
        main_sequence = so_p_id.so_work_authorization
        part_sequence = len(so_p_id.so_parts_ids)
        so_part.write({
            'part_sequence': str(main_sequence) + '-' + str(part_sequence),
        })
        return so_part
</code>```

Body:
I need to get the order number related with its service order. Each service order has many bench orders. E.g.: If the service order number is 223 the bench orders related to that are 223-1, 223-2, 223-3... if SO number is 553, bench order numbers must be 553-1, 553-2, 553-3, etc.

I tried it several ways and I failed to do it. Please help me. I used Odoo sequence to do that, but it did not give the output as I want. Here is my code: (E.g.: 223 means work authorization number).

class MyDepots_so(models.Model):
    _name = 'my_depots_so'

    so_parts_ids = fields.One2many('tiq_so_parts', 'so_p_id', string='Add Part Details', invisible='1')
    so_bo_ids  = fields.One2many('my_depots.so_bo',
    so_work_authorization = fields.Integer("Work Authorization#")

class SO_Parts(models.Model):
    _name = 'tiq_so_parts'

    so_p_id = fields.Many2one('my_depots_so',string='Add Service Order Part', invisible='1')

    @api.model
    def create(self, vals):
        sequence     = self.env['ir.sequence'].next_by_code('so.benchorder') or '/'
        str_sequence = str(sequence)

        query = """SELECT so_work_authorization FROM my_depots_so WHERE id=%d """ % (so_p_id)
        self.env.cr.execute(query)
        result = self.env.cr.fetchall()
        result_number = json.dumps(result, ensure_ascii=False)
        strip_number = result_number.strip('\' \" [] ')
        work_auth_no = str(strip_number)
        work_auth_no += "-"
        work_auth_no += str_sequence

Body:
Ok, I think you are looking for something like this (I added a field to your tiq_so_parts model since you have to store the subsequence somewhere -where were you storing the 223-1, 223-2, 223-3... values?
 I created the field part_sequence to store these values-).

class MyDepots_so(models.Model):
    _name = 'my_depots_so'

    so_parts_ids = fields.One2many('tiq_so_parts', 'so_p_id', string='Add Part Details', invisible='1')
    so_bo_ids = fields.One2many('my_depots.so_bo',
    so_work_authorization = fields.Integer("Work Authorization#")

class SO_Parts(models.Model):
    _name = 'tiq_so_parts'

    so_p_id = fields.Many2one('my_depots_so',string='Add Service Order Part', invisible='1')
    part_sequence = fields.Char(string='Part Sequence')

    @api.model
    def create(self, vals):
        so_part = super(SO_Parts, self).create(vals)
        so_p_id = so_part.so_p_id
        main_sequence = so_p_id.so_work_authorization
        part_sequence = len(so_p_id.so_parts_ids)
        so_part.write({
            'part_sequence': str(main_sequence) + '-' + str(part_sequence),
        })
        return so_part


问:
Can I use (two-dot) range notation for revisions in TortoiseGit?
I want to show only the revisions of a branch since the fork from the master.

At the git bash I can do the following:
git log master..mybranch

Can I do the same in TortoiseGit?

答:
You can run the log dialog from command line using tortoisegitproc /command:log /range:master..mybranch.

It is also possible to get this using the GUI: In LogDialog click on the branch indicator in the upper left. Then select the two branches/refs you want to see and click on OK. Here a context menu appears where you can select "master..mybranch". See:

Or you can right click on the selected branches, and here is also a "Show log of master..mybranch" item in context menu. See:

It opens a NEW Log Message dialog for "master..mybranch".


问:
Use of data-toggle="tooltip" in  or
when I use data-toggle="tooltip" with the tag <h>, it works normally:

```<code>    <h3 data-toggle="tooltip" data-placement="right"
    title="example"> example </h3>
</code>```

but when I try to use with //, this does not work normally, it just shows the normal tool-tip, without any style.

I'm starting with JavaScript and CSS, so I'm a bit stuck.

What can I do to solve this?

(I'm aware there are similar questions to this but they haven't solved my problem)

Thanks in advance.

答:
It works for me: https://jsfiddle.net/fgcb27aa/

Check if you have tooltips enabled in your current page.

```<code>$(document).ready(function() {
  $('[data-toggle="tooltip"]').tooltip();
});
</code>```

Title: Use of data-toggle="tooltip" in <a> or <span>

Body:
when I use data-toggle="tooltip" with the tag <h>, it works normally:

 example

but when I try to use with //, this does not work normally, it just shows the normal tool-tip, without any style.

I'm starting with JavaScript and CSS, so I'm a bit stuck.

What can I do to solve this?

(I'm aware there are similar questions to this but they haven't solved my problem)

Thanks in advance.

Body:
It works for me: https://jsfiddle.net/fgcb27aa/

Check if you have tooltips enabled in your current page.

$(document).ready(function() {
  $('[data-toggle="tooltip"]').tooltip();
});


问:
Compiling std::transforms with argument atan2/pow fails with clang (but works with gcc)
There seem to be some difference in how template parameters are resolved for clang and gcc. Or maybe clang does not consider atan2 and pow binary operations but gcc does.

The code sample below does not make much sense on its own but recreates the issue in a minimal fashion:

```<code>#include <vector>
#include <algorithm>
#include <cmath>

#define TRANSFORM_MACRO(op,func)                                          \
    template<class T>                                                     \
    std::vector<T> &trans_##op(const std::vector<T> &a, const std::vector<T> &b, std::vector<T> &dst) { \
      std::transform(a.begin(), a.end(), b.begin(), dst.begin(), func);   \
      return dst;                                                         \
    }                                                                     \
    template std::vector<float> &trans_##op(const std::vector<float>&, const std::vector<float>&, std::vector<float>&);     \
    template std::vector<double> &trans_##op(const std::vector<double>&, const std::vector<double>&, std::vector<double>&);

TRANSFORM_MACRO(arctan2, ::atan2)

int main() {
    return 0;
}
</code>```

Compiling this with GCC (5.4 Ubuntu; 6.0 OSX Sierra) works fine. Using clang (900.0.37) returns the following error:

```<code>/Users/alneuman/CLionProjects/temptest/main.cpp:15:1: error: no matching function for call to 'transform'
TRANSFORM_MACRO(arctan2, atan2)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/.../CLionProjects/temptest/main.cpp:9:7: note: expanded from macro 'TRANSFORM_MACRO'
      std::transform(a.begin(), a.end(), b.begin(), dst.begin(), func);       \
      ^~~~~~~~~~~~~~
/Users/.../CLionProjects/temptest/main.cpp:15:1: note: in instantiation of function template specialization 'trans_arctan2<float>' requested here
/Users/.../CLionProjects/temptest/main.cpp:12:34: note: expanded from macro 'TRANSFORM_MACRO'
    template std::vector<float> &trans_##op(const std::vector<float>&, const std::vector<float>&, std::vector<float>&);     \
                                 ^
<scratch space>:22:1: note: expanded from here
trans_arctan2
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:1932:1: note: candidate template ignored: couldn't infer template argument '_BinaryOperation'
transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:1922:1: note: candidate function template not viable: requires 4 arguments, but 5 were provided
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
</code>```

The problem seems to be that GCC uses the builtin versions of atan2 and pow which only have one definition and therefore do not need specification. Clang seems to fall back to std::atan2/pow which have multiple definitions. Clang also has a __builtin_atan2 but this cannot be used with std::transform as it has to be called directly (considering the compiler output).

答:
Thanks to @MarcGlisse I guess I figured out what causes the different behaviour for Clang and GCC. The :: notation asks to look for a function in the global namespace. GCC has atan2 builtin with a double signature in the global namespace but Clang does not. The std version Clang is using features a double and a float signature. Therefore, when std::atan2 is being used, the compiler requires more specific information which overload should be used as std::atan2 has (at least) three overloads: float, double and long double. This can be achieved with a static cast. The float cast obviously fails when GCC's built version is used since double to float cannot be casted statically.

I went for TRANSFORM_MACRO(arctan2, static_cast<T(*)(T, T)>(std::atan2)) which resolves the ambiguity in the macro and also makes GCC and Clang use the same version of atan2.

Body:
There seem to be some difference in how template parameters are resolved for clang and gcc. Or maybe clang does not consider atan2 and pow binary operations but gcc does.

The code sample below does not make much sense on its own but recreates the issue in a minimal fashion:

#include <vector>
#include <algorithm>
#include <cmath>

#define TRANSFORM_MACRO(op,func)                                          \
    template<class T>                                                     \
    std::vector<T> &trans_##op(const std::vector<T> &a, const std::vector<T> &b, std::vector<T> &dst) { \
      std::transform(a.begin(), a.end(), b.begin(), dst.begin(), func);   \
      return dst;                                                         \
    }                                                                     \
    template std::vector<float> &trans_##op(const std::vector<float>&, const std::vector<float>&, std::vector<float>&);     \
    template std::vector<double> &trans_##op(const std::vector<double>&, const std::vector<double>&, std::vector<double>&);

TRANSFORM_MACRO(arctan2, ::atan2)

int main() {
    return 0;
}

Compiling this with GCC (5.4 Ubuntu; 6.0 OSX Sierra) works fine. Using clang (900.0.37) returns the following error:

/Users/alneuman/CLionProjects/temptest/main.cpp:15:1: error: no matching function for call to 'transform'
TRANSFORM_MACRO(arctan2, atan2)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/.../CLionProjects/temptest/main.cpp:9:7: note: expanded from macro 'TRANSFORM_MACRO'
      std::transform(a.begin(), a.end(), b.begin(), dst.begin(), func);       \
      ^~~~~~~~~~~~~~
/Users/.../CLionProjects/temptest/main.cpp:15:1: note: in instantiation of function template specialization 'trans_arctan2<float>' requested here
/Users/.../CLionProjects/temptest/main.cpp:12:34: note: expanded from macro 'TRANSFORM_MACRO'
    template std::vector<float> &trans_##op(const std::vector<float>&, const std::vector<float>&, std::vector<float>&);     \
                                 ^
<scratch space>:22:1: note: expanded from here
trans_arctan2
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:1932:1: note: candidate template ignored: couldn't infer template argument '_BinaryOperation'
transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:1922:1: note: candidate function template not viable: requires 4 arguments, but 5 were provided
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)

The problem seems to be that GCC uses the builtin versions of atan2 and pow which only have one definition and therefore do not need specification. Clang seems to fall back to std::atan2/pow which have multiple definitions. Clang also has a __builtin_atan2 but this cannot be used with std::transform as it has to be called directly (considering the compiler output).


问:
Creating a JavaScript callback in an iframe
UPDATE: The back-end service was powered by an ASP.Net AJAX Web Service proxy.

1) The main page has two global objects, one for the back end connections (Svc) and another for handling the DOM (Main). It also dynamically loads documents into an iframe.

2) These iframes need to access services provided by Svc, and also supply a callback function.

3) The problem - passing a function created in the iframe to the parent frame, it's treated as an object not a function and cannot be invoked.

Can anyone provide a better solution than what I've got currently in the iframe:

```<code>var Main = parent.Main,
    Svc = parent.Svc;

Svc.method(data, Main.createCallback(
    function(response) {}
));
</code>```

and in the parent frame:

```<code>Main.createCallback = function(func) {
    return function() {
        func.apply(func, arguments);
    }
}
</code>```

答:
if you override the iFrame's function from the main, the main scope will then be used.
The inverse problem can be seen here, in your case, you just override the frame's function itself i.e:

document.getElementById('yourFrameID').contentWindow.targetFunctionInFrame = targetFunctionInMain;

Bonus: if you can modify the iFrame's code, I would suggest to:

In the frame:

make a placeholder function callbackParent() {}

add a call to this function into your iframe code, so that you just have to override the callbackParent from your main.

In the main:

make the function which should be invoked function doStuff() {}

override the function as described above document.getElementById('yourFrameID').contentWindow.callBackParent = doStuff;

Body:
UPDATE: The back-end service was powered by an ASP.Net AJAX Web Service proxy.

1) The main page has two global objects, one for the back end connections (Svc) and another for handling the DOM (Main). It also dynamically loads documents into an iframe.

2) These iframes need to access services provided by Svc, and also supply a callback function.

3) The problem - passing a function created in the iframe to the parent frame, it's treated as an object not a function and cannot be invoked.

Can anyone provide a better solution than what I've got currently in the iframe:

var Main = parent.Main,
    Svc = parent.Svc;

Svc.method(data, Main.createCallback(
    function(response) {}
));

and in the parent frame:

Main.createCallback = function(func) {
    return function() {
        func.apply(func, arguments);
    }
}

ContentLicense: CC BY-SA 4.0


问:
Drop rows of selected rows with null values
I want to drop rows with null values in both column a and b.
I have managed to find those rows with:

```<code>df[(df['a'].isnull()) & (df['b'].isnull())]
</code>```

How do I drop these rows?

答:
Invert mask by ~:

```<code>df[~(df['a'].isnull() & df['b'].isnull())]
</code>```

Or:

```<code>df[df[['a','b']].notnull().any(1)]
</code>```

Body:
I want to drop rows with null values in both column a and b.
I have managed to find those rows with:

df[(df['a'].isnull()) & (df['b'].isnull())]

How do I drop these rows?

Body:
Invert mask by ~:

df[~(df['a'].isnull() & df['b'].isnull())]

Or:

df[df[['a','b']].notnull().any(1)]


问:
IIS/ASP.NET responds with cache-control: private for all requests
Why does all responses from ASP.NET contain Cache-Control: private? Even a 404 response? Is there something in IIS that sets this default value, and is there a way to configure it? Or is there something in ASP.NET that sets this?

For dynamic content (that is, all MVC results) I would not like it to be cached by the browser, since it is dynamic and can change at any time. Static content is hosted on a CDN, so is not served by IIS.

Edit:

To clarify, I understand very well what Cache-Control: private is, the difference between private, public, no-store, etc and how/when to use them. The question I have is why Cache-Control: private is added by default by IIS/ASP.NET and how to prevent it from being added by default. I understand that it can be useful to cache dynamic pages, but in my application I don't want to cache dynamic pages/responses. For example, I don't want XHR JSON responses to be cached, since they contain dynamic content. Unfortunately the server adds Cache-Control: private to all responses automatically, so I have to manually override it everywhere.

How to reproduce: Open visual studio and create a new ASP.NET Framework (yes, framework, no not Core. We are not able to migrate our system to core yet) solution with an MVC project. Now start the project in IIS Express (just press the play button), and use F12 devtools in the browser to look at the http response. You will see that it contains Cache-Control: private. My question is, what adds this header, and how can I prevent it from being added by default?

答:
what adds this header?

The IIS 7 and later (included in the default installation) sends it to Web clients as one of the cache-related HTTP headers.

and how can I prevent it from being added by default?

I describe two ways of disabling cache mechanism (server-side approach and client-side approach) with a focus on server-side based on your question:

Server-Side Approach

Follow this steps Inside the Internet Information Services (IIS) Manager to change Cache-Control value (while I think this works for static contents):

In the Connections pane, go to the site, application, or
directory for which you want to disable caching.

In the Home pane, double-click HTTP Response Headers.

Click Set Common Headers ... in the Actions pane.

Check the box to expire Web content, select the option to expire after a specific interval or at a specific time,
and then click OK.

One way is to annotate your controller as follows which is quite powerful and the response headers contain a Cache-Control: public, max-age=0 header.:

```<code>[OutputCache(Duration = 0)]
public class SomeController : Controller  {

}
</code>```

You can also Define a cache profile in your application's Web.config file and in the profile, include duration and varyByParam settings:

```<code><caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <add name="nocache" duration="0"
        varyByParam="none" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>
</code>```

Then use it by the [OutputCache CacheProfile="nocache"] before the action/controller.

Note that there is a configuration in web.config file (following) which won’t prevent caching. Instead it just indicates that no kind of caching mechanism should be applied. By just disabling the output cache we get the default cache headers used by ASP.net MVC which falls back to Cache-Control: private, thus again opening the browser the possibility to cache requests.

```<code><caching>
    <outputCache enableOutputCache="false" />
</caching>
</code>```

Client-Side Approach

Using cache: false inside your js request like:

```<code>$.ajax({
    type: 'GET',
    cache: false,
    url: '/nation',
    ...
});
</code>```

For additional information, visit:

Client Cache <clientCache>

How to: Set the Cacheability of an ASP.NET Page Declaratively

output-caching-in-aspnet-mvc

Body:
what adds this header?

The IIS 7 and later (included in the default installation) sends it to Web clients as one of the cache-related HTTP headers.

and how can I prevent it from being added by default?

I describe two ways of disabling cache mechanism (server-side approach and client-side approach) with a focus on server-side based on your question:

Server-Side Approach

Follow this steps Inside the Internet Information Services (IIS) Manager to change Cache-Control value (while I think this works for static contents):

In the Connections pane, go to the site, application, or
directory for which you want to disable caching.

In the Home pane, double-click HTTP Response Headers.

Click Set Common Headers ... in the Actions pane.

Check the box to expire Web content, select the option to expire after a specific interval or at a specific time,
and then click OK.

One way is to annotate your controller as follows which is quite powerful and the response headers contain a Cache-Control: public, max-age=0 header.:

[OutputCache(Duration = 0)]
public class SomeController : Controller  {

}

You can also Define a cache profile in your application's Web.config file and in the profile, include duration and varyByParam settings:

<caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <add name="nocache" duration="0"
        varyByParam="none" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>

Then use it by the [OutputCache CacheProfile="nocache"] before the action/controller.

Note that there is a configuration in web.config file (following) which won’t prevent caching. Instead it just indicates that no kind of caching mechanism should be applied. By just disabling the output cache we get the default cache headers used by ASP.net MVC which falls back to Cache-Control: private, thus again opening the browser the possibility to cache requests.

<caching>
    <outputCache enableOutputCache="false" />
</caching>

Client-Side Approach

Using cache: false inside your js request like:

$.ajax({
    type: 'GET',
    cache: false,
    url: '/nation',
    ...
});

For additional information, visit:

Client Cache <clientCache>

How to: Set the Cacheability of an ASP.NET Page Declaratively

output-caching-in-aspnet-mvc


问:
Applescript Realistic Keystroke
Is it possible to use Applescript to type text at a randomised speed quickly & efficiently?  I have the following script:

On run {input, parameters}:

```<code>tell application "System Events"
    keystroke "H"
    delay 0.2
    keystroke "i"
    delay 0.2
    keystroke " "
    delay 0.2
    keystroke "t"
    delay 0.2
    keystroke "h"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke "r"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke "!"
    delay 0.1
    key code 36
    delay 0.5
    keystroke "H"
    delay 0.2
    keystroke "o"
    delay 0.1
    keystroke "w"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "a"
    delay 0.2
    keystroke "r"
    delay 0.1
    keystroke "e"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "y"
    delay 0.2
    keystroke "o"
    delay 0.2
    keystroke "u"
    delay 0.1
    keystroke "?"
    delay 0.2
    key code 36
    delay 1.0
    keystroke "W"
    delay 0.2
    keystroke "h"
    delay 0.2
    keystroke "e"
    delay 0.1
    keystroke "r"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "d"
    delay 0.2
    keystroke "o"
    delay 0.2
    keystroke " "
    delay 0.2
    keystroke "y"
    delay 0.2
    keystroke "o"
    delay 0.1
    keystroke "u"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "w"
    delay 0.2
    keystroke "a"
    delay 0.1
    keystroke "n"
    delay 0.2
    keystroke "t"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "t"
    delay 0.3
    keystroke "o"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "b"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke "g"
    delay 0.1
    keystroke "i"
    delay 0.2
    keystroke "n"
    delay 0.1
    keystroke "?"
end tell

return input
end run
</code>```

I basically, want to type all of the words (for 1 line at least) in one keystroke (or similar command), and then use a random delay such as the below between each key.  Is it possible?

```<code>delay (random number from 0.05 to 1.0)
</code>```

答:
If you do not mind that there are no returns then use this:

```<code>delay 3

set new_array to "h, i, ,  t, h, e, r, e, !,  , h, o, w,  , a, r, e,  , y, o, u, ?,  , w, h, e, r, e,  , d, o,  , y, o, u,  , w, a, n, t,  , t, o,  , b, e, g, i, n, ?"
set AppleScript's text item delimiters to ", "
set the list_items to every text item of the new_array
set a to list_items
set b to count of list_items
set c to 0
tell application "System Events"
repeat b times
    set c to c + 1
    delay (random number from 0.05 to 0.3)
    keystroke item c of a
end repeat
end tell
</code>```

But if you want the returns then use this:

```<code>delay 3
set a to "h, i, ,  t, h, e, r, e, !"
set b to "h, o, w,  , a, r, e,  , y, o, u, ?"
set c to "w, h, e, r, e,  , d, o,  , y, o, u,  , w, a, n, t,  , t, o,  , b, e, g, i, n, ?"
set AppleScript's text item delimiters to ", "
set the list_items to every text item of the a
set d to list_items
set e to count of list_items
set f to 0
set AppleScript's text item delimiters to ", "
set the m to every text item of the b
set g to m
set h to count of m
set i to 0
set AppleScript's text item delimiters to ", "
set the n to every text item of the c
set j to n
set k to count of n
set l to 0
tell application "System Events"
repeat e times
    set f to f + 1
    delay (random number from 0.05 to 0.3)
    keystroke item f of d
end repeat
key code 36
repeat h times
    set i to i + 1
    delay (random number from 0.05 to 0.3)
    keystroke item i of g
end repeat
key code 36
repeat k times
    set l to l + 1
    delay (random number from 0.05 to 0.3)
    keystroke item l of j
end repeat
end tell
</code>```

Title: Applescript Realistic Keystroke

Body:
Is it possible to use Applescript to type text at a randomised speed quickly & efficiently?  I have the following script:

On run {input, parameters}:

tell application "System Events"
    keystroke "H"
    delay 0.2
    keystroke "i"
    delay 0.2
    keystroke " "
    delay 0.2
    keystroke "t"
    delay 0.2
    keystroke "h"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke "r"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke "!"
    delay 0.1
    key code 36
    delay 0.5
    keystroke "H"
    delay 0.2
    keystroke "o"
    delay 0.1
    keystroke "w"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "a"
    delay 0.2
    keystroke "r"
    delay 0.1
    keystroke "e"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "y"
    delay 0.2
    keystroke "o"
    delay 0.2
    keystroke "u"
    delay 0.1
    keystroke "?"
    delay 0.2
    key code 36
    delay 1.0
    keystroke "W"
    delay 0.2
    keystroke "h"
    delay 0.2
    keystroke "e"
    delay 0.1
    keystroke "r"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "d"
    delay 0.2
    keystroke "o"
    delay 0.2
    keystroke " "
    delay 0.2
    keystroke "y"
    delay 0.2
    keystroke "o"
    delay 0.1
    keystroke "u"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "w"
    delay 0.2
    keystroke "a"
    delay 0.1
    keystroke "n"
    delay 0.2
    keystroke "t"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "t"
    delay 0.3
    keystroke "o"
    delay 0.2
    keystroke " "
    delay 0.1
    keystroke "b"
    delay 0.2
    keystroke "e"
    delay 0.2
    keystroke "g"
    delay 0.1
    keystroke "i"
    delay 0.2
    keystroke "n"
    delay 0.1
    keystroke "?"
end tell

return input
end run

I basically, want to type all of the words (for 1 line at least) in one keystroke (or similar command), and then use a random delay such as the below between each key.  Is it possible?

delay (random number from 0.05 to 1.0)

Body:
If you do not mind that there are no returns then use this:

delay 3

set new_array to "h, i, ,  t, h, e, r, e, !,  , h, o, w,  , a, r, e,  , y, o, u, ?,  , w, h, e, r, e,  , d, o,  , y, o, u,  , w, a, n, t,  , t, o,  , b, e, g, i, n, ?"
set AppleScript's text item delimiters to ", "
set the list_items to every text item of the new_array
set a to list_items
set b to count of list_items
set c to 0
tell application "System Events"
repeat b times
    set c to c + 1
    delay (random number from 0.05 to 0.3)
    keystroke item c of a
end repeat
end tell

But if you want the returns then use this:

delay 3
set a to "h, i, ,  t, h, e, r, e, !"
set b to "h, o, w,  , a, r, e,  , y, o, u, ?"
set c to "w, h, e, r, e,  , d, o,  , y, o, u,  , w, a, n, t,  , t, o,  , b, e, g, i, n, ?"
set AppleScript's text item delimiters to ", "
set the list_items to every text item of the a
set d to list_items
set e to count of list_items
set f to 0
set AppleScript's text item delimiters to ", "
set the m to every text item of the b
set g to m
set h to count of m
set i to 0
set AppleScript's text item delimiters to ", "
set the n to every text item of the c
set j to n
set k to count of n
set l to 0
tell application "System Events"
repeat e times
    set f to f + 1
    delay (random number from 0.05 to 0.3)
    keystroke item f of d
end repeat
key code 36
repeat h times
    set i to i + 1
    delay (random number from 0.05 to 0.3)
    keystroke item i of g
end repeat
key code 36
repeat k times
    set l to l + 1
    delay (random number from 0.05 to 0.3)
    keystroke item l of j
end repeat
end tell


问:
Is there an equivalent to __MODULE__ for named functions in Elixir/ Erlang?
Is there an equivalent for retrieving the name of a function just like like __MODULE__ retrieves the name of a Module in Elixir/Erlang?

Example:

```<code>defmodule Demo do
  def home_menu do
    module_name = __MODULE__
    func_name = :home_menu
    # is there a __FUNCTION__
  end
End
</code>```

EDITED

The selected answer works,

but calling the returned function name with apply/3 yields this error:

```<code>[error] %UndefinedFunctionError{arity: 4, exports: nil, function: :public_home, module: Demo, reason: nil}
</code>```

I have a function :

```<code>defp public_home(u, m, msg, reset) do

end
</code>```

The function in question will strictly be called within its module.

Is there a way to dynamically call a private function by name within its own module?

答:
```<code>▶ defmodule M, do: def m, do: __ENV__.function
▶ M.m
#⇒ {:m, 0}
</code>```

Essentially, __ENV__ structure contains everything you might need.

Body:
Is there an equivalent for retrieving the name of a function just like like __MODULE__ retrieves the name of a Module in Elixir/Erlang?

Example:

defmodule Demo do
  def home_menu do
    module_name = __MODULE__
    func_name = :home_menu
    # is there a __FUNCTION__
  end
End

EDITED

The selected answer works,

but calling the returned function name with apply/3 yields this error:

[error] %UndefinedFunctionError{arity: 4, exports: nil, function: :public_home, module: Demo, reason: nil}

I have a function :

defp public_home(u, m, msg, reset) do

end

The function in question will strictly be called within its module.

Is there a way to dynamically call a private function by name within its own module?

Body:
▶ defmodule M, do: def m, do: __ENV__.function
▶ M.m
#⇒ {:m, 0}

Essentially, __ENV__ structure contains everything you might need.


问:
Connect Pipes With the Series of Manhole in Autodesk Dynamo
I’ve created a script that instantiated manhole on a series of points that were generated on a property line. Now I’d like to instantiate a pipe and connect its open and close end with each next manhole in the series. Would appreciate if someone suggest how do I achieve this functionality with dynamo. Thank you in advance.

答: If the manholes are defined as pipe fittings with appropriate connectors, the pipes will connect themselves to them automatically, as illustrated by my series of articles on creating a rolling offset. </p>


问:
How to get event target/this without putting the event listener in the HTML tag?
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use

$(document).ready(function(){})

I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?

//$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}</code>```

<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>```

Thanks in advance!

PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.

PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D

PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)

答:
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:

```<code>var chosen = $(this).prop('value');
</code>```

I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.

UPDATE

Just saw your commented out code:

```<code>$("button").click(showImage(this)); // When a button is clicked
 // call the function returned by showImage(this).. err it doesnt return
 // a function so it fails.
</code>```

you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.

It should actually be:

```<code>$("button").click(showImage); // when a button is clicked
 // call the function showImage with this=<clicked button> and param=event
</code>```

and this will be automatically set inside the function as event.currentTarget

$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = $(this).prop('value');
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
  $('.myclass').on('click', showImage);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}</code>```

<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>```

Body:
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use

$(document).ready(function(){})

I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?

//$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});

body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}

<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>

Thanks in advance!

PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.

PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D

PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)

Body:
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:

var chosen = $(this).prop('value');

I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.

UPDATE

Just saw your commented out code:

$("button").click(showImage(this)); // When a button is clicked
 // call the function returned by showImage(this).. err it doesnt return
 // a function so it fails.

you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.

It should actually be:

$("button").click(showImage); // when a button is clicked
 // call the function showImage with this=<clicked button> and param=event

and this will be automatically set inside the function as event.currentTarget

$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = $(this).prop('value');
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
  $('.myclass').on('click', showImage);
});

body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>


问:
Export array data from MATLAB to C#
is it possible to export an array from MATLAB to C# directly, without the need to copying and pasting the value in C#?

Thanks

答: I would just save the array to a text file in MATLAB and read in the text file from C#.</p>

Title: Export array data from MATLAB to C#


问:
inability to read from a file corectly in C
Hey guys im new here and im working on some code that is meant to read in 2 files.  The file opens just fine, everything gets allocated ok later on down the line, however, when I read in individual lines from the file thats when I run into issues.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
char filename1[100];
    //Seting the file name for entery and seting the limit to 100
    //this one is for my matrix//
FILE* fp1;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename1);
    //scans in the name of the first file the file type needs to be
included//

fp1 = fopen(filename1, "r");
    //This will open the file as entered by the user//
if (fp1 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
int i;
int row1;
int col1;

fscanf(fp1, "%d,", &row1);
printf("%d \n ", row1);
fscanf(fp1, "%d,", &col1);  //WHY IS THIS SCANING WRONG!!!!//
printf("%d \n ", col1);
    //This will scan for the number of rows and columns in the matrix//
    //thats all for reading in the first file//

char filename2[100];
    //Seting the file name for entery and seting the limit to 100//
FILE* fp2;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename2);
    //Scans in the name of the first file//

fp2 = fopen(filename2, "r");
    //This will open the file as entered by the user//
if (fp2 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
return 0;
}
</code>```

This is what I get when i compile and run the full program.  compiling

What should appear is a 5 and a 3 after loading in the data file.

the data is in the attached image but also here:

```<code>5
3
3.4,  6.5,  4.1
1.8,  3.3,  4.5
2.6,  7.4,  4.9
5.5,  6.1,  2.4
1.9,  2.7,  4.2
</code>```

Everything else in my code works just fine with the exception of that.

答:
The primary responsibility you have when taking any user input is to validate the return from your input functions (whatever they may be) and if also required, validate the input falls within required range of values. But the minimum validation required is the return of the function you are using.

Also be aware that scanf (and family) can leave characters unread in the input buffer (e.g. stdin) that must be accounted for before the next call based on the format specifier being used. (e.g. numeric format specifiers (%d, %x, %o, etc.. will ignore leading whitespace for you, "%c" and "%s" do not remove leading whitespace (though it can be handled by explicitly including whitespace in your format string). this is also why fgets (or POSIX getline) are recommended for user input.

Putting the pieces together and using a VLA to hold the values, you can do something like the following. The program expects the filename as the 1st argument to the program, (it will read from stdin by default if no argument is given) It will then read the row and col values before reading row x col double values into a variable length array call arr. It closes the file and then outputs the values stored in the VLA in row x col form:

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

int main (int argc, char **argv) {

    int row = 0, col = 0;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read and vailidate row & col */
    if (fscanf (fp, " %d %d", &row, &col) != 2) {
        fprintf (stderr, "error: failed to read row & col.\n");
        return 1;
    }
    double arr[row][col];                   /* VLA for arr */

    for (int i = 0; i < row; i++)           /* fill VLA */
        for (int j = 0; j < col; j++)
            if (fscanf (fp, " %lf%*c", &arr[i][j]) != 1) {
                fprintf (stderr, "error: line[%2d] read failure.\n", i);
                return 1;
            }

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (int i = 0; i < row; i++) { /* output values stored in arr */
        for (int j = 0; j < col; j++)
            printf (" %5.2f", arr[i][j]);
        putchar ('\n');
    }
    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/arrrd <dat/arrrd.txt
 3.40   6.50   4.10
 1.80   3.30   4.50
 2.60   7.40   4.90
 5.50   6.10   2.40
 1.90   2.70   4.20
</code>```

Look things over and let me know if you have further questions.

Body:
Hey guys im new here and im working on some code that is meant to read in 2 files.  The file opens just fine, everything gets allocated ok later on down the line, however, when I read in individual lines from the file thats when I run into issues.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
char filename1[100];
    //Seting the file name for entery and seting the limit to 100
    //this one is for my matrix//
FILE* fp1;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename1);
    //scans in the name of the first file the file type needs to be
included//

fp1 = fopen(filename1, "r");
    //This will open the file as entered by the user//
if (fp1 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
int i;
int row1;
int col1;

fscanf(fp1, "%d,", &row1);
printf("%d \n ", row1);
fscanf(fp1, "%d,", &col1);  //WHY IS THIS SCANING WRONG!!!!//
printf("%d \n ", col1);
    //This will scan for the number of rows and columns in the matrix//
    //thats all for reading in the first file//

char filename2[100];
    //Seting the file name for entery and seting the limit to 100//
FILE* fp2;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename2);
    //Scans in the name of the first file//

fp2 = fopen(filename2, "r");
    //This will open the file as entered by the user//
if (fp2 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
return 0;
}

This is what I get when i compile and run the full program.  compiling

What should appear is a 5 and a 3 after loading in the data file.

the data is in the attached image but also here:

5
3
3.4,  6.5,  4.1
1.8,  3.3,  4.5
2.6,  7.4,  4.9
5.5,  6.1,  2.4
1.9,  2.7,  4.2

Everything else in my code works just fine with the exception of that.

Body:
The primary responsibility you have when taking any user input is to validate the return from your input functions (whatever they may be) and if also required, validate the input falls within required range of values. But the minimum validation required is the return of the function you are using.

Also be aware that scanf (and family) can leave characters unread in the input buffer (e.g. stdin) that must be accounted for before the next call based on the format specifier being used. (e.g. numeric format specifiers (%d, %x, %o, etc.. will ignore leading whitespace for you, "%c" and "%s" do not remove leading whitespace (though it can be handled by explicitly including whitespace in your format string). this is also why fgets (or POSIX getline) are recommended for user input.

Putting the pieces together and using a VLA to hold the values, you can do something like the following. The program expects the filename as the 1st argument to the program, (it will read from stdin by default if no argument is given) It will then read the row and col values before reading row x col double values into a variable length array call arr. It closes the file and then outputs the values stored in the VLA in row x col form:

#include <stdio.h>

int main (int argc, char **argv) {

    int row = 0, col = 0;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read and vailidate row & col */
    if (fscanf (fp, " %d %d", &row, &col) != 2) {
        fprintf (stderr, "error: failed to read row & col.\n");
        return 1;
    }
    double arr[row][col];                   /* VLA for arr */

    for (int i = 0; i < row; i++)           /* fill VLA */
        for (int j = 0; j < col; j++)
            if (fscanf (fp, " %lf%*c", &arr[i][j]) != 1) {
                fprintf (stderr, "error: line[%2d] read failure.\n", i);
                return 1;
            }

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (int i = 0; i < row; i++) { /* output values stored in arr */
        for (int j = 0; j < col; j++)
            printf (" %5.2f", arr[i][j]);
        putchar ('\n');
    }
    return 0;
}

Example Use/Output

$ ./bin/arrrd <dat/arrrd.txt
 3.40   6.50   4.10
 1.80   3.30   4.50
 2.60   7.40   4.90
 5.50   6.10   2.40
 1.90   2.70   4.20

Look things over and let me know if you have further questions.


问:
Checking when a SQL Server SSL Server Authentication Certificate Expires
We have just implemented and forced SSL on a few SQL Servers and would like to automated the reporting on the expiration of the certificates.

I had a look at using the below PowerShell script available online, however it has issues with navigating the path and throws an error before traversing all the certificates. This is apparently a known issue?

```<code>invoke-command -ComputerName <servername> -ScriptBlock {
    Get-ChildItem -path 'cert:\' -Recurse  | where { $_.notafter -le (get-date).AddDays(60) -AND $_.notafter -gt (get-date)} | select thumbprint, subject
}
</code>```

Throws the below error

```<code>NotSpecified: (:) [Get-ChildItem], Win32Exception
</code>```

So I had a look to see if the SSL Server Authentication certificate was recorded in SQL Server and queried master.sys.certificates however it was not here.

How do I go about checking for an expiring SSL certificate on Windows Server 2012 R2 for SQL Server 2012+?

答: I found that limiting the certificate path to for example cert:\LocalMachine\ resolved the Powershell error and traversed all the certificates in that path

Body:
We have just implemented and forced SSL on a few SQL Servers and would like to automated the reporting on the expiration of the certificates.

I had a look at using the below PowerShell script available online, however it has issues with navigating the path and throws an error before traversing all the certificates. This is apparently a known issue?

invoke-command -ComputerName <servername> -ScriptBlock {
    Get-ChildItem -path 'cert:\' -Recurse  | where { $_.notafter -le (get-date).AddDays(60) -AND $_.notafter -gt (get-date)} | select thumbprint, subject
}

Throws the below error

NotSpecified: (:) [Get-ChildItem], Win32Exception

So I had a look to see if the SSL Server Authentication certificate was recorded in SQL Server and queried master.sys.certificates however it was not here.

How do I go about checking for an expiring SSL certificate on Windows Server 2012 R2 for SQL Server 2012+?


问:
How to copy top and remaining values to different cell in Excel VBA

I would like to select the top 10 Values from Main table and paste in different range (E3) and REMAINING all values and PASTE and SUM in another range(I3)
I used the code below. It is working for Top 10 values, BUT for remaining,
when i am adding one more row in Main table, it is not working. Help me.

```<code>Private Sub CommandButton1_Click()

'Calculation for Top 10 Countries
Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(-9, -2).Resize(10, 3).Copy Sheets("Sheet1").Range("E3")

'Calculation for Remaining Countries
Range("A3:C14").Copy Range("I3")
Range("I15").Select
ActiveCell.FormulaR1C1 = "Remaining"
Range("J15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
Range("K15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
End Sub
</code>```

答:
The code below first sorts the main table by country (hard-coded option), then creates 2 copies of the sorted table in columns E and I sorted descending or ascending (hard-coded option), and deletes the part in each which isn't needed. The user can choose the year by which the ranking is to be determined, and the program allows for more years to be added to the main table and processed without change of code. You may wish to change the name of the worksheet in the code.</p>

```<code>Option Explicit

Private Sub CommandButton1_Click()
    ' 14 Nov 2017

    Dim Ws As Worksheet
    Dim ClmCount As Long
    Dim SortYear As Long                            ' = column in main table
    Dim SortOrder As XlSortOrder
    Dim Rng As Range
    Dim Rl As Long, Rend As Long                    ' last row
    Dim R As Long, C As Long

    Set Ws = Worksheets("Deepak")
    SortYear = YearToSort(Ws)
    If SortYear Then                                ' exit if cancelled
        Application.ScreenUpdating = False
        With Ws
            Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
            If Rl > 3 Then                          ' skip, if no list
                ClmCount = MainTableColumnsCount(Ws)

                ' === Sorting the main table
                '     you can sort on another column, in another order
                '     or skip the sort entirely
                '     to skip remove these two lines of code
                Set Rng = Range(.Cells(3, "A"), .Cells(Rl, ClmCount))
                SortRange Rng, 1, xlAscending       ' sort Main by country (column 1)

                ' === set the sort order for Lists 1 & 2 here:-
                SortOrder = xlAscending             ' Alt: change for xlDescending
                SheetSetup Ws, SortYear, SortOrder  ' create sorted copies

                ' List 1: delete all but the top 10
                C = ClmCount + 2
                R = IIf(SortOrder = xlAscending, 3, 13)
                Rend = IIf(SortOrder = xlAscending, Rl - 10, Rl)
                Set Rng = Range(.Cells(R, C), .Cells(Rend, C + ClmCount - 1))
                Rng.Delete Shift:=xlUp

                ' List 2: delete the top 10
                C = 2 * (ClmCount + 1) + 1
                R = IIf(SortOrder = xlAscending, Rl - 9, 3)
                Rend = IIf(SortOrder = xlAscending, Rl, 12)
                Set Rng = Range(.Cells(R, C), .Cells(Rend, C + ClmCount - 1))
                Rng.Delete Shift:=xlUp

                ' write totals
                Rl = .Cells(.Rows.Count, C).End(xlUp).Row
                With .Cells(Rl + 1, C)
                    .Value = "Remaining"
                    .HorizontalAlignment = xlRight
                    .Font.Bold = True
                End With
                For C = (C + 1) To (C + ClmCount - 1)
                    Set Rng = Range(.Cells(3, C), .Cells(Rl, C))
                    With .Cells(Rl + 1, C)
                        .Value = Application.Sum(Rng)
                        .HorizontalAlignment = xlCenter
                        .Font.Bold = True
                    End With
                Next C
            End If
        End With
        Application.ScreenUpdating = True
    End If
End Sub

Private Sub SortRange(Rng As Range, _
                      SortColumn As Long, _
                      SortOrder As XlSortOrder)
    ' 14 Nov 2017

    With Rng.Worksheet.Sort
        .SortFields.Clear
        .SortFields.Add Key:=Rng.Columns(SortColumn), _
                        SortOn:=xlSortOnValues, _
                        Order:=SortOrder, _
                        DataOption:=xlSortNormal
        .SetRange Rng
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Private Function YearToSort(Ws As Worksheet) As Long
    ' 14 Nov 2017
    ' return the column number of the main table
    ' return 0 if cancelled

    Dim Fun As Long
    Dim Rng As Range
    Dim UserInput As String

    Set Rng = Ws.Range(Cells(2, 2), Cells(2, MainTableColumnsCount(Ws)))
    ' use B2 as default
    Do
        UserInput = InputBox("Enter the year to sort by:", _
                             "Select a year", Rng.Cells(1).Value)
        If UserInput = "" Then Exit Do
        On Error Resume Next
        Fun = Application.Match(CLng(UserInput), Rng, 0)
        If Err Then
            MsgBox "There is no data for year " & UserInput & "." & vbCr & _
                   "Please enter an available year.", _
                   vbInformation, "Invalid input"
            UserInput = ""
            On Error GoTo 0
        End If
    Loop While UserInput = ""
    YearToSort = Fun + 1
End Function

Private Sub SheetSetup(Ws As Worksheet, _
                       SortYear As Long, _
                       SortOrder As XlSortOrder)
    ' 14 Nov 2017

    Const Captions As String = "Top 10 countries,All other countries"
    Dim Rng As Range, SortRng As Range
    Dim ClmCount As Long
    Dim Rl As Long                      ' last row
    Dim C As Long
    Dim i As Long

    With Ws
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row
        ClmCount = MainTableColumnsCount(Ws)
        C = .UsedRange.Columns.Count
        If C > ClmCount Then
            ' delete all existing except main table
            Set Rng = Range(.Cells(1, ClmCount + 1), .Cells(Rl, C))
            Rng.Cells.Delete Shift:=xlUp
        End If
        Set Rng = Range(.Cells(1, 1), .Cells(Rl, ClmCount))

        ' create two copies of the main table
        For i = 1 To 2
            C = (ClmCount + 1) * i + 1
            Rng.Copy Destination:=.Cells(1, C)
            .Cells(1, C + 1).Value = Split(Captions, ",")(i - 1)
            Set SortRng = Range(.Cells(3, C), .Cells(Rl, C + ClmCount - 1))
            SortRange SortRng, SortYear, SortOrder
        Next i
    End With
End Sub

Private Function MainTableColumnsCount(Ws As Worksheet) As Long
    ' 14 Nov 2017

    Dim Fun As Long

    Do
        Fun = Fun + 1
    Loop While Len(Ws.Cells(2, Fun).Value)
    MainTableColumnsCount = Fun - 1
End Function
</code>```

Body:
I would like to select the top 10 Values from Main table and paste in different range (E3) and REMAINING all values and PASTE and SUM in another range(I3)
I used the code below. It is working for Top 10 values, BUT for remaining,
when i am adding one more row in Main table, it is not working. Help me.

Private Sub CommandButton1_Click()

'Calculation for Top 10 Countries
Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(-9, -2).Resize(10, 3).Copy Sheets("Sheet1").Range("E3")

'Calculation for Remaining Countries
Range("A3:C14").Copy Range("I3")
Range("I15").Select
ActiveCell.FormulaR1C1 = "Remaining"
Range("J15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
Range("K15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
End Sub

Body:
The code below first sorts the main table by country (hard-coded option), then creates 2 copies of the sorted table in columns E and I sorted descending or ascending (hard-coded option), and deletes the part in each which isn't needed. The user can choose the year by which the ranking is to be determined, and the program allows for more years to be added to the main table and processed without change of code. You may wish to change the name of the worksheet in the code.

Option Explicit

Private Sub CommandButton1_Click()
    ' 14 Nov 2017

    Dim Ws As Worksheet
    Dim ClmCount As Long
    Dim SortYear As Long                            ' = column in main table
    Dim SortOrder As XlSortOrder
    Dim Rng As Range
    Dim Rl As Long, Rend As Long                    ' last row
    Dim R As Long, C As Long

    Set Ws = Worksheets("Deepak")
    SortYear = YearToSort(Ws)
    If SortYear Then                                ' exit if cancelled
        Application.ScreenUpdating = False
        With Ws
            Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
            If Rl > 3 Then                          ' skip, if no list
                ClmCount = MainTableColumnsCount(Ws)

                ' === Sorting the main table
                '     you can sort on another column, in another order
                '     or skip the sort entirely
                '     to skip remove these two lines of code
                Set Rng = Range(.Cells(3, "A"), .Cells(Rl, ClmCount))
                SortRange Rng, 1, xlAscending       ' sort Main by country (column 1)

                ' === set the sort order for Lists 1 & 2 here:-
                SortOrder = xlAscending             ' Alt: change for xlDescending
                SheetSetup Ws, SortYear, SortOrder  ' create sorted copies

                ' List 1: delete all but the top 10
                C = ClmCount + 2
                R = IIf(SortOrder = xlAscending, 3, 13)
                Rend = IIf(SortOrder = xlAscending, Rl - 10, Rl)
                Set Rng = Range(.Cells(R, C), .Cells(Rend, C + ClmCount - 1))
                Rng.Delete Shift:=xlUp

                ' List 2: delete the top 10
                C = 2 * (ClmCount + 1) + 1
                R = IIf(SortOrder = xlAscending, Rl - 9, 3)
                Rend = IIf(SortOrder = xlAscending, Rl, 12)
                Set Rng = Range(.Cells(R, C), .Cells(Rend, C + ClmCount - 1))
                Rng.Delete Shift:=xlUp

                ' write totals
                Rl = .Cells(.Rows.Count, C).End(xlUp).Row
                With .Cells(Rl + 1, C)
                    .Value = "Remaining"
                    .HorizontalAlignment = xlRight
                    .Font.Bold = True
                End With
                For C = (C + 1) To (C + ClmCount - 1)
                    Set Rng = Range(.Cells(3, C), .Cells(Rl, C))
                    With .Cells(Rl + 1, C)
                        .Value = Application.Sum(Rng)
                        .HorizontalAlignment = xlCenter
                        .Font.Bold = True
                    End With
                Next C
            End If
        End With
        Application.ScreenUpdating = True
    End If
End Sub

Private Sub SortRange(Rng As Range, _
                      SortColumn As Long, _
                      SortOrder As XlSortOrder)
    ' 14 Nov 2017

    With Rng.Worksheet.Sort
        .SortFields.Clear
        .SortFields.Add Key:=Rng.Columns(SortColumn), _
                        SortOn:=xlSortOnValues, _
                        Order:=SortOrder, _
                        DataOption:=xlSortNormal
        .SetRange Rng
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Private Function YearToSort(Ws As Worksheet) As Long
    ' 14 Nov 2017
    ' return the column number of the main table
    ' return 0 if cancelled

    Dim Fun As Long
    Dim Rng As Range
    Dim UserInput As String

    Set Rng = Ws.Range(Cells(2, 2), Cells(2, MainTableColumnsCount(Ws)))
    ' use B2 as default
    Do
        UserInput = InputBox("Enter the year to sort by:", _
                             "Select a year", Rng.Cells(1).Value)
        If UserInput = "" Then Exit Do
        On Error Resume Next
        Fun = Application.Match(CLng(UserInput), Rng, 0)
        If Err Then
            MsgBox "There is no data for year " & UserInput & "." & vbCr & _
                   "Please enter an available year.", _
                   vbInformation, "Invalid input"
            UserInput = ""
            On Error GoTo 0
        End If
    Loop While UserInput = ""
    YearToSort = Fun + 1
End Function

Private Sub SheetSetup(Ws As Worksheet, _
                       SortYear As Long, _
                       SortOrder As XlSortOrder)
    ' 14 Nov 2017

    Const Captions As String = "Top 10 countries,All other countries"
    Dim Rng As Range, SortRng As Range
    Dim ClmCount As Long
    Dim Rl As Long                      ' last row
    Dim C As Long
    Dim i As Long

    With Ws
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row
        ClmCount = MainTableColumnsCount(Ws)
        C = .UsedRange.Columns.Count
        If C > ClmCount Then
            ' delete all existing except main table
            Set Rng = Range(.Cells(1, ClmCount + 1), .Cells(Rl, C))
            Rng.Cells.Delete Shift:=xlUp
        End If
        Set Rng = Range(.Cells(1, 1), .Cells(Rl, ClmCount))

        ' create two copies of the main table
        For i = 1 To 2
            C = (ClmCount + 1) * i + 1
            Rng.Copy Destination:=.Cells(1, C)
            .Cells(1, C + 1).Value = Split(Captions, ",")(i - 1)
            Set SortRng = Range(.Cells(3, C), .Cells(Rl, C + ClmCount - 1))
            SortRange SortRng, SortYear, SortOrder
        Next i
    End With
End Sub

Private Function MainTableColumnsCount(Ws As Worksheet) As Long
    ' 14 Nov 2017

    Dim Fun As Long

    Do
        Fun = Fun + 1
    Loop While Len(Ws.Cells(2, Fun).Value)
    MainTableColumnsCount = Fun - 1
End Function


问:
Using functional for loop with non-Array iterator
Say we have this generator function (generator fn returns an iterator):

```<code>function* foo(){
  yield 1;
  yield 2;
  yield 3;
}

for (let i of foo()) {
  console.log(i);
}
</code>```

we can iterate over the iterator using a for..of loop.

My question is: is there a way to create a functional for-loop to iterate over an iterator like with an Array?

```<code>[1,2,3].forEach(function(i){
   // we have our own block scope for each item in the iterable
});
</code>```

is our best bet this technique?

```<code> for (let i of foo()) {
      (function(i){

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

seem like there must be an easier way

答:
[...foo()].forEach should be the closest.

A bigger question is why javascript doesn't provide array-like functions for generator/Iterables.

Body:
Say we have this generator function (generator fn returns an iterator):

function* foo(){
  yield 1;
  yield 2;
  yield 3;
}

for (let i of foo()) {
  console.log(i);
}

we can iterate over the iterator using a for..of loop.

My question is: is there a way to create a functional for-loop to iterate over an iterator like with an Array?

[1,2,3].forEach(function(i){
   // we have our own block scope for each item in the iterable
});

is our best bet this technique?

 for (let i of foo()) {
      (function(i){

      })(i);
 }

seem like there must be an easier way


问:
Are there md5 collisions for integers in range(1,1000000000)
I want to generate a uuid in python using the md5 hash of a preexisting unique identifier ranged between 1 and 999999999

It seems obvious that on numbers so small there couldn't be any worry... but it made me think, do we know the smallest two integers that have the same md5 hash ?

答:
You could test it:

provided you have ample memory, and/or an OS that manages excess
  memory usage with disk access, but then it will be rather slow -
  thanks to @EricDuminil & @vsenko in the comments

```<code>import hashlib

h = hashlib.new('md5', buffer=64)
md5hashes = set()

N = 1000000000

for _ in range(N):
    if _ % 10000000 == 0:
        print(".", flush = True)
    h.update(str(_).encode())
    hsh = h.hexdigest()
    if hsh in md5hashes:
        print(_, hsh)
    md5hashes.add(hsh)

print(f"has collisions: {len(md5hashes) != N})
</code>```

Body:
You could test it:

provided you have ample memory, and/or an OS that manages excess
  memory usage with disk access, but then it will be rather slow -
  thanks to @EricDuminil & @vsenko in the comments

import hashlib

h = hashlib.new('md5', buffer=64)
md5hashes = set()

N = 1000000000

for _ in range(N):
    if _ % 10000000 == 0:
        print(".", flush = True)
    h.update(str(_).encode())
    hsh = h.hexdigest()
    if hsh in md5hashes:
        print(_, hsh)
    md5hashes.add(hsh)

print(f"has collisions: {len(md5hashes) != N})


问:
Manage zoom level on Xcode9 simulators
Since Xcode 9 came out the simulator scale is disturbed. Here there is not any option of scaling further to 100% on some simulators and sometimes I am unable to switch to 100 % scale at all.

After searching on net I found out that sometimes if zooming doesn't work I need to do following to get it 100% zoom.

Uncheck Window -> Show Device Bezels

Click Window -> Zoom

Check Window -> Show Device Bezels

Is it something that I am missing to scale it further if I want to or current Xcode doesn't support further scaling at all.

答: Just drag the corner of the simulator window.

Title: Manage zoom level on Xcode9 simulators


问:
galen: how to wait dynamic new page with same url
I started working with Galen and I had this test that was working perfectly:

```<code>this.HomePage = $page('Welcome Page', {
    aboutButton: 'nav.navbar .about'
});

this.AboutPage = $page('About page', {
    modalContent: 'div.modal-content',
    supportLink: '.support-link',
    dismissButton: '.dismiss'
});

var homePage = new HomePage(driver);
homePage.waitForIt();
homePage.aboutButton.click();

var aboutPage = new AboutPage(driver);
aboutPage.waitForIt();
</code>```

I understand that the waitForIt method waits for all the attributes defined by page so the framework knows when to execute the next statement.

Now, I want to run this as a grunt task and I've been using grunt-galenframework, and I configured it correctly, everything is working, but I can't make the previous test pass, the task code is as follows:

```<code>load('../gl.js');

forAll(config.getDevices(), function (device) {
    test('simple test on ' + device.deviceName, function () {
        gl.openPage(device, config.getProjectPage(), "Welcome Page", {
            aboutButton: 'nav.navbar .about'
        });

        elements.aboutButton.click();

        // MISSING WAIT FOR ABOUT_PAGE

        gl.runSpecFile(device, './test/responsive/galen/about.gspec');
    });
});
</code>```

As you can see, I get into the Welcome Page and then I need to click a button, wait for a dialog to appear, and then check the about.gspec specs (they verify elements inside the dialog).

So how can I add a wait for new elements to appear on the same URL? it feels like grunt-galenframework only offers wait when entering a new url, with the openPage method.

答:
you could try

```<code>elements.newElement.waitToBeShown()
</code>```

The methods from here should be available.

PS: I'm the author of the grunt plugin for Galen and also involved in the development of the Galen Framework itself

Body:
I started working with Galen and I had this test that was working perfectly:

this.HomePage = $page('Welcome Page', {
    aboutButton: 'nav.navbar .about'
});

this.AboutPage = $page('About page', {
    modalContent: 'div.modal-content',
    supportLink: '.support-link',
    dismissButton: '.dismiss'
});

var homePage = new HomePage(driver);
homePage.waitForIt();
homePage.aboutButton.click();

var aboutPage = new AboutPage(driver);
aboutPage.waitForIt();

I understand that the waitForIt method waits for all the attributes defined by page so the framework knows when to execute the next statement.

Now, I want to run this as a grunt task and I've been using grunt-galenframework, and I configured it correctly, everything is working, but I can't make the previous test pass, the task code is as follows:

load('../gl.js');

forAll(config.getDevices(), function (device) {
    test('simple test on ' + device.deviceName, function () {
        gl.openPage(device, config.getProjectPage(), "Welcome Page", {
            aboutButton: 'nav.navbar .about'
        });

        elements.aboutButton.click();

        // MISSING WAIT FOR ABOUT_PAGE

        gl.runSpecFile(device, './test/responsive/galen/about.gspec');
    });
});

As you can see, I get into the Welcome Page and then I need to click a button, wait for a dialog to appear, and then check the about.gspec specs (they verify elements inside the dialog).

So how can I add a wait for new elements to appear on the same URL? it feels like grunt-galenframework only offers wait when entering a new url, with the openPage method.

Body:
you could try

elements.newElement.waitToBeShown()

The methods from here should be available.

PS: I'm the author of the grunt plugin for Galen and also involved in the development of the Galen Framework itself


问:
Only the last element is shown in Firebase database
I have a sample database in Firebase that is meant to display some facts. Currently, I want the textview to display all the five sample facts 1,2,3,4,5..but it shows only the last one. Where should I modify on my code?

Java sample:

```<code>fact = database.getInstance().getReference().child("Facts");

        fact.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){

                    Fact factdata = postSnapshot.getValue(Fact.class);

                    factViewBox.setText(factdata.getFactDetail());

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

And the json:

```<code>"Facts":{
    "01":{
   "factDetail":"1"
   }
,

"02":{
   "factDetail":"2"
}
,
"03":{
   "factDetail":"3"
}
,
"04":{
   "factDetail":"4"
}
,
"05":{
   "factDetail":"5"
}

}
</code>```

答:
What your code doing is just replacing the current text in the TextView with the factdata.getFactDetail().

For example you have 3 elements 1, 2, and 3. Then you want to display the element inside the TextView. With your code, this is what happen

First iteration:

```<code>element = elements[0];        // element = 1
factViewBox.setText(element); // TextView text is "1"
</code>```

Second iteration:

```<code>element = elements[1];        // element = 2
factViewBox.setText(element); // TextView text is "2"
</code>```

Third iteration:

```<code>element = elements[2];        // element = 3
factViewBox.setText(element); // TextView text is "3"
</code>```

Therefore, your TextView only displaying the last element/fact detail

Body:
I have a sample database in Firebase that is meant to display some facts. Currently, I want the textview to display all the five sample facts 1,2,3,4,5..but it shows only the last one. Where should I modify on my code?

Java sample:

fact = database.getInstance().getReference().child("Facts");

        fact.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){

                    Fact factdata = postSnapshot.getValue(Fact.class);

                    factViewBox.setText(factdata.getFactDetail());

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

And the json:

"Facts":{
    "01":{
   "factDetail":"1"
   }
,

"02":{
   "factDetail":"2"
}
,
"03":{
   "factDetail":"3"
}
,
"04":{
   "factDetail":"4"
}
,
"05":{
   "factDetail":"5"
}

}

Body:
What your code doing is just replacing the current text in the TextView with the factdata.getFactDetail().

For example you have 3 elements 1, 2, and 3. Then you want to display the element inside the TextView. With your code, this is what happen

First iteration:

element = elements[0];        // element = 1
factViewBox.setText(element); // TextView text is "1"

Second iteration:

element = elements[1];        // element = 2
factViewBox.setText(element); // TextView text is "2"

Third iteration:

element = elements[2];        // element = 3
factViewBox.setText(element); // TextView text is "3"

Therefore, your TextView only displaying the last element/fact detail


问:
ARKit - Update only the world coordinates origin
Once the user has scanned the environment and that I detected a plane, I would like the world origin anchor, which is the device position when the app opens (which is the origin of the 3D world), to be reset to where my device is right now so that the user can see my AR objects in front of him.
(my objects are floating and not related to the floor but detecting a plane makes the objects more stable)

I didn't find a way to do that. It's linked to ARConfiguration but it doesn't seem like we can update the coordinate system without resetting all the tracking. Do you have any idea?

答:
According to this post link, the documentation of the rootNode says:

You should not modify the transform property of the root node.

I still tried affecting the camera position to the position of the rootNode but it didn't change anything.
So it seems like the only way is to create a new node and use it as a rootNode from where we are.


问:
how to test method that prints to console in golang?
I have next struct.

```<code>package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}
</code>```

Test coverage says I need to test that ConsolePrinter Print method.

How can I cover this method?

Thanks.

答:
Use Examples to convey the usage of a function.

Don't fret over 100% test coverage, especially for simple straightforward functions.

```<code>func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}
</code>```

The additional benefit is that examples are outputted in a generated doc with go doc tool.

Body:
I have next struct.

package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}

Test coverage says I need to test that ConsolePrinter Print method.

How can I cover this method?

Thanks.

Body:
Use Examples to convey the usage of a function.

Don't fret over 100% test coverage, especially for simple straightforward functions.

func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}

The additional benefit is that examples are outputted in a generated doc with go doc tool.


问:
Better way of using services in Angular
I have an DatesService which responsible for manipulate dates. Also I have two services who need to use date manipulation - EventsService and CalendarService. CalendarService use EventsService.

My question is: what is better (performance and everything else) - include DatesService in both services, or in CalendarService call DatesService through EventsService in this way: this.eventsService.datesService?

答:
We faced a similar "problem" and we decided to create a central provider service that contains many other services that are frequently used.

It does not make a difference performance-wise, but it is more convenient to inject only one service instead of several. It keeps the code clean and refactoring is easier.

Title: Better way of using services in Angular


问:
Cannot update data in MySQL Database using mysqli
Hello can someone assist me im failing to update the data in my mysql database</p>

```<code><?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."<br>".$conn->error;
    }

    $conn->close();

    ?>
</code>```

答:
Your problem could be in this line :

```<code>$mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description =
'$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";
</code>```

Particularly here ')";

You're closing a bracket when you never opened one.

Body:
Hello can someone assist me im failing to update the data in my mysql database

<?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."
".$conn->error;
    }

    $conn->close();

    ?>

Body:
Your problem could be in this line :

$mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description =
'$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

Particularly here ')";

You're closing a bracket when you never opened one.


问:
Manipulating a Firebase element after Snapshot
I have a function that gets called when a button on a search form is clicked. We get the string and check it to make sure it's letters only. We then check to see if the players name is already in the database or not, if it isn't, we add him. If he is in the database, we go to the else portion of the statement. This is working fine -- but in my else area, when we get to the point that we know for sure there is a player with the exact same name in the database, I want to manipulate one of the characteristics in the database for that player. Specifically, add 1 to the players vote count.

```<code>writePlayer(newPlayerContent){
if (/^[a-zA-Z\s]*$/.test(this.state.newPlayerContent)) {
    this.checkIfUserExists(this.state.newPlayerContent);

    if(this.state.duplicate !== true){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
        var playersRef = firebase.database().ref();
        playersRef.child('players').orderByChild("playerContent").equalTo(this.state.newPlayerContent).once("value",snapshot => {
        const userData = snapshot.val();
        console.log(userData)
        })
    }
}
else {
    console.log("Non-letter character found in: " + this.state.newPlayerContent)
    }

}
</code>```

When I do that console.log(userData) I am getting relevant information for the specific player I want to manipulate -- such as

-KytHrvt8R1DkY0E4Fho: {playerContent: "Test", rank: 0, votes: 0}

I want to do a votes++ on the player in userData. I just can't figure out what to add into my else statement to change that fields data.

My Firebase is laid out like so:

```<code>players
    playerContent: "Test"
    rank: 0
    votes: 0
</code>```

答:
Try this

```<code>else{
    var playersRef = firebase.database().ref();
    playersRef.child('players').orderByChild("playerContent").equalTo(this.state.newPlayerContent).once("value",snapshot => {
    snapshot.forEach(child => {
        const data = child.val();
        const key = child.key
        //set the  vote count
        playersRef.child('players/'+key).update({
            votes: data.votes + 1;
         });
      });
    })
}
</code>```

you need to loop through the data to get the actual result, then use the key to point the desired player and set its value. hope this helps.

Body:
I have a function that gets called when a button on a search form is clicked. We get the string and check it to make sure it's letters only. We then check to see if the players name is already in the database or not, if it isn't, we add him. If he is in the database, we go to the else portion of the statement. This is working fine -- but in my else area, when we get to the point that we know for sure there is a player with the exact same name in the database, I want to manipulate one of the characteristics in the database for that player. Specifically, add 1 to the players vote count.

writePlayer(newPlayerContent){
if (/^[a-zA-Z\s]*$/.test(this.state.newPlayerContent)) {
    this.checkIfUserExists(this.state.newPlayerContent);

    if(this.state.duplicate !== true){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
        var playersRef = firebase.database().ref();
        playersRef.child('players').orderByChild("playerContent").equalTo(this.state.newPlayerContent).once("value",snapshot => {
        const userData = snapshot.val();
        console.log(userData)
        })
    }
}
else {
    console.log("Non-letter character found in: " + this.state.newPlayerContent)
    }

}

When I do that console.log(userData) I am getting relevant information for the specific player I want to manipulate -- such as

-KytHrvt8R1DkY0E4Fho: {playerContent: "Test", rank: 0, votes: 0}

I want to do a votes++ on the player in userData. I just can't figure out what to add into my else statement to change that fields data.

My Firebase is laid out like so:

players
    playerContent: "Test"
    rank: 0
    votes: 0

Body:
Try this

else{
    var playersRef = firebase.database().ref();
    playersRef.child('players').orderByChild("playerContent").equalTo(this.state.newPlayerContent).once("value",snapshot => {
    snapshot.forEach(child => {
        const data = child.val();
        const key = child.key
        //set the  vote count
        playersRef.child('players/'+key).update({
            votes: data.votes + 1;
         });
      });
    })
}

you need to loop through the data to get the actual result, then use the key to point the desired player and set its value. hope this helps.


问:
how to create custom list with sonata admin
I can't find (understand) how to add items and cathegories to Left Side Admin Menu.
There is no detailed tutorial how to do this.
I can add items to sonata.admin.block.admin_list but to aside Admin Menu
enter image description here</p>

答:
Since the menu is automatically built by traversing the registered admins there is no (to me known) simple solution for that by adding just an admin service entry. But it's quite easy yet. You could register a MenuBuilderListener and add new items as many as you want ...

In your services.yml

```<code>app.menu_listener:
    class: AppBundle\Listener\MenuBuilderListener
    tags:
        - { name: kernel.event_listener, event: sonata.admin.event.configure.menu.sidebar, method: addMenuItems }
</code>```

In you MenuBuilderListener class

```<code>public function addMenuItems(ConfigureMenuEvent $event)
{
    $event->getMenu()->addChild($event->getFactory()->createItem('Test entry', ['route' => 'custom_route']));
    ...
}
</code>```

The event is called after your menu is build ... you can change existing menu entries afterwards or just add new entries. Note that the admin service usually will take responsibility for creating routes, if you don't have an admin you have to build routes by yourself.

Body:
Since the menu is automatically built by traversing the registered admins there is no (to me known) simple solution for that by adding just an admin service entry. But it's quite easy yet. You could register a MenuBuilderListener and add new items as many as you want ...

In your services.yml

app.menu_listener:
    class: AppBundle\Listener\MenuBuilderListener
    tags:
        - { name: kernel.event_listener, event: sonata.admin.event.configure.menu.sidebar, method: addMenuItems }

In you MenuBuilderListener class

public function addMenuItems(ConfigureMenuEvent $event)
{
    $event->getMenu()->addChild($event->getFactory()->createItem('Test entry', ['route' => 'custom_route']));
    ...
}

The event is called after your menu is build ... you can change existing menu entries afterwards or just add new entries. Note that the admin service usually will take responsibility for creating routes, if you don't have an admin you have to build routes by yourself.


问:
Difference between with and run in Kotlin
Do with and run have the same functionality with only different syntax, or is there any major differences between with and run?

Which is the proper way?

```<code>adapter.run {
    notifyDataSetChanged()
    if (activityDetails.isEmpty())
        emptyText.visibility = View.VISIBLE
    else
       emptyText.visibility = View.GONE
}

with(adapter){
   notifyDataSetChanged()
   if (activityDetails.isEmpty())
       emptyText.visibility = View.VISIBLE
   else
       emptyText.visibility = View.GONE
}
</code>```

答:
In normal case, they are pretty similar, but for a nullable variable, it's better to use T.run()

E.g. if webview.settings is nullable, below would show the distinct

```<code>with(webview.settings) {
    this?.javaScriptEnabled = true
    this?.databaseEnabled = true
}

// similarly
webview.settings?.run {
    javaScriptEnabled = true
    databaseEnabled = true
}
</code>```

Body:
Do with and run have the same functionality with only different syntax, or is there any major differences between with and run?

Which is the proper way?

adapter.run {
    notifyDataSetChanged()
    if (activityDetails.isEmpty())
        emptyText.visibility = View.VISIBLE
    else
       emptyText.visibility = View.GONE
}

with(adapter){
   notifyDataSetChanged()
   if (activityDetails.isEmpty())
       emptyText.visibility = View.VISIBLE
   else
       emptyText.visibility = View.GONE
}

Body:
In normal case, they are pretty similar, but for a nullable variable, it's better to use T.run()

E.g. if webview.settings is nullable, below would show the distinct

with(webview.settings) {
    this?.javaScriptEnabled = true
    this?.databaseEnabled = true
}

// similarly
webview.settings?.run {
    javaScriptEnabled = true
    databaseEnabled = true
}


问:
I can't load any active x component on IE11?
Ever since I formatted my computer, I am not able to load any active x component for any site. I get the following error:

ActiveX is not supported

For example, I opened the following page in IE11:
https://www.pcpitstop.com/testax.asp

It should display the date, but it doesn't, it just gives the active x not supported error. I changed in IE security settings but that didn't fix it.

答:
IE displays a active x warning and ask for permission if you allow it to run or not. To overcome this the only solution is to;
Open Internet Explorer.
Click the Tools menu, and then click Internet Options.
On the Security tab, click the Custom level button.
Scroll down the Security Settings list until you see ActiveX controls and plug-ins.
For Automatic prompting for ActiveX controls, click Enable.
Scroll down to Download signed ActiveX controls and click Enable or Prompt.
Scroll down to Run ActiveX controls and plug-ins and click Enable or Prompt.
Scroll down to Script ActiveX controls marked safe for scripting and click Enable or Prompt.
Click OK, and then click OK again.</p>