问:
Show loading indicator at root level until all route resolves are complete
I've been doing some Googling around this already but I'm unable to find a solution that works.

I'm using AngularJS 1.5.5 and .NET Web API 2 to build a web application and I would quite simply like to hide the ng-view element until all resolves have completed on the route.

I'm trying to use the $routeChangeStart and $routeChangeSuccess to set a variable on the $rootScope that is used in the index html to display the loading indicator and hide the content until the variable is false.

Here is my routing code for the routeChange properties:

```<code>_app.config([
        '$routeProvider', '$httpProvider', '$provide',
        function ($routeProvider, $httpProvider, $provide) {
                    $routeProvider.when('/Account',
                    {
                        templateUrl: '/Content/js/areas/account/account.html',
                        controller: 'accountController',
                        resolve: {
                            $accountResolver: function (accountService) {
                                return accountService.getMyAccountData();
                            }
                        },
                        caseInsensitiveMatch: true
                    });
            $routeProvider.otherwise({ redirectTo: '404' });

        }
]);

_app.run(['$rootScope', '$location', '$window', '$q', 'authService',
        function ($rootScope, $location, $window, $q, authService) {
            $rootScope.$on("$routeChangeStart",
                function (e, curr, prev) {
                    $rootScope.$loadingRoute = true;
                });
            $rootScope.$on("$routeChangeSuccess",
                function (evt, next) {
                    $rootScope.$loadingRoute = false;
                });
            $rootScope.$on("$routeChangeError",
                function (evt, next) {
                    $rootScope.$loadingRoute = false;
                });
        }]);
</code>```

And here is my html using that $loadingRoute variable:

```<code><body class="ng-cloak" data-ng-app="wishlist" data-ng-controller="appController">
    <wl-header></wl-header>
    <preloader ng-if="$loadingRoute"></preloader>
    <section ng-view ng-if="!$loadingRoute" class="container ng-cloak"></section>
</body>
</code>```

I understand that there's quite a lot of articles covering this but none seem to work in my case. $loadingRoute gets set to true when the route change starts, as expected, which I will see if I add {{$loadingRoute}} to the HTML before the

 tag. However before the $accountResolveris resolved, the $routeChangeSuccess gets fired, setting $rootScope.$loadingRoute = false which is unexpected.

I was under the impression that $routeChangeSuccess only got fired after all resolves had completed on the current route.

Am I doing something really obviously wrong here? Or has Angular simply changed?

Edit: I would also like to add that this approach worked in previous projects, so I'm at a real loss as to what's going wrong. I could set $rootScope.$loadingRoute manually in each page controller but that feels too dirty and unmaintainable.

Edit 2:

```<code>_app.factory('accountService', [
        'accountResource',
        function (accountResource) {
            var _self = this;

            return {
                register: function (authData) {
                    return accountResource.register(authData);
                },

                getMyAccountData: function () {
                    return accountResource.getMyAccountData();
                }
            }
        }
]);

_app.factory('accountResource', [
        '$resource', 'rootUrl',
        function ($resource, rootUrl) {
            var api = rootUrl() + 'api/Account';
            return $resource(api,
            {},
            {
                register: {
                    method: 'POST',
                    url: '{0}/register'.format(api)
                },
                getMyAccountData: {
                    method: 'GET',
                    url: '{0}/GetMyAccountData'.format(api)
                }
            });
        }
    ])
</code>```

答:
In order for a resolver to delay route change, it should return a promise. Otherwise route change happens immediately, this is what happens when $routeChangeSuccess is triggered before a promise from accountService.getMyAccountData() is resolved.

The problem is $resource methods (and so accountService.getMyAccountData()) return self-filling object that is populated with data asynchronously. A promise for this data is available as $promise property (see the reference), so it should be used for a resolver:

```<code>$accountResolver: function (accountService) {
  return accountService.getMyAccountData().$promise;
}
</code>```

If accountService is supposed to be purely promise-based wrapper for accountResource, a cleaner way to do this is to return a promise from its methods instead:

```<code>getMyAccountData: function () {
    return accountResource.getMyAccountData().$promise;
}
</code>```

Body:
I've been doing some Googling around this already but I'm unable to find a solution that works.

I'm using AngularJS 1.5.5 and .NET Web API 2 to build a web application and I would quite simply like to hide the ng-view element until all resolves have completed on the route.

I'm trying to use the $routeChangeStart and $routeChangeSuccess to set a variable on the $rootScope that is used in the index html to display the loading indicator and hide the content until the variable is false.

Here is my routing code for the routeChange properties:

_app.config([
        '$routeProvider', '$httpProvider', '$provide',
        function ($routeProvider, $httpProvider, $provide) {
                    $routeProvider.when('/Account',
                    {
                        templateUrl: '/Content/js/areas/account/account.html',
                        controller: 'accountController',
                        resolve: {
                            $accountResolver: function (accountService) {
                                return accountService.getMyAccountData();
                            }
                        },
                        caseInsensitiveMatch: true
                    });
            $routeProvider.otherwise({ redirectTo: '404' });

        }
]);

_app.run(['$rootScope', '$location', '$window', '$q', 'authService',
        function ($rootScope, $location, $window, $q, authService) {
            $rootScope.$on("$routeChangeStart",
                function (e, curr, prev) {
                    $rootScope.$loadingRoute = true;
                });
            $rootScope.$on("$routeChangeSuccess",
                function (evt, next) {
                    $rootScope.$loadingRoute = false;
                });
            $rootScope.$on("$routeChangeError",
                function (evt, next) {
                    $rootScope.$loadingRoute = false;
                });
        }]);

And here is my html using that $loadingRoute variable:

    <wl-header></wl-header>
    <preloader ng-if="$loadingRoute"></preloader>

I understand that there's quite a lot of articles covering this but none seem to work in my case. $loadingRoute gets set to true when the route change starts, as expected, which I will see if I add {{$loadingRoute}} to the HTML before the

 tag. However before the $accountResolveris resolved, the $routeChangeSuccess gets fired, setting $rootScope.$loadingRoute = false which is unexpected.

I was under the impression that $routeChangeSuccess only got fired after all resolves had completed on the current route.

Am I doing something really obviously wrong here? Or has Angular simply changed?

Edit: I would also like to add that this approach worked in previous projects, so I'm at a real loss as to what's going wrong. I could set $rootScope.$loadingRoute manually in each page controller but that feels too dirty and unmaintainable.

Edit 2:

_app.factory('accountService', [
        'accountResource',
        function (accountResource) {
            var _self = this;

            return {
                register: function (authData) {
                    return accountResource.register(authData);
                },

                getMyAccountData: function () {
                    return accountResource.getMyAccountData();
                }
            }
        }
]);

_app.factory('accountResource', [
        '$resource', 'rootUrl',
        function ($resource, rootUrl) {
            var api = rootUrl() + 'api/Account';
            return $resource(api,
            {},
            {
                register: {
                    method: 'POST',
                    url: '{0}/register'.format(api)
                },
                getMyAccountData: {
                    method: 'GET',
                    url: '{0}/GetMyAccountData'.format(api)
                }
            });
        }
    ])

Body:
In order for a resolver to delay route change, it should return a promise. Otherwise route change happens immediately, this is what happens when $routeChangeSuccess is triggered before a promise from accountService.getMyAccountData() is resolved.

The problem is $resource methods (and so accountService.getMyAccountData()) return self-filling object that is populated with data asynchronously. A promise for this data is available as $promise property (see the reference), so it should be used for a resolver:

$accountResolver: function (accountService) {
  return accountService.getMyAccountData().$promise;
}

If accountService is supposed to be purely promise-based wrapper for accountResource, a cleaner way to do this is to return a promise from its methods instead:

getMyAccountData: function () {
    return accountResource.getMyAccountData().$promise;
}


来源: stackexchange

问:
Programmatically detecting PEAR in PHP
One of my scripts needs PEAR for some additional functionality. I need a way I can detect if PEAR is installed within PHP itself. Since PEAR.php would be in the include path if properly installed, I suppose I could check for the existence of PEAR.php with file_exists() and then check for the PEAR class inside of it to try and determine if it's actually the file I want. Sounds awfully hackish and unreliable though.

Can anybody suggest a better or improved approach?

答:
You can check if PEAR is installed by requiring the System.php file to see if the class exists. This method can be done as instructed here: http://pear.php.net/manual/en/installation.checking.php

System.php is shipped with every PEAR installation, so it would be an easy way to detect it.

```<code><?php
require_once 'System.php';
if(class_exists('System')===true) {
   echo 'PEAR is installed!';
} else {
   echo 'PEAR is not installed :(';
}
?>
</code>```

Hope this helps you!

ContentLicense: CC BY-SA 2.5

Title: Programmatically detecting PEAR in PHP

Body:
You can check if PEAR is installed by requiring the System.php file to see if the class exists. This method can be done as instructed here: http://pear.php.net/manual/en/installation.checking.php

System.php is shipped with every PEAR installation, so it would be an easy way to detect it.

<?php
require_once 'System.php';
if(class_exists('System')===true) {
   echo 'PEAR is installed!';
} else {
   echo 'PEAR is not installed :(';
}
?>

Hope this helps you!


问:
How to invoke async methods in Hangfire?
I have asp.net core API application and this is the first time i will be using HangFire.

In .Net Core application all my methods are async. Based on SO Post it's not good idea to use wait() while calling async method in hangfire.

Also as per the hangfire support issue in v1.6.0, async support was added. I am using version 1.6.12 but still i dont see async support.

How do i call async method from Enqueue. Currently i am using wait()

```<code>public class MyController : Controller
{
    private readonly Downloader _downlaoder;
    private readonly IBackgroundJobClient _backgroungJobClient;
    public MyController(Downloader downloader, IBackgroundJobClient backgroungJobClient)
    {
        _downlaoder = downloader;
        _backgroungJobClient = backgroungJobClient;
    }

    [HttpPost]
    public void Post([FromBody]IEnumerable<string> files)
    {
        _backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files).Wait());
    }
}
</code>```

答:
Based on one of the examples on the repository on github

Just remove the Wait blocking call

```<code>_backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files));
</code>```

The method knows now how to handle Func that returns Task

Hangfire 1.6.0 - Blog

The enqueueing logic is the same for sync and async methods. In early
  betas there was a warning CS4014, but now you can remove all the
  #pragma warning disable statements. It was implemented by using Expression<Func<Task>> parameter overloads.

```<code>BackgroundJob.Enqueue(() => HighlightAsync(snippet.Id));
</code>```

Note:

That’s not a real asynchrony

Please consider this feature as a syntactic sugar. Background
  processing hasn’t became asynchronous. Internally it was implemented
  using the Task.Wait method, so workers don’t perform any processing,
  while waiting for a task completion. Real asynchrony may come in
  Hangfire 2.0 only, and it requires a lot of breaking changes to the
  existing types.

ContentLicense: CC BY-SA 3.0

Body:
I have asp.net core API application and this is the first time i will be using HangFire.

In .Net Core application all my methods are async. Based on SO Post it's not good idea to use wait() while calling async method in hangfire.

Also as per the hangfire support issue in v1.6.0, async support was added. I am using version 1.6.12 but still i dont see async support.

How do i call async method from Enqueue. Currently i am using wait()

public class MyController : Controller
{
    private readonly Downloader _downlaoder;
    private readonly IBackgroundJobClient _backgroungJobClient;
    public MyController(Downloader downloader, IBackgroundJobClient backgroungJobClient)
    {
        _downlaoder = downloader;
        _backgroungJobClient = backgroungJobClient;
    }

    [HttpPost]
    public void Post([FromBody]IEnumerable<string> files)
    {
        _backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files).Wait());
    }
}

Body:
Based on one of the examples on the repository on github

Just remove the Wait blocking call

_backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files));

The method knows now how to handle Func that returns Task

Hangfire 1.6.0 - Blog

The enqueueing logic is the same for sync and async methods. In early
  betas there was a warning CS4014, but now you can remove all the
  #pragma warning disable statements. It was implemented by using Expression<Func<Task>> parameter overloads.

BackgroundJob.Enqueue(() => HighlightAsync(snippet.Id));

Note:

That’s not a real asynchrony

Please consider this feature as a syntactic sugar. Background
  processing hasn’t became asynchronous. Internally it was implemented
  using the Task.Wait method, so workers don’t perform any processing,
  while waiting for a task completion. Real asynchrony may come in
  Hangfire 2.0 only, and it requires a lot of breaking changes to the
  existing types.

ContentLicense: CC BY-SA 4.0


问:
Webpack wont transpile a correct React/JSX file
I have this React file that I got from an example that works on codepen. When I use webpack on it, I get the following error: Transpile error
Why am I running into this issue. </p>

答:
Arrow function is a ES6+/ES7 feature. You must to install and configure  Babel Stage 1 preset

https://babeljs.io/docs/plugins/preset-stage-1/

You can read details about this here: https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb  (Event handlers with arrow functions)


问:
hexadecimal to binary and decimal in matlab
I am trying to read a txt file which has hexadecimal data. I Want to convert them in decimal except one column which I want to convert into binary bits and write them in 8  separate columns.
Sample data set

1/4/2010 15:31 <00000> 0x0001  0x0010  0x0014  0x0000  0x0142  0x0001  0x0001  0x0000  0x028F  0x2007  0x0105  0x00AA  0x005A  0xFA8C  0xFACD  0xFAED  0x003B  0xFFA3  0xFFDE  0x0080  0xFEE0  0xFF2E  0x0000  0x0108
  1/4/2010 15:31 <00000> 0x0001  0x0010  0x0014  0x0000  0x0143  0x0001  0x0001  0x0000  0x028F  0x2008  0x0105  0x00AA  0x005B  0xFA8C  0xFACC  0xFAEE  0x003C  0xFFA3  0xFFDE  0x0080  0xFEE0  0xFF2E  0x0000  0x0108
  1/4/2010 15:31 <00000> 0x0001  0x0010  0x0014  0x0000  0x0144  0x0001  0x0001  0x0000  0x028F  0x2009  0x0105  0x00A9  0x005C  0xFA8C  0xFACC  0xFAF0  0x003B  0xFFA3

clear all;
%

[b,pathb]=uigetfile({'*.txt'},'Select the file','C:\Data\2010');

file2=[pathb b];

data=dlmread('file2', '\t', 2, 1);

newdata=hex2dec(data);

Now I  do not know how to get rid of  0x in all the values and I need to convert the last column into binary and write in  8 columns.

Any help  is highly appreciated.
thanks

答:
Here's a slightly different tack you could try, using TEXTSCAN to read all the data first as strings:

```<code>fid = fopen(file2,'rt');                   %# Open the file
str = ['%s %s %s ' repmat('0x%s ',1,24)];  %# Format string for columns
C = textscan(fid,str,'CollectOutput',1);   %# Read all fields as strings
                                           %#   (removing 0x's)
fclose(fid);                               %# Close the file
C = C{1};                                  %# Remove outer cell encapsulation

dates = strcat(C(:,1),{' '},C(:,2));         %# Collect the date strings
decValues = cellfun(@hex2dec,C(:,4:end-1));  %# Convert the first 23 columns to
                                             %#   decimal values
decValues = decValues-65536.*(decValues > 32767);  %# Change from unsigned to
                                                   %#   signed 16 bit values
binValues = cellfun(@(n) dec2bin(hex2dec(n),8),...    %# Convert the last column
                    C(:,end),'UniformOutput',false);  %#   to binary strings
</code>```

If you have N rows in your file, you should end up with:

An N-by-1 cell array dates of date strings (which can be converted to either serial date numbers or date vectors).

An N-by-23 array decValues containing the converted decimal values. The values were converted from the range 0 to 65535 (i.e. unsigned 16-bit integer) to -32768 to 32767 (i.e. signed 16-bit integer) using two's complement.

An N-by-1 cell array binValues containing the converted binary values. Each cell contains a 1-by-8 character string of zeroes and ones.

Body:
Here's a slightly different tack you could try, using TEXTSCAN to read all the data first as strings:

fid = fopen(file2,'rt');                   %# Open the file
str = ['%s %s %s ' repmat('0x%s ',1,24)];  %# Format string for columns
C = textscan(fid,str,'CollectOutput',1);   %# Read all fields as strings
                                           %#   (removing 0x's)
fclose(fid);                               %# Close the file
C = C{1};                                  %# Remove outer cell encapsulation

dates = strcat(C(:,1),{' '},C(:,2));         %# Collect the date strings
decValues = cellfun(@hex2dec,C(:,4:end-1));  %# Convert the first 23 columns to
                                             %#   decimal values
decValues = decValues-65536.*(decValues > 32767);  %# Change from unsigned to
                                                   %#   signed 16 bit values
binValues = cellfun(@(n) dec2bin(hex2dec(n),8),...    %# Convert the last column
                    C(:,end),'UniformOutput',false);  %#   to binary strings

If you have N rows in your file, you should end up with:

An N-by-1 cell array dates of date strings (which can be converted to either serial date numbers or date vectors).

An N-by-23 array decValues containing the converted decimal values. The values were converted from the range 0 to 65535 (i.e. unsigned 16-bit integer) to -32768 to 32767 (i.e. signed 16-bit integer) using two's complement.

An N-by-1 cell array binValues containing the converted binary values. Each cell contains a 1-by-8 character string of zeroes and ones.


问:
How to subset a pandas dataframe on value_counts?
I have the following pandas dataframe

```<code>import pandas as pd
df = pd.read_csv("filename1.csv")

df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1
3      5071       B          0
4      5891       B          0
5      3210       B          0
6        12       B          2
7        13       C          2
8        20       C          0
9         5       C          3
10        9       C          3
</code>```

Now, using the function value_counts() will give me the counts of each value in a certain column, e.g.

```<code>df.column3.value_counts()

1   3
2   2
3   2
</code>```

However, I would like to subset a pandas dataframe based on the number of values in a given column. For example, in the above dataframe df, I would like to subset on rows with 3 or more unique values (excluding 0). In this case, the resulting dataframe would be

```<code>df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1
</code>```

As the rows for values 2 and 3 only had two rows, i.e. 2, 3 only occurred twice in column3. What is the pandas way to do this?

答:
Or you could filter out the zeroes before you group:</p>

```<code> df1[df1['column3'] != 0].groupby("column3").filter(lambda x: x['column3'].size >= 3 )
</code>```

Body:
I have the following pandas dataframe

import pandas as pd
df = pd.read_csv("filename1.csv")

df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1
3      5071       B          0
4      5891       B          0
5      3210       B          0
6        12       B          2
7        13       C          2
8        20       C          0
9         5       C          3
10        9       C          3

Now, using the function value_counts() will give me the counts of each value in a certain column, e.g.

df.column3.value_counts()

1   3
2   2
3   2

However, I would like to subset a pandas dataframe based on the number of values in a given column. For example, in the above dataframe df, I would like to subset on rows with 3 or more unique values (excluding 0). In this case, the resulting dataframe would be

df
    column1  column2   column3
0        10       A          1
1        15       A          1
2        19       B          1

As the rows for values 2 and 3 only had two rows, i.e. 2, 3 only occurred twice in column3. What is the pandas way to do this?

Body:
Or you could filter out the zeroes before you group:

 df1[df1['column3'] != 0].groupby("column3").filter(lambda x: x['column3'].size >= 3 )


问:
How to add comma separator to Venn diagram
In r is there a way to add the comma separator to thousands on a Venn diagram.

```<code>venn.plot <- VennDiagram::draw.pairwise.venn(10000, 7000, 3000, c("First", "Second"), scaled = FALSE)

grid::grid.draw(venn.plot)
</code>```

The resulting chart looks like the one below.

答:
It does not look like this function was designed to do that. If you really want to use this function, you could "hack" it to replace the default formatting code it uses for labels. Note that this method is very fragile since we are editing particular "lines" of code. First make a copy of the function

```<code>myvenn <- VennDiagram::draw.pairwise.venn
</code>```

Here's the default formatter

```<code>body(myvenn)[[46]]
# wrapLab <- function(num) {
#     stri = ""
#     if (print.mode[1] == "percent") {
#         stri <- paste(signif(num * 100/denom, digits = sigdigs),
#             "%", sep = "")
#         if (isTRUE(print.mode[2] == "raw")) {
#             stri <- paste(stri, "\n(", num, ")", sep = "")
#         }
#     }
#     if (print.mode[1] == "raw") {
#         stri <- num
#         if (isTRUE(print.mode[2] == "percent")) {
#             stri <- paste(stri, "\n(", paste(signif(num * 100/denom,
#                 digits = sigdigs), "%)", sep = ""), sep = "")
#         }
#     }
#     return(stri)
# }
</code>```

Let's replace that with a call to prettyNum to add the commas

```<code>body(myvenn)[[46]][[3]] <- quote(function(x) {
    prettyNum(x ,big.mark=",",scientific=FALSE)
})
</code>```

Now we can call our version of the function

```<code>venn.plot <- myvenn(10000, 7000, 3000, c("First", "Second"), scaled = FALSE)
grid::grid.draw(venn.plot)
</code>```

Body:
In r is there a way to add the comma separator to thousands on a Venn diagram.

venn.plot <- VennDiagram::draw.pairwise.venn(10000, 7000, 3000, c("First", "Second"), scaled = FALSE)

grid::grid.draw(venn.plot)

The resulting chart looks like the one below.

Body:
It does not look like this function was designed to do that. If you really want to use this function, you could "hack" it to replace the default formatting code it uses for labels. Note that this method is very fragile since we are editing particular "lines" of code. First make a copy of the function

myvenn <- VennDiagram::draw.pairwise.venn

Here's the default formatter

body(myvenn)[[46]]
# wrapLab <- function(num) {
#     stri = ""
#     if (print.mode[1] == "percent") {
#         stri <- paste(signif(num * 100/denom, digits = sigdigs),
#             "%", sep = "")
#         if (isTRUE(print.mode[2] == "raw")) {
#             stri <- paste(stri, "\n(", num, ")", sep = "")
#         }
#     }
#     if (print.mode[1] == "raw") {
#         stri <- num
#         if (isTRUE(print.mode[2] == "percent")) {
#             stri <- paste(stri, "\n(", paste(signif(num * 100/denom,
#                 digits = sigdigs), "%)", sep = ""), sep = "")
#         }
#     }
#     return(stri)
# }

Let's replace that with a call to prettyNum to add the commas

body(myvenn)[[46]][[3]] <- quote(function(x) {
    prettyNum(x ,big.mark=",",scientific=FALSE)
})

Now we can call our version of the function

venn.plot <- myvenn(10000, 7000, 3000, c("First", "Second"), scaled = FALSE)
grid::grid.draw(venn.plot)


问:
Webkit browsers will not allow me to set CORS preflight headers
I am trying to create a cross origin GET request using jQuery.ajax(). My server is configured to accept such requests. Chrome will not allow me to send the headers:

Access-Control-Request-Method

Access-Control-Request-Headers

Refused to set unsafe header "Access-Control-Request-Method" <- error
  message

Here is my ajax request:

```<code>$.ajax({
    type:"GET",
    headers: {
        'Access-Control-Request-Method' : 'GET',
        'Access-Control-Request-Headers': 'X-Custom'
    },
    url: "http://localhost:3000",
    success: function(msg) {
        console.log(msg);
    }
});
</code>```

I was expecting these headers to cause the browser to create a pre-flight request (OPTIONS) to negotiate with the server. I know that I have accomplished this before. Can someone tell me what I am forgetting?

Thanks a lot!

答:
A PREFLIGHT options request automatically takes place on a cross domain request IF the request is not a simple request. A simple request is typically a GET request. Thus if you make a cross domain GET request there will NOT be a preflight OPTIONS request.

However, if you make a cross domain POST request, the browser will, without you instructing it to do so, make a preflight OPTIONS request first. The purpose of this request is to see whether the server permits cross-domain POST requests from your client's domain / IP.

If your server has the correct "Access-Control" headers in the response, that say, yes this client is permitted to make a cross domain POST request, then the browser will proceed to make the POST request. If your server says NO (because the "Access-Control" headers on your server are wrong) then the browser will respect that and will NOT make the second POST request.

See https://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request for more info.

Also, you must make sure your server is set to handle incoming OPTIONS requests.

Body:
I am trying to create a cross origin GET request using jQuery.ajax(). My server is configured to accept such requests. Chrome will not allow me to send the headers:

Access-Control-Request-Method

Access-Control-Request-Headers

Refused to set unsafe header "Access-Control-Request-Method" <- error
  message

Here is my ajax request:

$.ajax({
    type:"GET",
    headers: {
        'Access-Control-Request-Method' : 'GET',
        'Access-Control-Request-Headers': 'X-Custom'
    },
    url: "http://localhost:3000",
    success: function(msg) {
        console.log(msg);
    }
});

I was expecting these headers to cause the browser to create a pre-flight request (OPTIONS) to negotiate with the server. I know that I have accomplished this before. Can someone tell me what I am forgetting?

Thanks a lot!


问:
Combobox interaction issue
I have a wpf user control library with three combo boxes (cmbBox1,cmbBox2 and cmbBox3). Initially the comboboxes 2 & 3 are disabled. User first selects and item from cmbBox1. Based on the user selection the items in cmbBox2 and cmbBox3 are populated. My code works fine for the first time. However it breaks when the user changes the selection in box1. Here is my code:

```<code>private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.cmbBox2.Items.Clear();
    this.cmbBox3.Items.Clear();

    //this.cmbBox2.ItemsSource = new object[] {};
    //this.cmbBox3.ItemsSource = new object[] {};

    string Box1String = cmbBox1.SelectedItem.ToString();

    if (this.cmbBox1.SelectedIndex == 0)
    {
        this.cmbBox2.ItemsSource = new object[] { "Item2_0"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_0"};
    }
    else if (this.cmbBox1.SelectedIndex == 1)
    {
        this.cmbBox2ItemsSource = new object[] { "Item2_1"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_1"};
    }

}

private void cmbBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box2String = cmbBox2.SelectedItem.ToString();

    //Rest of the code//

}
</code>```

When the form opens up the code works perfectly. Now afer the selections are made, if the user goes back and changes the selection in combobox1, then code crashes with error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

at the first line of the Combobox2 SelectionIndexChanged event. I thought it is due to the fact that I am clearing the items in Combobox2 and combobox3 when any change happens in combobox1. So I tried commenting thoses lines out, but was not successful either. I currently have no clue why this is occurring and any help is greatly appreciated.

答:
I found a solution that fixed the issue. What I did was to delink the selectionchanged event for comboboxes 2 & 3 within the selection changed event of combobox1. Later after I bind the items for comboboxes 2 & 3 I again assign the function to the selection changed event. Here is the code that worked.</p>

```<code>private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //this.cmbBox2.Items.Clear();
    //this.cmbBox3.Items.Clear();

    //this.cmbBox2.ItemsSource = new object[] {};
    //this.cmbBox3.ItemsSource = new object[] {};

    string Box1String = cmbBox1.SelectedItem.ToString();
    this.cmbBox2.SelectionChanged -= new SelectionChangedEventHandler(cmbBox2_SelectedIndexChanged);
    this.cmbBox3.SelectionChanged -= new SelectionChangedEventHandler(cmbBox3_SelectedIndexChanged);

    if (this.cmbBox1.SelectedIndex == 0)
    {
        this.cmbBox2.ItemsSource = new object[] { "Item2_0"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_0"};
    }
    else if (this.cmbBox1.SelectedIndex == 1)
    {
        this.cmbBox2ItemsSource = new object[] { "Item2_1"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_1"};
    }
    this.cmbBox2.SelectionChanged += new SelectionChangedEventHandler(cmbBox2_SelectedIndexChanged);
    this.cmbBox3.SelectionChanged += new SelectionChangedEventHandler(cmbBox3_SelectedIndexChanged);
}

private void cmbBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box2String = cmbBox2.SelectedItem.ToString();

    //Rest of the code//

}

private void cmbBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box3String = cmbBox3.SelectedItem.ToString();

    //Rest of the code//

}
</code>```

Title: Combobox interaction issue

Body:
I have a wpf user control library with three combo boxes (cmbBox1,cmbBox2 and cmbBox3). Initially the comboboxes 2 & 3 are disabled. User first selects and item from cmbBox1. Based on the user selection the items in cmbBox2 and cmbBox3 are populated. My code works fine for the first time. However it breaks when the user changes the selection in box1. Here is my code:

private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.cmbBox2.Items.Clear();
    this.cmbBox3.Items.Clear();

    //this.cmbBox2.ItemsSource = new object[] {};
    //this.cmbBox3.ItemsSource = new object[] {};

    string Box1String = cmbBox1.SelectedItem.ToString();

    if (this.cmbBox1.SelectedIndex == 0)
    {
        this.cmbBox2.ItemsSource = new object[] { "Item2_0"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_0"};
    }
    else if (this.cmbBox1.SelectedIndex == 1)
    {
        this.cmbBox2ItemsSource = new object[] { "Item2_1"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_1"};
    }

}

private void cmbBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box2String = cmbBox2.SelectedItem.ToString();

    //Rest of the code//

}

When the form opens up the code works perfectly. Now afer the selections are made, if the user goes back and changes the selection in combobox1, then code crashes with error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

at the first line of the Combobox2 SelectionIndexChanged event. I thought it is due to the fact that I am clearing the items in Combobox2 and combobox3 when any change happens in combobox1. So I tried commenting thoses lines out, but was not successful either. I currently have no clue why this is occurring and any help is greatly appreciated.

Body:
I found a solution that fixed the issue. What I did was to delink the selectionchanged event for comboboxes 2 & 3 within the selection changed event of combobox1. Later after I bind the items for comboboxes 2 & 3 I again assign the function to the selection changed event. Here is the code that worked.

private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //this.cmbBox2.Items.Clear();
    //this.cmbBox3.Items.Clear();

    //this.cmbBox2.ItemsSource = new object[] {};
    //this.cmbBox3.ItemsSource = new object[] {};

    string Box1String = cmbBox1.SelectedItem.ToString();
    this.cmbBox2.SelectionChanged -= new SelectionChangedEventHandler(cmbBox2_SelectedIndexChanged);
    this.cmbBox3.SelectionChanged -= new SelectionChangedEventHandler(cmbBox3_SelectedIndexChanged);

    if (this.cmbBox1.SelectedIndex == 0)
    {
        this.cmbBox2.ItemsSource = new object[] { "Item2_0"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_0"};
    }
    else if (this.cmbBox1.SelectedIndex == 1)
    {
        this.cmbBox2ItemsSource = new object[] { "Item2_1"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_1"};
    }
    this.cmbBox2.SelectionChanged += new SelectionChangedEventHandler(cmbBox2_SelectedIndexChanged);
    this.cmbBox3.SelectionChanged += new SelectionChangedEventHandler(cmbBox3_SelectedIndexChanged);
}

private void cmbBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box2String = cmbBox2.SelectedItem.ToString();

    //Rest of the code//

}

private void cmbBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box3String = cmbBox3.SelectedItem.ToString();

    //Rest of the code//

}


问:
How can I attach a custom form to a Workfront user with the API?
I have a requirement to insert new Workfront users through the API, which I am able to do. However, I need to update a Custom Form item with an employee id. With a new user, the Custom Form must be attached before the employee id can be update. I am using the following url to attach the form:

```<code>https://<url>/attask/api/user/<userguid>?sessionID=<sessionid>&updates={'objectCategories':[{'categoryID': '225845d1800010d52527455df2a27f0fe2','categoryOrder':0,'objCode':'CTGY'}]}&method=put
</code>```

The result is a HTTP Error 400: Bad Request

Is it even possible to attach a Custom Form to a user? Or is there another way that it can be done through the API?

答:
For reference, I had to work through the exact same question. You are correct in your update that you need to use the most recent version of the API (as of this post, that would be 6.0) but for others who are wondering, the syntax is as follows:

https://<url>/attask/api/v6.0/USER/<userID>?apiKey=<key>&updates={"objectCategories":[{"categoryID":"<customFormID>","categoryOrder":0,"objCode":"CTGY"}]}&method=put

Body:
I have a requirement to insert new Workfront users through the API, which I am able to do. However, I need to update a Custom Form item with an employee id. With a new user, the Custom Form must be attached before the employee id can be update. I am using the following url to attach the form:

https://<url>/attask/api/user/<userguid>?sessionID=<sessionid>&updates={'objectCategories':[{'categoryID': '225845d1800010d52527455df2a27f0fe2','categoryOrder':0,'objCode':'CTGY'}]}&method=put

The result is a HTTP Error 400: Bad Request

Is it even possible to attach a Custom Form to a user? Or is there another way that it can be done through the API?


问:
Why does this HashSet code snippet behave this way?
Given the following code:

```<code>public class NewClass {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
        Set<String> fruitsSet = new HashSet<>();

        for (String fruit : fruits) {
            fruitsSet.add(fruit);
        }

        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
    }
}
</code>```

Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:

```<code>Banana
Pineapple
Orange
</code>```

My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)

答:
The order in which HashSet stores elements depends on the hashCode of each element. Because each time you're placing the same Strings their hashCodes are also the same and the order the same as well.

But as Louis Wasserman said you shouldn't rely on that order because there are no guarantees that it will not be changed in newer JDKs.

Body:
Given the following code:

public class NewClass {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
        Set<String> fruitsSet = new HashSet<>();

        for (String fruit : fruits) {
            fruitsSet.add(fruit);
        }

        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
    }
}

Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:

Banana
Pineapple
Orange

My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)


问:
How to convert office file to image
I am searching from last two days but did not find any thing.

My requirement is to create a document viewer in my web application (C#.Net) and I don't want to use any third party tool for this. Can I convert the files in image or PDF or in any common formate which can be easly render on web page. I also can not use Introp object.

Any help will be highly appreciated

答: If you cannot use COM/Interop technologies in your solution, you can take a look at the specialized 3rd party options. I see that you prefer not to use them, however, there are no existing built-in solutions in the .NET Framework. Check out my answer in a similar thread that describes how to accomplish exactly the same task using 3rd party libraries (for example, DevExpress, since I have experience with it). In addition, take a look at the Documents demo, where you can see how to create images/thumbnails from different types of MS Office documents.</p>

Title: How to convert office file to image


问:
Why is this named pipe not printing the sent line?
The following server creates a named pipe when it's run like this:

```<code>./serverprogram -p nameofthepipe -t 99
</code>```

the optarg after t indicates a number of threads to be created (not done here).

Anyway, the pipe isn't working here:

```<code>/* Open the first named pipe for reading */
    int rdfd = open(pipeName, O_RDONLY);

 /* Read from the first pipe */
int numread = read(rdfd, command_and_pid, 280);

printf("what's being read is %s \n", command_and_pid);  // not printing!!1!
</code>```

Why?

Server program:

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

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

char pipeName[30];
int  numThreads;

char command_and_pid[280];

  int opcion;
        if (argc < 2) {
        printf ("ERROR: Missing arguments\n");//
        exit(1);
   }
  opterr = 0;

while ((opcion = getopt (argc, argv, "p:t:w")) != -1)
{
        switch (opcion) {

               case 'p': // -p indica el nombre del pipe
               printf("The name of the pipe is: %s\n",optarg);
               strcpy(pipeName, optarg);

               break;

               case 't'://-t indica los hilos
        printf("The number of threads is: %s\n",optarg);
               numThreads= atoi(optarg);

               break;

               case '?':
        fprintf(stderr,"no reconozco esa opcion\n");
               break;
        }
}

    int ret_val = mkfifo(pipeName, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

     /* Open the first named pipe for reading */
    int rdfd = open(pipeName, O_RDONLY);

     /* Read from the first pipe */
    int numread = read(rdfd, command_and_pid, 280);

    printf("what's being read is %s \n", command_and_pid);  // not printing!!1!

    close(rdfd);

   return 0;
}
</code>```

Client program:

```<code>#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

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

        char pipeName[30];

        printf("write the name of the pipe used to write to the server \n");

        fgets(pipeName,30, stdin);

         /* Open the first named pipe for writing */
        int wrfd = open(pipeName, O_WRONLY);

         printf("write the name of the command you want to execute \n");

         char command_and_pid[280];
         char command[250];

          fgets(command,250, stdin);
          puts(command); //quitar

         strcpy(command_and_pid,command);
         strcat(command_and_pid," ");

         int pipeIntId;

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         strcat(command_and_pid,pidstring);

         int written;

         written=write(pipeIntId,command_and_pid,280);
         //write to the pipe
         // send the command and pid

         close(pipeIntId); // close write pipe

 return 0;
}
</code>```

答:
In the client, fgets keeps the newline at the end of the line, so you'll need to strip that before opening the file.

Also, in the code as given, you're opening wrfd but writing to pipeIntId, which is uninitialized (though perhaps you are extracting something from a function here).

Body:
The following server creates a named pipe when it's run like this:

./serverprogram -p nameofthepipe -t 99

the optarg after t indicates a number of threads to be created (not done here).

Anyway, the pipe isn't working here:

/* Open the first named pipe for reading */
    int rdfd = open(pipeName, O_RDONLY);

 /* Read from the first pipe */
int numread = read(rdfd, command_and_pid, 280);

printf("what's being read is %s \n", command_and_pid);  // not printing!!1!

Why?

Server program:

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

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

char pipeName[30];
int  numThreads;

char command_and_pid[280];

  int opcion;
        if (argc < 2) {
        printf ("ERROR: Missing arguments\n");//
        exit(1);
   }
  opterr = 0;

while ((opcion = getopt (argc, argv, "p:t:w")) != -1)
{
        switch (opcion) {

               case 'p': // -p indica el nombre del pipe
               printf("The name of the pipe is: %s\n",optarg);
               strcpy(pipeName, optarg);

               break;

               case 't'://-t indica los hilos
        printf("The number of threads is: %s\n",optarg);
               numThreads= atoi(optarg);

               break;

               case '?':
        fprintf(stderr,"no reconozco esa opcion\n");
               break;
        }
}

    int ret_val = mkfifo(pipeName, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

     /* Open the first named pipe for reading */
    int rdfd = open(pipeName, O_RDONLY);

     /* Read from the first pipe */
    int numread = read(rdfd, command_and_pid, 280);

    printf("what's being read is %s \n", command_and_pid);  // not printing!!1!

    close(rdfd);

   return 0;
}

Client program:

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

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

        char pipeName[30];

        printf("write the name of the pipe used to write to the server \n");

        fgets(pipeName,30, stdin);

         /* Open the first named pipe for writing */
        int wrfd = open(pipeName, O_WRONLY);

         printf("write the name of the command you want to execute \n");

         char command_and_pid[280];
         char command[250];

          fgets(command,250, stdin);
          puts(command); //quitar

         strcpy(command_and_pid,command);
         strcat(command_and_pid," ");

         int pipeIntId;

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         strcat(command_and_pid,pidstring);

         int written;

         written=write(pipeIntId,command_and_pid,280);
         //write to the pipe
         // send the command and pid

         close(pipeIntId); // close write pipe

 return 0;
}


问:
check a background treatment process in ksh
How to test continuously and in the background if a treatment is in error.
if error i will send an error mail</p>

答:
The wrong method IMHO is running a background process that will test and sleep and test and ...   That is terrible for the system administrator (what is going on on the system), you need additional actions (start after reboot) and what to do when your proc stops? Perhaps have another one that checks your prog?

Use crontab. Tell how often to check and all goes well (when cron works and your useraccount isnt blocked).

Make some check that one instance of the tester is finished before starting another one (something like a pid-file). And look for the best way to send mail.


问:
PHP function - custom string length function
In php what is a function to only display strings that have a length greater than 50 characters, truncate it to not display more than 130 characters and limit it to one result?

so for example say i have 30 rows in a result set but I only want to show the newest row that have these parameters. If the newest row has 25 characters it should not display. It should only display the newest one that has a string length of 50 or more characters.

答:
Something like this should do just make sure that you grab your data sorting by the newest items first.  The break statement will ensure that the loop is terminated after the first result matching your criteria is found...</p>

```<code>foreach($array_returned_from_query as $row)
{
    if(strlen($row) > 50)
    {
        echo substr($row, 0, 130);
        break;
    }
}
</code>```

Body:
Something like this should do just make sure that you grab your data sorting by the newest items first.  The break statement will ensure that the loop is terminated after the first result matching your criteria is found...

foreach($array_returned_from_query as $row)
{
    if(strlen($row) > 50)
    {
        echo substr($row, 0, 130);
        break;
    }
}


问:
Best way to echo two rows of two?
I am retrievieng from a query 4 rows.

This rows recover the id (to set the href), the image path and the title.

For example the code for the first row is:

```<code><div class="row">
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">The title</p>
 </a>
</div>
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">Another title</p>
 </a>
</div>
</div>
</code>```

I achieve this using:

```<code>echo "<div class='table'>"
 for($i=0;$i<2;$i++){
  echo "<div class='row'>"
  for($j=0;$j<2;$j++){
   echo "<div class='col'>"
   echo "<a href='id'>
      <img src='file'>
       <p class='titulo-noticia'>".$title."</p>
     </a>"
   echo "</div>"
  } //end col loop
  echo "</div>"
 } //end row loop
echo "</div>"
</code>```

CSS is:

```<code>.col{
    display: table-cell;
}

.row{
    display: row;
}
.table{
    display: table;

}
</code>```

Is this the correct way to show a 2*2 matrix of php content? Or there is a better way using  css?

Thank you.

答:
I don't think there's really a best way, but here's another way with CSS. Basically just echo out all your query results into one container div without worrying about rows. Display each result in a div with float: left and width: 50% and they'll make their own rows.

```<code><div class="matrix">
    <?php while ($row = however_youre_fetching_them()): ?>
        <div class="cell">
            <a href="<?= $row['id'] ?>">
                <img src="<?= $row['path'] ?>">
                <p><?= $row['title'] ?></p>
            </a>
        </div>
    <?php endwhile ?>
</div>
</code>```

And the CSS

```<code>.cell {
    height: 100px;
    width: 50%;
    float: left;
}
</code>```

Setting a constant height on the cells should ensure that the rows line up properly.

Title: Best way to echo two rows of two?

Body:
I am retrievieng from a query 4 rows.

This rows recover the id (to set the href), the image path and the title.

For example the code for the first row is:

The title

Another title

I achieve this using:

echo "
"
 for($i=0;$i<2;$i++){
  echo "
"
  for($j=0;$j<2;$j++){
   echo "
"
   echo "

".$title."

     "
   echo "
"
  } //end col loop
  echo "
"
 } //end row loop
echo "
"

CSS is:

.col{
    display: table-cell;
}

.row{
    display: row;
}
.table{
    display: table;

}

Is this the correct way to show a 2*2 matrix of php content? Or there is a better way using  css?

Thank you.

Body:
I don't think there's really a best way, but here's another way with CSS. Basically just echo out all your query results into one container div without worrying about rows. Display each result in a div with float: left and width: 50% and they'll make their own rows.

<div class="matrix">
    <?php while ($row = however_youre_fetching_them()): ?>
        <div class="cell">
            <a href="<?= $row['id'] ?>">
                <img src="<?= $row['path'] ?>">
                <p><?= $row['title'] ?></p>
            </a>
        </div>
    <?php endwhile ?>
</div>

And the CSS

.cell {
    height: 100px;
    width: 50%;
    float: left;
}

Setting a constant height on the cells should ensure that the rows line up properly.


问:
Merging same columns from a table with different conditions
I want to retrieve data from one table but the data is based on conditions this is my query:

```<code>Select
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-15-2017'
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-22-2017'
       and Store_ID like 'S%')
from
    DailyStockHistory
</code>```

Any help please.

Thanks in advance.

答:
You need to generate PIVOT table to get your expected output, please check this.

Sample Data:

```<code>Insert Into DailyStockHistory Values('SCCC387','SAWA/QuickNet prepaid triosim','2017-03-15',518)
Insert Into DailyStockHistory Values('SCCC387','SAWA/QuickNet prepaid triosim','2017-03-22',251)
</code>```

SQL:

```<code>Select
    *
From
(
    Select
        Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
    From DailyStockHistory
    Where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
        And Store_ID Like 'S%'
        And (Imported_Date = '3-15-2017' Or Imported_Date = '3-22-2017')
) AS Data
PIVOT
(
    SUM(Quantity_On_Hand)
    FOR Imported_Date IN ([3-15-2017],[3-22-2017])
) AS PIVOTData
</code>```

Output:

3-15-2017 & 3-22-2017 are columns for Quantity_On_Hand quantity according to Imported_Date date.

Body:
I want to retrieve data from one table but the data is based on conditions this is my query:

Select
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-15-2017'
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-22-2017'
       and Store_ID like 'S%')
from
    DailyStockHistory

Any help please.

Thanks in advance.

Body:
You need to generate PIVOT table to get your expected output, please check this.

Sample Data:

Insert Into DailyStockHistory Values('SCCC387','SAWA/QuickNet prepaid triosim','2017-03-15',518)
Insert Into DailyStockHistory Values('SCCC387','SAWA/QuickNet prepaid triosim','2017-03-22',251)

SQL:

Select
    *
From
(
    Select
        Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
    From DailyStockHistory
    Where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
        And Store_ID Like 'S%'
        And (Imported_Date = '3-15-2017' Or Imported_Date = '3-22-2017')
) AS Data
PIVOT
(
    SUM(Quantity_On_Hand)
    FOR Imported_Date IN ([3-15-2017],[3-22-2017])
) AS PIVOTData

Output:

3-15-2017 & 3-22-2017 are columns for Quantity_On_Hand quantity according to Imported_Date date.


问:
Django Admin - change header 'Django administration' text
How does one change the 'Django administration' text in the django admin header?

It doesn't seem to be covered in the "Customizing the admin" documentation.

答:
The easiest way of doing it
make sure you have

```<code>from django.contrib import admin
</code>```

and then just add these at bottom of url.py of you main application

```<code>admin.site.site_title = "Your App Title"
admin.site.site_header = "Your App Admin"
</code>```

Body:
The easiest way of doing it
make sure you have

from django.contrib import admin

and then just add these at bottom of url.py of you main application

admin.site.site_title = "Your App Title"
admin.site.site_header = "Your App Admin"


问:
Symfony 3 expected "Doctrine\Common\Collections\ArrayCollection" given ... when using OneToMany
I have a problem with this error:

```<code>Expected argument of type "AppBundle\Entity\BusVehiclesAmenities", "Doctrine\Common\Collections\ArrayCollection" given
</code>```

EDIT 3

After few comments I applied suggestions and error is gone now (remove ArrayCollection from bus vehicles amenities Entity, removed setting bus vehicles amenities entity from controller and removed ORM Join columns on all mapped entites)

Now I have this error:

```<code>The association AppBundle\Entity\BusVehiclesAmenities#bus refers to the inverse side field AppBundle\Entity\BusVehicles#busVehiclesAmenities which does not exist.
</code>```

Mapped entities

Bus vehicles:

```<code>/* @ORM\OneToMany(
     *     targetEntity="BusVehiclesAmenities",
     *     mappedBy="bus",
     *     fetch="EXTRA_LAZY",
     *     orphanRemoval=true,
     *     cascade={"persist"}

     * )
     *
     */

    private $busVehiclesAmenities;
</code>```

bus vehicles amenities entity:

```<code>private $bus;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Amenities", inversedBy="amenities")
     * @ORM\JoinColumn(name="amenities_id", referencedColumnName="id")
     *
     */
</code>```

I am using Collection of Forms to create OneToMany relationship. Problem is when I adding new data I got this error.

Does someone knows where is the problem?

CODE:
Bus Entity (Parent)

```<code>/**
     * @ORM\OneToMany(targetEntity="BusVehiclesAmenities", mappedBy="bus", cascade={"persist", "remove"}, fetch="EAGER", orphanRemoval=true)
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id", onDelete="CASCADE")
     *
     */

private $busVehiclesAmenities;

    public function __construct()
    {

        $this->busVehiclesAmenities = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         if ($this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
             return;
         }
        $this->busVehiclesAmenities->add($busVehiclesAmenities);
        $busVehiclesAmenities->addBus($this);

        return $this;
    }

    /**
     * Set busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function setBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         $this->busVehiclesAmenities = $busVehiclesAmenities;

        return $this;
    }

    /**
     * Remove busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     * @return BusVehicles
     */
    public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        if (!$this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
            return;
        }
        $this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
        $busVehiclesAmenities->removeBus($this);

        return $this;

    }
</code>```

Amenity Entity (Child)

```<code>/**
     *
     * @ORM\ManyToOne(targetEntity="BusVehicles", inversedBy="busVehiclesAmenities")
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id")
     *
     */
    private $bus;

    public function __construct()
    {
        $this->bus = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param BusVehicles $busVehicles
     */

    public function addBus(BusVehicles $busVehicles)
    {
        if ($this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->add($busVehicles);
        $busVehicles->addBusVehiclesAmenities($this);
    }

    /**
     * @param BusVehicles $busVehicles
     */
    public function removeBus(BusVehicles $busVehicles)
    {
        if (!$this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->removeElement($busVehicles);
        $busVehicles->removeBusVehiclesAmenities($this);
    }
</code>```

EDIT 1:

I removed ArrayCollection from BusVehiclesAmenitites Entity but I still got same error when I submit form.

EDIT 2:

Added forms

BusVehicles Form Type

```<code><?php

namespace AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class BusVehiclesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('licencePlate')
            ->add('chassisNumber')
            ->add('manufacturer')
            ->add('busVehiclesAmenities', CollectionType::class, array(
                'entry_type'   => BusVehiclesAmenitiesType::class,
                'prototype' => true,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\BusVehicles',
            'cascade_validation' => true,

        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'adminbundle_busvehicles';
    }

}
</code>```

BusVehiclesAmenities Form Type

```<code>    <?php

namespace AdminBundle\Form\Type;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use AppBundle\Entity\BusVehiclesAmenities;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BusVehiclesAmenitiesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('price', NumberType::class, array(

            ))
            ->add('amenities', EntityType::class, array(
                'class' =>'AppBundle:Amenities',
                'choice_label' => 'name',
            ))

        ;

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => BusVehiclesAmenities::class
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_busvehiclesamenities';
    }

}
</code>```

Controller.

```<code>/**
     * @Template
     */
    public function newAction(Request $request)
    {
        $bus = new BusVehicles();
        $busAmenities = new BusVehiclesAmenities();
        //   $this->getDoctrine()->getManager()->persist($busAmenities);
        $bus->setBusVehiclesAmenities($busAmenities);
        $form = $this->createForm(BusVehiclesType::class, $bus);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            /*$form->get('busVehiclesAmenities')->getData()->map(
                function ($amenities) use ($em, $bus) {

                    $bus->setBusVehiclesAmenities($amenities);
                    $em->persist($amenities);
                }
            );*/
            $em->persist($bus);

            $em->flush();

            // Adding flash message to our user

            $this->addFlash('success', 'admin.bus.created');

            //  return $this->redirectToRoute('bus_add');

        }
        return [
            'form' => $form->createView(),
        ];
    }
</code>```

答:
BusVehiclesAmenities->bus is an object, not a collection. The line $this->bus = new ArrayCollection(); has no reason to exist in your child entity.

You want to achieve ManyToOne, a Many (amentities) aka an ArrayCollection in a object (bus) which is a single object.

Edit

In your controller you do the following

```<code>$bus->setBusVehiclesAmenities($busAmenities);
</code>```

This is not needed. The form will handle the collection by himself. magic

Your error may come from this call, but this is because you are trying to say arrayCollection = object which is not possible.

```<code>  public function setBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        // ArrayCollection = Object
        $this->busVehiclesAmenities = $busVehiclesAmenities;
        return $this;
    }
</code>```

You can either try to do setBusVehiclesAmenities(ArrayCollection $busVehiclesAmenities) or Collection, I don't know, or remove the setBusVehiclesAmenities method. (personally I would remove the method)

Also you should check your getter/setter for bus in your child, this time your variable is a single object, juste do getBus() and setBus($bus), not add and remove.

Hope this may helps you

Body:
I have a problem with this error:

Expected argument of type "AppBundle\Entity\BusVehiclesAmenities", "Doctrine\Common\Collections\ArrayCollection" given

EDIT 3

After few comments I applied suggestions and error is gone now (remove ArrayCollection from bus vehicles amenities Entity, removed setting bus vehicles amenities entity from controller and removed ORM Join columns on all mapped entites)

Now I have this error:

The association AppBundle\Entity\BusVehiclesAmenities#bus refers to the inverse side field AppBundle\Entity\BusVehicles#busVehiclesAmenities which does not exist.

Mapped entities

Bus vehicles:

/* @ORM\OneToMany(
     *     targetEntity="BusVehiclesAmenities",
     *     mappedBy="bus",
     *     fetch="EXTRA_LAZY",
     *     orphanRemoval=true,
     *     cascade={"persist"}

     * )
     *
     */

    private $busVehiclesAmenities;

bus vehicles amenities entity:

private $bus;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Amenities", inversedBy="amenities")
     * @ORM\JoinColumn(name="amenities_id", referencedColumnName="id")
     *
     */

I am using Collection of Forms to create OneToMany relationship. Problem is when I adding new data I got this error.

Does someone knows where is the problem?

CODE:
Bus Entity (Parent)

/**
     * @ORM\OneToMany(targetEntity="BusVehiclesAmenities", mappedBy="bus", cascade={"persist", "remove"}, fetch="EAGER", orphanRemoval=true)
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id", onDelete="CASCADE")
     *
     */

private $busVehiclesAmenities;

    public function __construct()
    {

        $this->busVehiclesAmenities = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         if ($this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
             return;
         }
        $this->busVehiclesAmenities->add($busVehiclesAmenities);
        $busVehiclesAmenities->addBus($this);

        return $this;
    }

    /**
     * Set busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function setBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         $this->busVehiclesAmenities = $busVehiclesAmenities;

        return $this;
    }

    /**
     * Remove busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     * @return BusVehicles
     */
    public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        if (!$this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
            return;
        }
        $this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
        $busVehiclesAmenities->removeBus($this);

        return $this;

    }

Amenity Entity (Child)

/**
     *
     * @ORM\ManyToOne(targetEntity="BusVehicles", inversedBy="busVehiclesAmenities")
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id")
     *
     */
    private $bus;

    public function __construct()
    {
        $this->bus = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param BusVehicles $busVehicles
     */

    public function addBus(BusVehicles $busVehicles)
    {
        if ($this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->add($busVehicles);
        $busVehicles->addBusVehiclesAmenities($this);
    }

    /**
     * @param BusVehicles $busVehicles
     */
    public function removeBus(BusVehicles $busVehicles)
    {
        if (!$this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->removeElement($busVehicles);
        $busVehicles->removeBusVehiclesAmenities($this);
    }

EDIT 1:

I removed ArrayCollection from BusVehiclesAmenitites Entity but I still got same error when I submit form.

EDIT 2:

Added forms

BusVehicles Form Type

<?php

namespace AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class BusVehiclesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('licencePlate')
            ->add('chassisNumber')
            ->add('manufacturer')
            ->add('busVehiclesAmenities', CollectionType::class, array(
                'entry_type'   => BusVehiclesAmenitiesType::class,
                'prototype' => true,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\BusVehicles',
            'cascade_validation' => true,

        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'adminbundle_busvehicles';
    }

}

BusVehiclesAmenities Form Type

    <?php

namespace AdminBundle\Form\Type;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use AppBundle\Entity\BusVehiclesAmenities;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BusVehiclesAmenitiesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('price', NumberType::class, array(

            ))
            ->add('amenities', EntityType::class, array(
                'class' =>'AppBundle:Amenities',
                'choice_label' => 'name',
            ))

        ;

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => BusVehiclesAmenities::class
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_busvehiclesamenities';
    }

}

Controller.

/**
     * @Template
     */
    public function newAction(Request $request)
    {
        $bus = new BusVehicles();
        $busAmenities = new BusVehiclesAmenities();
        //   $this->getDoctrine()->getManager()->persist($busAmenities);
        $bus->setBusVehiclesAmenities($busAmenities);
        $form = $this->createForm(BusVehiclesType::class, $bus);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            /*$form->get('busVehiclesAmenities')->getData()->map(
                function ($amenities) use ($em, $bus) {

                    $bus->setBusVehiclesAmenities($amenities);
                    $em->persist($amenities);
                }
            );*/
            $em->persist($bus);

            $em->flush();

            // Adding flash message to our user

            $this->addFlash('success', 'admin.bus.created');

            //  return $this->redirectToRoute('bus_add');

        }
        return [
            'form' => $form->createView(),
        ];
    }

Body:
BusVehiclesAmenities->bus is an object, not a collection. The line $this->bus = new ArrayCollection(); has no reason to exist in your child entity.

You want to achieve ManyToOne, a Many (amentities) aka an ArrayCollection in a object (bus) which is a single object.

Edit

In your controller you do the following

$bus->setBusVehiclesAmenities($busAmenities);

This is not needed. The form will handle the collection by himself. magic

Your error may come from this call, but this is because you are trying to say arrayCollection = object which is not possible.

  public function setBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        // ArrayCollection = Object
        $this->busVehiclesAmenities = $busVehiclesAmenities;
        return $this;
    }

You can either try to do setBusVehiclesAmenities(ArrayCollection $busVehiclesAmenities) or Collection, I don't know, or remove the setBusVehiclesAmenities method. (personally I would remove the method)

Also you should check your getter/setter for bus in your child, this time your variable is a single object, juste do getBus() and setBus($bus), not add and remove.

Hope this may helps you


问:
get temp file name in server machine folder in c#
I want to get the temp file name in my server machine temp folder. For example:

```<code>string TempFile = System.IO.Path.GetTempFileName();
</code>```

but instead of using System.IO.Path.GetTempFileName() I need to use Environment. How can I accomplish that? Thanks

答: Look with class Environment Environment.GetEnvironmentVariable("TEMP")

Body:
I want to get the temp file name in my server machine temp folder. For example:

string TempFile = System.IO.Path.GetTempFileName();

but instead of using System.IO.Path.GetTempFileName() I need to use Environment. How can I accomplish that? Thanks


问:
Passing Object back from view on Ruby on rails
I tried this:

```<code>th = link_to "ID", results_path(sort: "id", search_form: @search_form)
</code>```

to return the instance @search_form to the controller "results", but that returns a nil variable, but I have to point out that the sort variable accessed on the controller in this way params[:sort] has the correct value, so the path works.

So now I have to return every single attribute by its own and this is the solution that works

```<code>th = link_to "ID",
                      :sort => "id",
                      :verweildauer => @search_form.verweildauer,
                      :datenjahr => @search_form.datenjahr,
                      :drgsystem => @search_form.drgsystem,
                      :greatersmallerequal => @search_form.greatersmallerequal,
                      :patients_per_page => @search_form.patients_per_page
</code>```

then I have to rebuild the object on the controller accessing every single attribute.

How can I directly pass in the @search_form into the controller?

答: If I correctly understand you want to pass many filter params to the get/link_to. It is a bad idea because of get request query size limit. You should use form tag here and move all your params to hidden fields. This is the right way.    </p>

Body:
I tried this:

th = link_to "ID", results_path(sort: "id", search_form: @search_form)

to return the instance @search_form to the controller "results", but that returns a nil variable, but I have to point out that the sort variable accessed on the controller in this way params[:sort] has the correct value, so the path works.

So now I have to return every single attribute by its own and this is the solution that works

th = link_to "ID",
                      :sort => "id",
                      :verweildauer => @search_form.verweildauer,
                      :datenjahr => @search_form.datenjahr,
                      :drgsystem => @search_form.drgsystem,
                      :greatersmallerequal => @search_form.greatersmallerequal,
                      :patients_per_page => @search_form.patients_per_page

then I have to rebuild the object on the controller accessing every single attribute.

How can I directly pass in the @search_form into the controller?


问:
How can I populate a google maps info window with text from a jQuery ajax request? [example included]
Here I make an ajax request and process it in order to return a paragraph of text. I would like to populate my info window with this text on a 'click' event.

My code functions in so far as the ajax call is successful and the map and markers are rendered in the View. However, the info window does not populate with the text on the 'click' event as I had hoped.

Instead I get a type error:

```<code>TypeError: Cannot read property 'function (){
                wikiExtract(marker.title).then(function (data){
                infowindow...<omitted>... }' of undefined
</code>```

If I try another pattern that seems intuitively correct to me, the map will not load at all:

```<code>google.maps.event.addListener('click',
    wikiExtract(marker.title).then(function (data){
        infowindow.setContent(data);
        infowindow.open(bayarea, marker)
    });
);
</code>```

This is my map and ajax call:

```<code>'use strict';

var bayarea;
var markers = [];

var initMap = function() {
    const map = document.querySelector('#map');
    const center = {
        lat: 37.656,
        lng: -122.288
    };

    bayarea = new google.maps.Map(map, {
        center,
        zoom: 9,
        scrollwheel: false,
    });

    var getMarkers = function getMarkers(siteDatabase) {
        var i = 1;
        for (var site in siteDatabase) {
            site = siteDatabase[site];
            addMarker(site, i * 200);
            i++;
        };

        var infowindow = new google.maps.InfoWindow();

        function addMarker(site, timeout) {
            window.setTimeout(function() {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(site.lat, site.lng),
                    map: bayarea,
                    title: site.position,
                    animation: google.maps.Animation.DROP
                });
                google.maps.event.addListener('click',function (){
                    wikiExtract(marker.title).then(function (data){
                    infowindow.setContent(data);
                    infowindow.open(bayarea, marker);
                    });

                });
                markers.push(marker);
            }, timeout);
        }
    };
    getMarkers(siteDatabase);
};

function wikiExtract(site) {
    return $.when(ventanaWik(site)).then( (wiki) => {
        return dig(wiki.query.pages).extract;
    });
    function dig(object) {
        return object[Object.keys(object)[0]];
    }
    function ventanaWik(site) {
        return $.ajax({
            type: 'json',
            url: 'https://en.wikipedia.org/w/api.php' + '?origin=*'
            + '&format=json' + '&action=query' + '&prop=extracts'
            + '&exintro=' + '&explaintext=' + '&titles=' + site,
            method: 'GET'
        }).promise();
    }
};
</code>```

EDIT: Works using this pattern

```<code>   var initMap = function() {
    const map = document.querySelector('#map');
    const center = {
        lat: 37.656,
        lng: -122.288
    };

    bayarea = new google.maps.Map(map, {
        center,
        zoom: 9,
        scrollwheel: false,
    });

    var getMarkers = function getMarkers(siteDatabase) {
        var i = 1;
        for (var site in siteDatabase) {
            site = siteDatabase[site];
            addMarker(site, i * 200);
            i++;
        }

        var infowindow = new google.maps.InfoWindow({
            content: "<i class='fa fa-spinner fa-spin fa-lg' style='color: #FFA46B;' title='Loading...'></i> Loading..."
        });

        function addMarker(site, timeout) {
            window.setTimeout(function() {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(site.lat, site.lng),
                    map: bayarea,
                    title: site.position,
                    county: site.county,
                    animation: google.maps.Animation.DROP
                });
            google.maps.event.addListener(marker, 'click', (function(marker, infowindow) {
                return function() {
                    if (infowindow) {
                        infowindow.close();
                    }
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                    setTimeout(function(){ marker.setAnimation(null); }, 1500);
                    infowindow.open(bayarea, marker);
                    wikiExtract(marker.title).then(function(data) {
                        infowindow.setContent(data);
                    });
                };
            })(marker, infowindow));
            markers.push(marker);
            }, timeout);
        }
    };
    getMarkers(siteDatabase);
};

function wikiExtract(site) {
    return $.when(ventanaWik(site)).then( (wiki) => {
        return dig(wiki.query.pages).extract;
    });
    function dig(object) {
        return object[Object.keys(object)[0]];
    }
    function ventanaWik(site) {
        return $.ajax({
            type: 'json',
            url: 'https://en.wikipedia.org/w/api.php' + '?origin=*'
            + '&format=json' + '&action=query' + '&prop=extracts'
            + '&exintro=' + '&explaintext=' + '&titles=' + site,
            method: 'GET'
        }).promise();
    }
}
</code>```

答:
According to the documentation google.maps.event.addListener() has 3 parameters: instance:Object, eventName:string, handler:Function.

https://developers.google.com/maps/documentation/javascript/reference#event

You are missing the first parameter:

```<code>google.maps.event.addListener(marker, 'click', function (){
    wikiExtract(marker.title).then(function (data){
        infowindow.setContent(data);
        infowindow.open(bayarea, marker);
    });
});
</code>```

Body:
Here I make an ajax request and process it in order to return a paragraph of text. I would like to populate my info window with this text on a 'click' event.

My code functions in so far as the ajax call is successful and the map and markers are rendered in the View. However, the info window does not populate with the text on the 'click' event as I had hoped.

Instead I get a type error:

TypeError: Cannot read property 'function (){
                wikiExtract(marker.title).then(function (data){
                infowindow...<omitted>... }' of undefined

If I try another pattern that seems intuitively correct to me, the map will not load at all:

google.maps.event.addListener('click',
    wikiExtract(marker.title).then(function (data){
        infowindow.setContent(data);
        infowindow.open(bayarea, marker)
    });
);

This is my map and ajax call:

'use strict';

var bayarea;
var markers = [];

var initMap = function() {
    const map = document.querySelector('#map');
    const center = {
        lat: 37.656,
        lng: -122.288
    };

    bayarea = new google.maps.Map(map, {
        center,
        zoom: 9,
        scrollwheel: false,
    });

    var getMarkers = function getMarkers(siteDatabase) {
        var i = 1;
        for (var site in siteDatabase) {
            site = siteDatabase[site];
            addMarker(site, i * 200);
            i++;
        };

        var infowindow = new google.maps.InfoWindow();

        function addMarker(site, timeout) {
            window.setTimeout(function() {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(site.lat, site.lng),
                    map: bayarea,
                    title: site.position,
                    animation: google.maps.Animation.DROP
                });
                google.maps.event.addListener('click',function (){
                    wikiExtract(marker.title).then(function (data){
                    infowindow.setContent(data);
                    infowindow.open(bayarea, marker);
                    });

                });
                markers.push(marker);
            }, timeout);
        }
    };
    getMarkers(siteDatabase);
};

function wikiExtract(site) {
    return $.when(ventanaWik(site)).then( (wiki) => {
        return dig(wiki.query.pages).extract;
    });
    function dig(object) {
        return object[Object.keys(object)[0]];
    }
    function ventanaWik(site) {
        return $.ajax({
            type: 'json',
            url: 'https://en.wikipedia.org/w/api.php' + '?origin=*'
            + '&format=json' + '&action=query' + '&prop=extracts'
            + '&exintro=' + '&explaintext=' + '&titles=' + site,
            method: 'GET'
        }).promise();
    }
};

EDIT: Works using this pattern

   var initMap = function() {
    const map = document.querySelector('#map');
    const center = {
        lat: 37.656,
        lng: -122.288
    };

    bayarea = new google.maps.Map(map, {
        center,
        zoom: 9,
        scrollwheel: false,
    });

    var getMarkers = function getMarkers(siteDatabase) {
        var i = 1;
        for (var site in siteDatabase) {
            site = siteDatabase[site];
            addMarker(site, i * 200);
            i++;
        }

        var infowindow = new google.maps.InfoWindow({
            content: " Loading..."
        });

        function addMarker(site, timeout) {
            window.setTimeout(function() {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(site.lat, site.lng),
                    map: bayarea,
                    title: site.position,
                    county: site.county,
                    animation: google.maps.Animation.DROP
                });
            google.maps.event.addListener(marker, 'click', (function(marker, infowindow) {
                return function() {
                    if (infowindow) {
                        infowindow.close();
                    }
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                    setTimeout(function(){ marker.setAnimation(null); }, 1500);
                    infowindow.open(bayarea, marker);
                    wikiExtract(marker.title).then(function(data) {
                        infowindow.setContent(data);
                    });
                };
            })(marker, infowindow));
            markers.push(marker);
            }, timeout);
        }
    };
    getMarkers(siteDatabase);
};

function wikiExtract(site) {
    return $.when(ventanaWik(site)).then( (wiki) => {
        return dig(wiki.query.pages).extract;
    });
    function dig(object) {
        return object[Object.keys(object)[0]];
    }
    function ventanaWik(site) {
        return $.ajax({
            type: 'json',
            url: 'https://en.wikipedia.org/w/api.php' + '?origin=*'
            + '&format=json' + '&action=query' + '&prop=extracts'
            + '&exintro=' + '&explaintext=' + '&titles=' + site,
            method: 'GET'
        }).promise();
    }
}

Body:
According to the documentation google.maps.event.addListener() has 3 parameters: instance:Object, eventName:string, handler:Function.

https://developers.google.com/maps/documentation/javascript/reference#event

You are missing the first parameter:

google.maps.event.addListener(marker, 'click', function (){
    wikiExtract(marker.title).then(function (data){
        infowindow.setContent(data);
        infowindow.open(bayarea, marker);
    });
});


问:
iOS SegmentedControl equivalent in Android
What is a good Android analog of iOS's UISegmentedControl?

答: Benjamin Ferrari has a nice implementation here: http://blog.bookworm.at/2010/10/segmented-controls-in-android.html . Essentially he's just overridden the RadioButton.</p>


答:
From Amenity Entity (Child) remove this part of code:

```<code>public function __construct()
{
    $this->bus = new ArrayCollection();
}
</code>```

It should solve your problem, if forms have been defined right way.

Explanation - bus in this entity is the owning side of OneToMany relation. It's always one, it can't be a collection.

Title: Symfony 3 expected "Doctrine\Common\Collections\ArrayCollection" given ... when using OneToMany

Body:
From Amenity Entity (Child) remove this part of code:

public function __construct()
{
    $this->bus = new ArrayCollection();
}

It should solve your problem, if forms have been defined right way.

Explanation - bus in this entity is the owning side of OneToMany relation. It's always one, it can't be a collection.


问:
Polymer, how to adjust padding to internal div on paper-dialog-scrollable
The content area of paper-dialog-scrollable has a 24px padding on the left and right. I'd like to change that. When the HTML is rendered, it's an in-line style sheet and an in-line div that has the padding. I've tried using the following to no avail. The polymer inline styles come in after my inline style.

DOES NOT WORK:

```<code><style>
  .scrollable {
    --paper-dialog-scrollable: {
        padding-left: 0px;
        padding-right: 0px;
    };
  }
</style>
</code>```

In the following image  it is the div with id="scrollable" that I need to change. I think it is scope=paper-dialog-scrollable-0 that actually sets the padding.

So how do I adjust padding to internal div on paper-dialog-scrollable?

答:
I found another way, just by using the element style, as follow</p>

```<code>paper-dialog-scrollable { --paper-dialog-scrollable:  { padding: 0 10px; }; }
</code>```

Body:
The content area of paper-dialog-scrollable has a 24px padding on the left and right. I'd like to change that. When the HTML is rendered, it's an in-line style sheet and an in-line div that has the padding. I've tried using the following to no avail. The polymer inline styles come in after my inline style.

DOES NOT WORK:

In the following image  it is the div with id="scrollable" that I need to change. I think it is scope=paper-dialog-scrollable-0 that actually sets the padding.

So how do I adjust padding to internal div on paper-dialog-scrollable?

Body:
I found another way, just by using the element style, as follow

paper-dialog-scrollable { --paper-dialog-scrollable:  { padding: 0 10px; }; }


问:
$http.get not sending data in the body of the request
Using angular v1.3.1 i got a singular the following problem trying to implement a facade for making http request to a REST + JSON interface in the backend of the web app.

I got something like this in the code:

```<code>findSomething(value: number): ng.IPromise<api.DrugIndication[]> {
  const getParams = { 'param' : 'value' };
  const config:ng.IRequestShortcutConfig = {
    headers: {
      "Content-Type" : "application/json"
    },
    data: getParams
  }
  return this.$http.get(url,config);
}
</code>```

And when the times comes to invoke it, i got an 400 Bad Request (btw: Great name for a band!) because the backend (made with Play for Scala) rejects the request inmediately. So making an inspection in the request i see that no data is being send in the body of the request/message.

So how i can send some data in the body of and HTTP Get request using angular "$http.get"?

Additional info: This doesn't happen if i the make request using the curl command from an ubuntu shell. So probably is an problem between Chrome and angular.js

答:
If you inspect the network tab in chrome development tools you will see that this is a pre-flight OPTIONS request (Cross-Origin Resource Sharing (CORS)).

You have two ways to solve this.

Client side (this requires that your server does not require the application/json value)

GET, POST, HEAD methods only

Only browser set headers plus these

Content-Type only with:

application/x-www-form-urlencoded

multipart/form-data

text/plain

Server side

Set something like this as a middleware on your server framework:

```<code>if r.Method == "OPTIONS" {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "GET")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
    w.Header().Set("Access-Control-Max-Age", "86400") // firefox: max 24h, chrome 10min
    return
}
</code>```

For your specific framework this should work

Body:
Using angular v1.3.1 i got a singular the following problem trying to implement a facade for making http request to a REST + JSON interface in the backend of the web app.

I got something like this in the code:

findSomething(value: number): ng.IPromise<api.DrugIndication[]> {
  const getParams = { 'param' : 'value' };
  const config:ng.IRequestShortcutConfig = {
    headers: {
      "Content-Type" : "application/json"
    },
    data: getParams
  }
  return this.$http.get(url,config);
}

And when the times comes to invoke it, i got an 400 Bad Request (btw: Great name for a band!) because the backend (made with Play for Scala) rejects the request inmediately. So making an inspection in the request i see that no data is being send in the body of the request/message.

So how i can send some data in the body of and HTTP Get request using angular "$http.get"?

Additional info: This doesn't happen if i the make request using the curl command from an ubuntu shell. So probably is an problem between Chrome and angular.js

Body:
If you inspect the network tab in chrome development tools you will see that this is a pre-flight OPTIONS request (Cross-Origin Resource Sharing (CORS)).

You have two ways to solve this.

Client side (this requires that your server does not require the application/json value)

GET, POST, HEAD methods only

Only browser set headers plus these

Content-Type only with:

application/x-www-form-urlencoded

multipart/form-data

text/plain

Server side

Set something like this as a middleware on your server framework:

if r.Method == "OPTIONS" {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "GET")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
    w.Header().Set("Access-Control-Max-Age", "86400") // firefox: max 24h, chrome 10min
    return
}

For your specific framework this should work


问:
how to use beautifulsoup and regular expression to get IP address from a proxy website
I am trying to use Beautifulsoup and regular expressions to get the IP address from the website (http://www.gatherproxy.com/).

By inspecting the website, I saw that the IP address existing in the following format:

```<code><tr class="proxy 149-56-34-94-225F" prx="149.56.34.94:8799" time="2017-03-29T15:42:33Z" type="Transparent" country="United States" port="8799" tmres="797"><td>2m 54s ago</td><td>149.56.34.94</td><td><a>

<tr class="proxy 138-68-180-44-1FB6" prx="138.68.180.44:8118" time="2017-03-29T15:42:32Z" type="Elite" country="United States" port="8118" tmres="47"><td>3m 25s ago</td><td>138.68.180.44</td><td><a>
</code>```

So I am using the following code to get each tag

```<code>soup.find_all(name='tr',attrs={'class':re.compile(r"proxy [0-9a-zA-Z]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+")})
</code>```

But the output is nothing.

答:
If you print the contents of your request from that website, you'll notice that the rows are being generated via Javascript.

Here's an example of that:

gp.insertPrx({"PROXY_CITY":"","PROXY_COUNTRY":"France","PROXY_IP":"149.202.191.205","PROXY_LAST_UPDATE":"3 1","PROXY_PORT":"C38","PROXY_REFS":null,"PROXY_STATE":"","PROXY_STATUS":"OK","PROXY_TIME":"524","PROXY_TYPE":"Transparent","PROXY_UID":null,"PROXY_UPTIMELD":"4152/393"});

For this step you don't need BeautifulSoup, you can regex the contents directly.

Like this:

```<code>import re
import requests
import json

result = requests.get("http://www.gatherproxy.com").content
matches = re.findall(r'gp\.insertPrx\(([^(]*)\);', str(result))

for match in matches:
    _object = json.loads(match)
    print (_object["PROXY_IP"])
</code>```

Which outputs:

104.156.226.80

52.32.220.134

138.68.184.128

...

Body:
I am trying to use Beautifulsoup and regular expressions to get the IP address from the website (http://www.gatherproxy.com/).

By inspecting the website, I saw that the IP address existing in the following format:

2m 54s ago	149.56.34.94

3m 25s ago	138.68.180.44

So I am using the following code to get each tag

soup.find_all(name='tr',attrs={'class':re.compile(r"proxy [0-9a-zA-Z]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+")})

But the output is nothing.

Body:
If you print the contents of your request from that website, you'll notice that the rows are being generated via Javascript.

Here's an example of that:

gp.insertPrx({"PROXY_CITY":"","PROXY_COUNTRY":"France","PROXY_IP":"149.202.191.205","PROXY_LAST_UPDATE":"3 1","PROXY_PORT":"C38","PROXY_REFS":null,"PROXY_STATE":"","PROXY_STATUS":"OK","PROXY_TIME":"524","PROXY_TYPE":"Transparent","PROXY_UID":null,"PROXY_UPTIMELD":"4152/393"});

For this step you don't need BeautifulSoup, you can regex the contents directly.

Like this:

import re
import requests
import json

result = requests.get("http://www.gatherproxy.com").content
matches = re.findall(r'gp\.insertPrx\(([^(]*)\);', str(result))

for match in matches:
    _object = json.loads(match)
    print (_object["PROXY_IP"])

Which outputs:

104.156.226.80

52.32.220.134

138.68.184.128

...