问:
How can I avoid using CATiledLayer when rendering a PDF?
I have been trying to render PDF documents into a CATiledLayer, but this appears to be slowing down the rendering process on the iPad.

I've also tried using a normal layer, but I've not seen an improvement.

Is there any alternative to using a CATiledLayer for rendering a PDF?

答:
CATiledLayer is necessary either by itself or as a backing layer for a UIView when you are attempting to display a view or layer that exceeds the maximum texture size supported by the GPU.  Apple lists this as 1024x1024 for the iPhone, but in my experience I've been able to go up to 2048x2048 on even the first-generation iPhone.

If you are able to render to a view or layer that is smaller in both width and height than those dimensions, you don't need to use a CATiledLayer and can get away with a standard layer.  The tiling process does slow rendering a bit as it brings in the appropriate tiles, so you could gain some performance that way.

For a discussion on general PDF rendering performance, I direct you to this question:

Fast and Lean PDF Viewer for iPhone / iPad / iOs - tips and hints?


来源: stackexchange

问:
What file name placeholders are available for Serilog?
I use Serilog on a .NET Core application with RollingFile. I wonder, if there are different filename placeholders? I only know {Date}.

For example, I have code like

```<code>        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.RollingFile("Logs/{Date}.log")
            .CreateLogger();
</code>```

Are there any other options for the filename like {Date}? I'd like to have log files by hour.

答:
At the time of this writing, Serilog's Rolling File sink supports 3 (three) specifiers:

{Date}, which is formatted as yyyyMMdd

{Hour}, which is formatted as yyyyMMddHH

{HalfHour}, which is formatted as yyyyMMddHHmm

You can see it in the README of the Rolling File sink, as well as in the source code of the Rolling File sink.

ContentLicense: CC BY-SA 3.0

Body:
I use Serilog on a .NET Core application with RollingFile. I wonder, if there are different filename placeholders? I only know {Date}.

For example, I have code like

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.RollingFile("Logs/{Date}.log")
            .CreateLogger();

Are there any other options for the filename like {Date}? I'd like to have log files by hour.

ContentLicense: CC BY-SA 4.0


问:
Pod installed Alamofire 4.4, but class is not being autocomplete by Xcode 8.3
I have noticed this problem as closed before but I am getting the same problem.

P.S - I have imported Alamofire in the class mentioned in the screenshot

Here is my pod details

```<code>platform :ios, '10.0'

use_frameworks!
target 'PhotoTagger' do
     pod 'Alamofire'
end
</code>```

Also the only thing being auto completed is AlamofireVersionNumber and i cannot access anything when I am trying to use the auto complete feature. Now if i write Alamofire by hand then I can access some methods, but then again something is going wrong and code is not compiling, which i think boils down to the issue that the class isnt being fetched by auto complete.

I have tried -

In Project settings > Build settings

Always search user path To YES

Header search path to only include "$(inherited)" as non-recursive

All other pods are working fine, except Alamofire.
Also after writing class name by hand or copy pasting, some of the methods that are being auto completed does not have the same signature of the actual method of the Alamofire class

Please please please !! help me sort this out, so that someone out there when facing this can help themselves too. There isnt any solution to this as of now.

P.S

I had opened an issue on Alamofire's Github page, but they responded with

```<code>Sorry, we're not responsible for Xcode's autocomplete issues.
In the future, you should open questions like this on Stack Overflow
and tag alamofire.

Cheers.
</code>```

Please help, I am stuck with this for quite some time.

EDIT :

Here is my project settings details

Also, I have build the project and still the problem persists.

P.S - Writing the class manually by hand , and the methods even, it compiles but everytime, I have to go to the github page, to copy paste the method signature, The problem is that with Autocomplete, i can navigate all method signatures and know about the public available methods. But I am only restricted to the example methods available in github, as everytime I have to copy paste the methods and the overwrite the implementation. Again, this compiles and runs, but the auto complete is not working, not for the class, or for the functions.

答: Sometimes when you install some pod from the terminal's window you need to restart xcode or also the mac, before see the import name correctly.</p>

Body:
I have noticed this problem as closed before but I am getting the same problem.

P.S - I have imported Alamofire in the class mentioned in the screenshot

Here is my pod details

platform :ios, '10.0'

use_frameworks!
target 'PhotoTagger' do
     pod 'Alamofire'
end

Also the only thing being auto completed is AlamofireVersionNumber and i cannot access anything when I am trying to use the auto complete feature. Now if i write Alamofire by hand then I can access some methods, but then again something is going wrong and code is not compiling, which i think boils down to the issue that the class isnt being fetched by auto complete.

I have tried -

In Project settings > Build settings

Always search user path To YES

Header search path to only include "$(inherited)" as non-recursive

All other pods are working fine, except Alamofire.
Also after writing class name by hand or copy pasting, some of the methods that are being auto completed does not have the same signature of the actual method of the Alamofire class

Please please please !! help me sort this out, so that someone out there when facing this can help themselves too. There isnt any solution to this as of now.

P.S

I had opened an issue on Alamofire's Github page, but they responded with

Sorry, we're not responsible for Xcode's autocomplete issues.
In the future, you should open questions like this on Stack Overflow
and tag alamofire.

Cheers.

Please help, I am stuck with this for quite some time.

EDIT :

Here is my project settings details

Also, I have build the project and still the problem persists.

P.S - Writing the class manually by hand , and the methods even, it compiles but everytime, I have to go to the github page, to copy paste the method signature, The problem is that with Autocomplete, i can navigate all method signatures and know about the public available methods. But I am only restricted to the example methods available in github, as everytime I have to copy paste the methods and the overwrite the implementation. Again, this compiles and runs, but the auto complete is not working, not for the class, or for the functions.


问:
IONIC 2 : Error: Unexpected token: name (Players) www/build/main.js at line 26325, col 4, pos 888867
I tried to run "ionic cordova run android --prod" but I've got the following error in my terminal.

[19:33:28] uglifyjs started ...  [WARN] Error occurred during command
  execution from a CLI plugin (@ionic/cli-plugin-cordova). Your plugins
  may be out of date. Error: Unexpected token: name (Players) in
  /Volumes/Macintosh Data/IONIC_PROJECT/hukulele/www/build/main.js at
  line 26325, col 4, pos 888867 Here is my Players class :

```<code>import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

@Injectable()
export class Players{
    players: {name: string}[];

    addPlayer(player: {name: string}){
        this.players.push(player);
    }

    getPlayers(){
        return this.players.slice();
    }

    setPlayers(liste: {name: string}[]){
        this.players = liste;
    }

    initPlayers(){
        this.players = [{"name":""},{"name":""},{"name":""},{"name":""},{"name":""}];
    }
}
</code>```

And the main.js file at line 26325 :

```<code>let Players = class Players {
    addPlayer(player) {
        this.players.push(player);
    }
    getPlayers() {
        return this.players.slice();
    }
    setPlayers(liste) {
        this.players = liste;
    }
    initPlayers() {
        this.players = [{ "name": "" }, { "name": "" }, { "name": "" }, { "name": "" }, { "name": "" }];
    }
};
</code>```

Please help!

答:
Try to update tsconfig.json and set
target: "es5"

I had mine set to es6

Refer to this: https://github.com/AngularClass/angular-starter/issues/853

Body:
I tried to run "ionic cordova run android --prod" but I've got the following error in my terminal.

[19:33:28] uglifyjs started ...  [WARN] Error occurred during command
  execution from a CLI plugin (@ionic/cli-plugin-cordova). Your plugins
  may be out of date. Error: Unexpected token: name (Players) in
  /Volumes/Macintosh Data/IONIC_PROJECT/hukulele/www/build/main.js at
  line 26325, col 4, pos 888867 Here is my Players class :

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

@Injectable()
export class Players{
    players: {name: string}[];

    addPlayer(player: {name: string}){
        this.players.push(player);
    }

    getPlayers(){
        return this.players.slice();
    }

    setPlayers(liste: {name: string}[]){
        this.players = liste;
    }

    initPlayers(){
        this.players = [{"name":""},{"name":""},{"name":""},{"name":""},{"name":""}];
    }
}

And the main.js file at line 26325 :

let Players = class Players {
    addPlayer(player) {
        this.players.push(player);
    }
    getPlayers() {
        return this.players.slice();
    }
    setPlayers(liste) {
        this.players = liste;
    }
    initPlayers() {
        this.players = [{ "name": "" }, { "name": "" }, { "name": "" }, { "name": "" }, { "name": "" }];
    }
};

Please help!


问:
Named enumarations in C++
Am using named enumerations in my code as shown below.

```<code>namespace Config
{
    enum class SubscribersIpVersion
    {
        Dhcpv6,
        DualStack,
        DualStackDhcpv6,
        DualStackSlaac,
        Ipv4,
        Ipv6,
        Slaac,
    };
};
</code>```

In one of my class, a function is returned to the IP version

```<code>class xxxx
{
...
public:
SubscribersIpVersion getIpVersion() {return ipVersion;}
private:
SubscribersIpVersion ipVersion;
};
</code>```

But the following if condition is failing

```<code>if (!isIpv6 && (pSubGroup->getIpVersion() == Config::SubscribersIpVersion::Ipv6 ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::Slaac ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::Dhcpv6 ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStack ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStackSlaac ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStackDhcpv6))
</code>```

The reason I found in gdb is,

```<code>(gdb) pt pSubGroup->getIpVersion()
type = enum Config::SubscribersIpVersion {Config::Dhcpv6, Config::DualStack,
    Config::DualStackDhcpv6, Config::DualStackSlaac, Config::Ipv4, Config::Ipv6,
    Config::Slaac}
(gdb) p pSubGroup->getIpVersion()
$1 = Config::DualStack
</code>```

This is the error in gdb if I compare

```<code>(gdb) p pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStack
`Config::SubscribersIpVersion' is not defined as an aggregate type.
</code>```

Can anyone tell what is wrong with the above code?

答: All: Thanks for the support. I found there is a logic problem in the code. Once that is fixed, everything is working fine.</p>

Title: Named enumarations in C++

Body:
Am using named enumerations in my code as shown below.

namespace Config
{
    enum class SubscribersIpVersion
    {
        Dhcpv6,
        DualStack,
        DualStackDhcpv6,
        DualStackSlaac,
        Ipv4,
        Ipv6,
        Slaac,
    };
};

In one of my class, a function is returned to the IP version

class xxxx
{
...
public:
SubscribersIpVersion getIpVersion() {return ipVersion;}
private:
SubscribersIpVersion ipVersion;
};

But the following if condition is failing

if (!isIpv6 && (pSubGroup->getIpVersion() == Config::SubscribersIpVersion::Ipv6 ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::Slaac ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::Dhcpv6 ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStack ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStackSlaac ||
                     pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStackDhcpv6))

The reason I found in gdb is,

(gdb) pt pSubGroup->getIpVersion()
type = enum Config::SubscribersIpVersion {Config::Dhcpv6, Config::DualStack,
    Config::DualStackDhcpv6, Config::DualStackSlaac, Config::Ipv4, Config::Ipv6,
    Config::Slaac}
(gdb) p pSubGroup->getIpVersion()
$1 = Config::DualStack

This is the error in gdb if I compare

(gdb) p pSubGroup->getIpVersion() == Config::SubscribersIpVersion::DualStack
`Config::SubscribersIpVersion' is not defined as an aggregate type.

Can anyone tell what is wrong with the above code?


问:
aptana unistall from eclipse
Finally I have decided to get rid of aptana from eclipse but the "Software update" menu shows "unistall" as disabled. How to enable unistall and release me of aptana woes? Is there a workaround or I simply go searching for aptana everywhere and delete all files which I will eventually do?</p>

答: Try to run eclipse as Administrator and see what this link can do.</p>

ContentLicense: CC BY-SA 2.5

Title: aptana unistall from eclipse


问:
How to access dimensions and measures from qHyperCube?
I'm very new to developing Qlik Sense extensions.

This question may sound very silly, but can anyone please tell me how to access the result matrix that contains the measures entered from the properties panel? I'm able to get the measures (qNum and qText) from qGrandTotalRow, but qDataPages is always empty.

Has it got anything to do with initialProperties? Currently I've left it empty.

答:
Yes, make sure that you have the initialProperties set properly, e.g:

```<code>initialProperties: {
    qHyperCubeDef: {
        qDimensions: [],
        qMeasures: [],
        qInitialDataFetch: [
            {
                qWidth: 10,
                qHeight: 100
            }
        ]
    }
},
</code>```

See here for a more detailed explanation: http://qliksite.io/tutorials/qliksense-visualization-extensions/part-01/08-Hello-Data/#

Body:
Yes, make sure that you have the initialProperties set properly, e.g:

initialProperties: {
    qHyperCubeDef: {
        qDimensions: [],
        qMeasures: [],
        qInitialDataFetch: [
            {
                qWidth: 10,
                qHeight: 100
            }
        ]
    }
},

See here for a more detailed explanation: http://qliksite.io/tutorials/qliksense-visualization-extensions/part-01/08-Hello-Data/#


问:
dput() sp object in R
Is there a practical way to dput() an sp object in R?

When I try to do the following:

```<code>data(World, package = "tmap")
dput(World[1:10, ], file=(tempFile <- tempfile()))
World2 <- dget(tempFile)
</code>```

I get:

```<code>> World2 <- dget(tempFile)
Error in parse(file = file, keep.source = keep.source) :
  ...\file14f4ee257b1:155:23: unexpected '<'
154: 9L, 10L, 12L, 14L, 16L, 17L), class = "data.frame")
155:     , polygons = list(<
                           ^
</code>```

The < is usually followed by S4 object of class structure("Polygons", package = "sp")>, so dput() apparently does not resolve these nested S4 objects.

The problem seems to be quite similar to this one, but the proposed solution does not work here.

For a solution, please assume that I do not have access to the file system.

EDIT: The more general question is, of course: How can I send a complete sp object to the console?

答:
Despite the comments suggests to save the sp Object as .rds-file (which is probably for the best when saving things for yourself), sometimes it is more preferable to get a text-version of the object. In fact, when providing a reproducible example for SO/SX Qs it is more handy to provide data in text form. Moreover, as stated in the question, there might be cases in which you cannot access the file system.

If you just want to share a sp object's coordinates you can use rgeos::writeWKT()

```<code>library(rgeos)
writeWKT(x)
# [1] "POLYGON ((1441727.5096940901130438 6550163.0046194596216083,
#                 1150685.2609429201111197 6669225.7427449300885201,
#                 975398.4520359700545669 6603079.7771196700632572,
#                 866257.6087542800232768 6401334.5819626096636057,
#                 1441727.5096940901130438 6550163.0046194596216083))"
</code>```

This can then be inserted into your example like:

```<code>library(rgeos)
x <- readwkt("POLYGON ((1441727.5096940901130438 6550163.0046194596216083,
                        1150685.2609429201111197 6669225.7427449300885201,
                        975398.4520359700545669 6603079.7771196700632572,
                        866257.6087542800232768 6401334.5819626096636057,
                        1441727.5096940901130438 6550163.0046194596216083))")
</code>```

Unfortunately, thus the attribute information (x@data) and CRS are lost. Thus, one must consider adding this information if needed by adding dput(x@data) to create a Spatial*DataFrame.

Title: dput() sp object in R

Body:
Is there a practical way to dput() an sp object in R?

When I try to do the following:

data(World, package = "tmap")
dput(World[1:10, ], file=(tempFile <- tempfile()))
World2 <- dget(tempFile)

I get:

> World2 <- dget(tempFile)
Error in parse(file = file, keep.source = keep.source) :
  ...\file14f4ee257b1:155:23: unexpected '<'
154: 9L, 10L, 12L, 14L, 16L, 17L), class = "data.frame")
155:     , polygons = list(<
                           ^

The < is usually followed by S4 object of class structure("Polygons", package = "sp")>, so dput() apparently does not resolve these nested S4 objects.

The problem seems to be quite similar to this one, but the proposed solution does not work here.

For a solution, please assume that I do not have access to the file system.

EDIT: The more general question is, of course: How can I send a complete sp object to the console?

Body:
Despite the comments suggests to save the sp Object as .rds-file (which is probably for the best when saving things for yourself), sometimes it is more preferable to get a text-version of the object. In fact, when providing a reproducible example for SO/SX Qs it is more handy to provide data in text form. Moreover, as stated in the question, there might be cases in which you cannot access the file system.

If you just want to share a sp object's coordinates you can use rgeos::writeWKT()

library(rgeos)
writeWKT(x)
# [1] "POLYGON ((1441727.5096940901130438 6550163.0046194596216083,
#                 1150685.2609429201111197 6669225.7427449300885201,
#                 975398.4520359700545669 6603079.7771196700632572,
#                 866257.6087542800232768 6401334.5819626096636057,
#                 1441727.5096940901130438 6550163.0046194596216083))"

This can then be inserted into your example like:

library(rgeos)
x <- readwkt("POLYGON ((1441727.5096940901130438 6550163.0046194596216083,
                        1150685.2609429201111197 6669225.7427449300885201,
                        975398.4520359700545669 6603079.7771196700632572,
                        866257.6087542800232768 6401334.5819626096636057,
                        1441727.5096940901130438 6550163.0046194596216083))")

Unfortunately, thus the attribute information (x@data) and CRS are lost. Thus, one must consider adding this information if needed by adding dput(x@data) to create a Spatial*DataFrame.


问:
JSON data cannot be accessed getting error 404 (TMDB)?
I want the poster of required movie from TMDB. I am not able to get JSON data from TMDB API. I have send the request but getting error 404 'The resource you requested could not be found'.
Link to access TMDB movie API : https://developers.themoviedb.org/3/movies/get-movie-images
Here is my code:

```<code><script type="text/javascript">
    var film = "speed";
    var api_key = 'my-api-key';
    var requestURL = "https://api.themoviedb.org/3/movie/images?api_key=" + api_key +"&language=en-US&callback=?";

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response; //request.response contains all our JSON data

        console.log(myjsondata);
    }
</script>
</code>```

The JSON data in my console should look like this:

But instead I am getting this in my console:error 404 This resource cannot be found.

答:
You need to include a movie_id value in the path part of the request URL, right? Like this:

```<code>var requestURL = "https://api.themoviedb.org/3/movie/"
  + movie_id + "/images?api_key=" + api_key +"&language=en-US&callback=?";
</code>```

At least in the documentation cited in the question that’s what’s shown:

GET /movie/{movie_id}/images

Path Parameters

```<code>movie_id : integer
</code>```

Example:

```<code>https://api.themoviedb.org/3/movie/{movie_id}/images?api_key=<<api_key>>
</code>```

For example, to get JSON-formatted data for the images for the movie with the ID 9340:

```<code>https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>
</code>```

You can confirm that works by testing with curl or whatever:

```<code>$ curl "https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>"

{
    "backdrops": [
        {
            "aspect_ratio": 1.777251184834123,
            "file_path": "/qKeyO9gXaaK0g87tvvqOPK1siwc.jpg",
            "height": 1688,
            "iso_639_1": null,
            "vote_average": 5.454545454545455,
            "vote_count": 3,
            "width": 3000
        },
        …
</code>```

Body:
I want the poster of required movie from TMDB. I am not able to get JSON data from TMDB API. I have send the request but getting error 404 'The resource you requested could not be found'.
Link to access TMDB movie API : https://developers.themoviedb.org/3/movies/get-movie-images
Here is my code:

The JSON data in my console should look like this:

But instead I am getting this in my console:error 404 This resource cannot be found.

Body:
You need to include a movie_id value in the path part of the request URL, right? Like this:

var requestURL = "https://api.themoviedb.org/3/movie/"
  + movie_id + "/images?api_key=" + api_key +"&language=en-US&callback=?";

At least in the documentation cited in the question that’s what’s shown:

GET /movie/{movie_id}/images

Path Parameters

movie_id : integer

Example:

https://api.themoviedb.org/3/movie/{movie_id}/images?api_key=<<api_key>>

For example, to get JSON-formatted data for the images for the movie with the ID 9340:

https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>

You can confirm that works by testing with curl or whatever:

$ curl "https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>"

{
    "backdrops": [
        {
            "aspect_ratio": 1.777251184834123,
            "file_path": "/qKeyO9gXaaK0g87tvvqOPK1siwc.jpg",
            "height": 1688,
            "iso_639_1": null,
            "vote_average": 5.454545454545455,
            "vote_count": 3,
            "width": 3000
        },
        …


问:
Use TO_CHAR function to display the Fiscal Year
Is there a way in ORACLE that can display the Fiscal Year?

For example, I can write this query in SQL SERVER to pull the FYs but don't know how to write it in ORACLE.

```<code>SELECT
DATEPART(yyyy, DATEADD(mm, 3, DATE)) AS FY
FROM MYTABLE
</code>```

Output:

```<code>FY
----
2009
2010
2011
</code>```

What can I try to resolve this?

答:
The Oracle equivalent of your query would be something like this:</p>

```<code>SELECT EXTRACT(YEAR FROM ADD_MONTHS(MYDATE, 3)) AS FY
FROM MYTABLE
</code>```

Body:
Is there a way in ORACLE that can display the Fiscal Year?

For example, I can write this query in SQL SERVER to pull the FYs but don't know how to write it in ORACLE.

SELECT
DATEPART(yyyy, DATEADD(mm, 3, DATE)) AS FY
FROM MYTABLE

Output:

FY
----
2009
2010
2011

What can I try to resolve this?

Body:
The Oracle equivalent of your query would be something like this:

SELECT EXTRACT(YEAR FROM ADD_MONTHS(MYDATE, 3)) AS FY
FROM MYTABLE


问:
how to insert numeric(10,6) datatype column value in to numeric(8,6) datatype column
I have a table TABLEA with COL1 NUMERIC(8,6) and need to insert a value from second table TABLEB which contains a value 123.000000.I have tried below scenarios.In this case i have to use NVL function and CAST together

```<code>SELECT CAST(899.000000 AS NUMERIC(8,6))-- This gives Numeric overflow.  Value does not fit in a numeric(8,6)
</code>```

Tried below as well

```<code>CAST(NVL(COL1,0) AS NUMERIC(10,6)) -- ERROR:  0 : Numeric value out of range
</code>```

Any insights would be helpful.
Thanks in advance.

答:
```<code>NUMERIC(p,s)  | Exact numerical, precision p, scale s
</code>```

In your query precision value is 8 that's why getting over flow error.Actual Precision value is 9.

```<code>SELECT CAST(899.000000 AS NUMERIC(8,6)
</code>```

I have update your query which is below .

```<code>SELECT CAST(899.000000 AS NUMERIC(9,6))
</code>```

Body:
I have a table TABLEA with COL1 NUMERIC(8,6) and need to insert a value from second table TABLEB which contains a value 123.000000.I have tried below scenarios.In this case i have to use NVL function and CAST together

SELECT CAST(899.000000 AS NUMERIC(8,6))-- This gives Numeric overflow.  Value does not fit in a numeric(8,6)

Tried below as well

CAST(NVL(COL1,0) AS NUMERIC(10,6)) -- ERROR:  0 : Numeric value out of range

Any insights would be helpful.
Thanks in advance.

Body:
NUMERIC(p,s)  | Exact numerical, precision p, scale s

In your query precision value is 8 that's why getting over flow error.Actual Precision value is 9.

SELECT CAST(899.000000 AS NUMERIC(8,6)

I have update your query which is below .

SELECT CAST(899.000000 AS NUMERIC(9,6))


问:
Unable to call function assigned to a variable in python
I have the following code in which the function is not being called and an error is being returned. Following is the code -

```<code>def deleteExistingBackupFiles(step):
    try:
        for setting in step.Setting:
            key = setting['key']
            value = setting['value']
            configTable.update({key: value})
            if os.path.isfile(value):
                os.remove(value)
            elif os.path.isdir(value):
                shutil.rmtree(value)
    except:
        report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

def main():
    scriptPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    configFilePath = os.path.abspath(os.path.realpath(scriptPath + '\config.xml'))
    parsedXML = ET.parse(configFilePath)

    #try:
    for step in parsedXML.iter('Step'):
        for setting in step.iter('Setting'):
            print setting.attrib.get('key')
            print setting.attrib.get('value')
            configTable.update({setting.attrib.get('key'): setting.attrib.get('value')})

    for step in tqdm(parsedXML.iter('Step'), desc='Wordpress Backup Restoration : '):
        methodName = step.attrib.get('methodname')
        result = methodName
        result(step)
</code>```

While trying to execute the last statement, I am getting the following error -

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1585, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 119, in <module>
    main()
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 106, in main
    result(step)
TypeError: 'str' object is not callable
</code>```

The methodName contains DeleteExistingBackupFiles yet it is still not working. Any idea what is going wrong?

Although when I try to execute the following code, it works fine -

```<code>def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

result = (sampleFunc)

result("Hello World!")
</code>```

Have a nice day!

答: You cannot call result because result is the name of the function, rather than the function itself. You could try evaluating the string to get the function (e.g. function = eval(result), function(step)) but that's kind of dubious. Instead, consider making a dictionary mapping function names to functions.

Body:
I have the following code in which the function is not being called and an error is being returned. Following is the code -

def deleteExistingBackupFiles(step):
    try:
        for setting in step.Setting:
            key = setting['key']
            value = setting['value']
            configTable.update({key: value})
            if os.path.isfile(value):
                os.remove(value)
            elif os.path.isdir(value):
                shutil.rmtree(value)
    except:
        report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

def main():
    scriptPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    configFilePath = os.path.abspath(os.path.realpath(scriptPath + '\config.xml'))
    parsedXML = ET.parse(configFilePath)

    #try:
    for step in parsedXML.iter('Step'):
        for setting in step.iter('Setting'):
            print setting.attrib.get('key')
            print setting.attrib.get('value')
            configTable.update({setting.attrib.get('key'): setting.attrib.get('value')})

    for step in tqdm(parsedXML.iter('Step'), desc='Wordpress Backup Restoration : '):
        methodName = step.attrib.get('methodname')
        result = methodName
        result(step)

While trying to execute the last statement, I am getting the following error -

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1585, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 119, in <module>
    main()
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 106, in main
    result(step)
TypeError: 'str' object is not callable

The methodName contains DeleteExistingBackupFiles yet it is still not working. Any idea what is going wrong?

Although when I try to execute the following code, it works fine -

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

result = (sampleFunc)

result("Hello World!")

Have a nice day!


问:
Query to find the FIRST AND SECOND largest value from a group
i have a query like this:

```<code>SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
</code>```

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

答:
RANK() is maybe the thing you are looking for...

http://msdn.microsoft.com/en-us/library/ms176102.aspx

Body:
i have a query like this:

SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)


问:
.htaccess do not rewrite if URI includes "admin"
What kind of rule do I need if I do not want redirect in the administrative panel on site.ru/admin? </p>

```<code>RewriteCond %{HTTP_HOST} ^(www\.)?(dev\.)?(site\.ru)$ [NC]
RewriteRule ^(.*)$ http://%2msk\.site\.ru/$1 [R=301,L]
</code>```

答:
Try with below condition above your rule,</p>

```<code>RewriteCond %{REQUEST_URI} !^/admin
</code>```

Body:
What kind of rule do I need if I do not want redirect in the administrative panel on site.ru/admin?

RewriteCond %{HTTP_HOST} ^(www\.)?(dev\.)?(site\.ru)$ [NC]
RewriteRule ^(.*)$ http://%2msk\.site\.ru/$1 [R=301,L]

Body:
Try with below condition above your rule,

RewriteCond %{REQUEST_URI} !^/admin


问:
code before app.run() can not be run in gunicorn+flask
```<code>#main.py
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    print("before app run")
    app.run()  # , threaded=True host='0.0.0.0', debug=True, port=5000
</code>```

Run gunicorn as follow:

```<code>gunicorn -b 0.0.0.0:8000 --preload main:app
</code>```

the result will not print “before app unn”. How can i run the print code? if i don't want to place print outside of if __name__ == '__main__'

答:
Gunicorn is not running the file, but importing it. That means that __name__ != "__main__" and your code never gets run.

Gunicorn then manually calls app.run() itself, after importing your file.

The solution is to make sure that your code is run at import time:

```<code>> cat main.py
from flask import Flask

app = Flask(__name__)

print "before main stanza"
if __name__ == "__main__":
    print "in main stanza"
    app.run()
</code>```

And then running the app:

```<code>> gunicorn -b 0.0.0.0:8000 --preload main:app
before main stanza
[2017-06-07 08:33:15 +0100] [8865] [INFO] Starting gunicorn 19.7.1
[2017-06-07 08:33:15 +0100] [8865] [INFO] Listening at: http://0.0.0.0:8000 (8865)
...
</code>```

Body:
#main.py
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    print("before app run")
    app.run()  # , threaded=True host='0.0.0.0', debug=True, port=5000

Run gunicorn as follow:

gunicorn -b 0.0.0.0:8000 --preload main:app

the result will not print “before app unn”. How can i run the print code? if i don't want to place print outside of if __name__ == '__main__'

Body:
Gunicorn is not running the file, but importing it. That means that __name__ != "__main__" and your code never gets run.

Gunicorn then manually calls app.run() itself, after importing your file.

The solution is to make sure that your code is run at import time:

> cat main.py
from flask import Flask

app = Flask(__name__)

print "before main stanza"
if __name__ == "__main__":
    print "in main stanza"
    app.run()

And then running the app:

> gunicorn -b 0.0.0.0:8000 --preload main:app
before main stanza
[2017-06-07 08:33:15 +0100] [8865] [INFO] Starting gunicorn 19.7.1
[2017-06-07 08:33:15 +0100] [8865] [INFO] Listening at: http://0.0.0.0:8000 (8865)
...


问:
Fetching data in form of radio button format for quiz game in PHP
I have stored data in database statically. Its having 5 col One for question and 4 col. for answers. Basically its a quiz game format. Now I want to fetch data from database in the form of radio button for that 4 col. How to implement that method. Currently i am fetching in normal text mode.

Here is the code

```<code> <?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<br>Question: " . $row["Question"]. "<br>";
    echo " A) " . $row["Answer1"]. "<br>";
    echo " B) " . $row["Answer2"]. "<br>";
    echo " C) " . $row["Answer3"]. "<br>";
    echo " D) " . $row["Answer4"]. "<br>";
}
} else {
 echo "0 results";
}
$conn->close();

?>
</code>```

答:
If I understand your question correctly, you simply want to make the answers into radio buttons. You can achieve this by doing this:</p>

```<code>while($row = $result->fetch_assoc()) {
    echo "<br>Question: " . $row["Question"]. "<br>";
    echo ' A) <input type="radio" value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
    echo ' B) <input type="radio" value="'.$row["Answer2"].'">'.$row["Answer2"].'<br>';
    echo ' C) <input type="radio" value="'.$row["Answer3"].'">'.$row["Answer3"].'<br>';
    echo ' D) <input type="radio" value="'.$row["Answer4"].'">'.$row["Answer4"].'<br>';
}
</code>```

Body:
I have stored data in database statically. Its having 5 col One for question and 4 col. for answers. Basically its a quiz game format. Now I want to fetch data from database in the form of radio button for that 4 col. How to implement that method. Currently i am fetching in normal text mode.

Here is the code

 <?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully

";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "
Question: " . $row["Question"]. "
";
    echo " A) " . $row["Answer1"]. "
";
    echo " B) " . $row["Answer2"]. "
";
    echo " C) " . $row["Answer3"]. "
";
    echo " D) " . $row["Answer4"]. "
";
}
} else {
 echo "0 results";
}
$conn->close();

?>

Body:
If I understand your question correctly, you simply want to make the answers into radio buttons. You can achieve this by doing this:

while($row = $result->fetch_assoc()) {
    echo "<br>Question: " . $row["Question"]. "<br>";
    echo ' A) <input type="radio" value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
    echo ' B) <input type="radio" value="'.$row["Answer2"].'">'.$row["Answer2"].'<br>';
    echo ' C) <input type="radio" value="'.$row["Answer3"].'">'.$row["Answer3"].'<br>';
    echo ' D) <input type="radio" value="'.$row["Answer4"].'">'.$row["Answer4"].'<br>';
}


问:
How to resolve service for type 'IdentityServer4.EntityFramework.Options.OperationalStoreOptions'
I created a aspnet core web application and installed IdentityServer4 and IdentityServer4.EntityFramework packages to use database storage for Client and Resources configuration instead of inMemory. However when I add the ConfigurationDbContext and PersistedGrantDbContext in the services collection as shown in the image below
I get an exception saying "Unable to resolve service for type 'IdentityServer4.EntityFramework.Options.OperationalStoreOptions' while attempting to activate 'IdentityServer4.EntityFramework.DbContexts.PersistedGrantDbContext'."
as seen in the commandline screenshot below

How do I fix the exception being thrown

答:
How to solve this issue

Firstly I removed the DbContexts that I was adding manually which is from line 49 to 53, in the first screenshot.
Secondly I made a mistake when adding the .AddSigningCredentials() loading the certificate I am supposed to use the IHostingEnvironment to get the ContentRootPath to my certificate. Therefore change .AddSigningCredentials(..) to:

```<code>.AddSigningCredential(new X509Certificate2(Path.Combine(_environment.ContentRootPath,
                "sample-cert.pfx"), "password")
</code>```

Add thats how I solved the exception being thrown and processed the migrations I wanted to.

Body:
How to solve this issue

Firstly I removed the DbContexts that I was adding manually which is from line 49 to 53, in the first screenshot.
Secondly I made a mistake when adding the .AddSigningCredentials() loading the certificate I am supposed to use the IHostingEnvironment to get the ContentRootPath to my certificate. Therefore change .AddSigningCredentials(..) to:

.AddSigningCredential(new X509Certificate2(Path.Combine(_environment.ContentRootPath,
                "sample-cert.pfx"), "password")

Add thats how I solved the exception being thrown and processed the migrations I wanted to.


问:
Is it possible now to record screen on iOS 11?
Today I saw some videos that apple gave the option to record screen in control center.

I am curious if it is also available for developers or not?

I googled but didn't found any doc related to this. Can someone put some light on this topic.

答:
App Screen Sharing:

As per the new update in API docs you can capture Video & Audio of the screen through your app only.

RPScreenRecorder : The shared recorder object providing the ability to record audio and video of your app.

By this class, you can record your app screen and also bind audio through the iPhone microphone.

Below are some methods that you can use to record the screen with different options.

To Accessing the Shared Recorder:

```<code>class func shared()
</code>```

To Controlling App Recording:

```<code>-- Starts recording the app display.
func startRecording(handler: ((Error?) -> Void)? = nil)

-- Stops the current recording.
func stopRecording(handler: ((RPPreviewViewController?, Error?) -> Void)? = nil)

-- Starts screen and audio capture.
func startCapture(handler: ((CMSampleBuffer, RPSampleBufferType, Error?) -> Void)?, completionHandler: ((Error?) -> Void)? = nil)

-- Stops screen capture
func stopCapture(handler: ((Error?) -> Void)? = nil)
</code>```

Hope this will helps you to capture the screen in your app.

Ref Link: https://developer.apple.com/documentation/replaykit/rpscreenrecorder

Doc Ref: https://developer.apple.com/library/content/releasenotes/General/WhatsNewIniOS/Articles/iOS_11_0.html

Late Post but may be useful for those who are still searching related to this
question.

iPhone Screen Sharing:

I have done some R&D on the sharing screen and come up with the below updates.

WWDC 2017 Session 606

Covering all details that we actually want to share/broadcast or capture our iOS device screen with audio & videos.

Apple Introduce ReplyKit2 for screen capturing & sharing.

Code For Broadcasting:

1. Create Object of RPScreenRecorder:

```<code>`let broadCastController = RPBroadcastController()`

`let recorder = RPScreenRecorder.shared()`
</code>```

2. Use startBroadcasting() method to start broadcasting:

```<code>    func startBroadcasting() {
            RPBroadcastActivityViewController.load { broadcastAVC, error in
                guard error == nil else {
                    print("Cannot load Broadcast Activity View Controller.")
                    return
                }

                if let broadcastAVC = broadcastAVC {
                    broadcastAVC.delegate = self
                    self.present(broadcastAVC, animated: true, completion: nil)
                }
            }
      }
</code>```

3. Use below activity Controller method to choose your app to broadcast.

```<code>func broadcastActivityViewController(_ broadcastActivityViewController: RPBroadcastActivityViewController,
                                         didFinishWith broadcastController: RPBroadcastController?,
                                         error: Error?) {
        guard error == nil else {
            print("Broadcast Activity Controller is not available.")
            return
        }

        broadcastActivityViewController.dismiss(animated: true) {
            broadcastController?.startBroadcast { error in
                //TODO: Broadcast might take a few seconds to load up. I recommend that you add an activity indicator or something similar to show the user that it is loading.
                if error == nil {
                    print("Broadcast started successfully!")
                    self.broadcastStarted()
                }
            }
        }
    }
</code>```

4. Use stopBroadcasting() method to Stop Broadcasting:

```<code>func stopBroadcasting() {
        broadCastController.finishBroadcast { error in
            if error == nil {
                print("Broadcast ended")
                self.broadcastEnded()
            }
        }
}
</code>```

Hope this latest update will help!

Will update more soon...

Body:
App Screen Sharing:

As per the new update in API docs you can capture Video & Audio of the screen through your app only.

RPScreenRecorder : The shared recorder object providing the ability to record audio and video of your app.

By this class, you can record your app screen and also bind audio through the iPhone microphone.

Below are some methods that you can use to record the screen with different options.

To Accessing the Shared Recorder:

class func shared()

To Controlling App Recording:

-- Starts recording the app display.
func startRecording(handler: ((Error?) -> Void)? = nil)

-- Stops the current recording.
func stopRecording(handler: ((RPPreviewViewController?, Error?) -> Void)? = nil)

-- Starts screen and audio capture.
func startCapture(handler: ((CMSampleBuffer, RPSampleBufferType, Error?) -> Void)?, completionHandler: ((Error?) -> Void)? = nil)

-- Stops screen capture
func stopCapture(handler: ((Error?) -> Void)? = nil)

Hope this will helps you to capture the screen in your app.

Ref Link: https://developer.apple.com/documentation/replaykit/rpscreenrecorder

Doc Ref: https://developer.apple.com/library/content/releasenotes/General/WhatsNewIniOS/Articles/iOS_11_0.html

Late Post but may be useful for those who are still searching related to this
question.

iPhone Screen Sharing:

I have done some R&D on the sharing screen and come up with the below updates.

WWDC 2017 Session 606

Covering all details that we actually want to share/broadcast or capture our iOS device screen with audio & videos.

Apple Introduce ReplyKit2 for screen capturing & sharing.

Code For Broadcasting:

1. Create Object of RPScreenRecorder:

`let broadCastController = RPBroadcastController()`

`let recorder = RPScreenRecorder.shared()`

2. Use startBroadcasting() method to start broadcasting:

    func startBroadcasting() {
            RPBroadcastActivityViewController.load { broadcastAVC, error in
                guard error == nil else {
                    print("Cannot load Broadcast Activity View Controller.")
                    return
                }

                if let broadcastAVC = broadcastAVC {
                    broadcastAVC.delegate = self
                    self.present(broadcastAVC, animated: true, completion: nil)
                }
            }
      }

3. Use below activity Controller method to choose your app to broadcast.

func broadcastActivityViewController(_ broadcastActivityViewController: RPBroadcastActivityViewController,
                                         didFinishWith broadcastController: RPBroadcastController?,
                                         error: Error?) {
        guard error == nil else {
            print("Broadcast Activity Controller is not available.")
            return
        }

        broadcastActivityViewController.dismiss(animated: true) {
            broadcastController?.startBroadcast { error in
                //TODO: Broadcast might take a few seconds to load up. I recommend that you add an activity indicator or something similar to show the user that it is loading.
                if error == nil {
                    print("Broadcast started successfully!")
                    self.broadcastStarted()
                }
            }
        }
    }

4. Use stopBroadcasting() method to Stop Broadcasting:

func stopBroadcasting() {
        broadCastController.finishBroadcast { error in
            if error == nil {
                print("Broadcast ended")
                self.broadcastEnded()
            }
        }
}

Hope this latest update will help!

Will update more soon...


问:
Maintain Unique Array In Mongo
Below code represent that 101 has initiated chat with 102.

```<code>db.chat.insert(
   {
     "mydate" : ISODate(),
     "chatusers" : [101,102]
   }
)
</code>```

To make sure this entry is unique and there should be no duplicate like
[101,102] or [102,101] is tried to add unique index in chatusers but this does not work on pairs as it dont allow to use either of 101 or 102.

Question:
One way is to make sure at application end or should i change my collection schema?
What is the better approach and please suggest schema for the same.

Note:
select Queries will be based on both sender and receiver.

答:
The array size contains just 2 elements sender and receiver. and the combination should be unique. Based on google i am not sure if array is right choice ?

Yes, array is not the right choice because 1) mongodb gives them special treatment and 2) semantically, two arrays with different order of elements are different arrays.

So, assuming that your array works well enough to satisfy your queries and whatnot, here's how you can ensure uniqueness of the combinations:

Make a synthethic derived field of properly indexable type. String, for example. So, for "chatusers" : [102,101], you take the chat users, sort them and concatenate, producing something like this:

```<code> "chatusers_sig": "101,102"
</code>```

Now you can build unique index on this field. Just don't forget to update it when chat users array changes (if it does).

Title: Maintain Unique Array In Mongo

Body:
Below code represent that 101 has initiated chat with 102.

db.chat.insert(
   {
     "mydate" : ISODate(),
     "chatusers" : [101,102]
   }
)

To make sure this entry is unique and there should be no duplicate like
[101,102] or [102,101] is tried to add unique index in chatusers but this does not work on pairs as it dont allow to use either of 101 or 102.

Question:
One way is to make sure at application end or should i change my collection schema?
What is the better approach and please suggest schema for the same.

Note:
select Queries will be based on both sender and receiver.

Body:
The array size contains just 2 elements sender and receiver. and the combination should be unique. Based on google i am not sure if array is right choice ?

Yes, array is not the right choice because 1) mongodb gives them special treatment and 2) semantically, two arrays with different order of elements are different arrays.

So, assuming that your array works well enough to satisfy your queries and whatnot, here's how you can ensure uniqueness of the combinations:

Make a synthethic derived field of properly indexable type. String, for example. So, for "chatusers" : [102,101], you take the chat users, sort them and concatenate, producing something like this:

 "chatusers_sig": "101,102"

Now you can build unique index on this field. Just don't forget to update it when chat users array changes (if it does).


问:
File upload validation get trigger on upload button click but not on Ok Button
I am validating File uploader using Jquery Validation like this:

HTML

```<code><form class="getintouch_form" name="Form_Career" action="" id="frm">
  <input type="file" id="fileInput" name="UploadResume" placeholder="Upload Resume">
  <button class="submitbtn bluebutton" id="BtnSend" type="button">Send</button>
</form>
</code>```

JQuery

```<code>$.validator.addMethod(
  "UploadResume",
  function(value, element) {
    return /\.(doc|docx|pdf)$/i.test(value);
  },
  "Only docx,doc,pdf file formats allow"
);
$("#frm").validate({
  onfocusout: function(element) {
    $(element).valid();
  },
  rules: {
    UploadResume: {
      required: true,
      UploadResume: true
    }
  },

  messages: {
    UploadResume: {
      required: "Resume is mandatory field."
    }
  },
});
</code>```

Issue

Validation gets fired immediately after I click Upload button and not after I click ok button after selecting file. I want to trigger validation only after I select the file. I've attached Codepen Link as well.

CodePen : https://codepen.io/Ruhard/pen/RgPeQP

答:
To create the behaviour you require, you can call valid() on the form under the change event of the input, which is fired after a file is selected. Try this:

```<code>$('#fileInput').change(function() {
  $('#frm').valid();
});
</code>```

Body:
I am validating File uploader using Jquery Validation like this:

HTML

<form class="getintouch_form" name="Form_Career" action="" id="frm">
  <input type="file" id="fileInput" name="UploadResume" placeholder="Upload Resume">
  <button class="submitbtn bluebutton" id="BtnSend" type="button">Send</button>
</form>

JQuery

$.validator.addMethod(
  "UploadResume",
  function(value, element) {
    return /\.(doc|docx|pdf)$/i.test(value);
  },
  "Only docx,doc,pdf file formats allow"
);
$("#frm").validate({
  onfocusout: function(element) {
    $(element).valid();
  },
  rules: {
    UploadResume: {
      required: true,
      UploadResume: true
    }
  },

  messages: {
    UploadResume: {
      required: "Resume is mandatory field."
    }
  },
});

Issue

Validation gets fired immediately after I click Upload button and not after I click ok button after selecting file. I want to trigger validation only after I select the file. I've attached Codepen Link as well.

CodePen : https://codepen.io/Ruhard/pen/RgPeQP

Body:
To create the behaviour you require, you can call valid() on the form under the change event of the input, which is fired after a file is selected. Try this:

$('#fileInput').change(function() {
  $('#frm').valid();
});


问:
Gitlab runner on kubernetes
I would like to use kubernetes for gitlab runner.

I have a gitlab instance on server 1 and kubernetes on server 2 (with gitlab runner) .
I installed kubernetes with kubeadm and flannel network pod.

When I launch the build, I can connect with kubernetes.
But, the job is not running.
I have this error:

```<code>Post https://<master_ip>:<master_port>/api/v1/namespaces/gitlab/pods: x509: certificate signed by unknown authority
</code>```

So I know it is a ssl issue.

Do I must create a ssl certificates?
And how and which argument?

Thanks for help

答:
have you tried making a service account on kubernetes and generate a bearer token? Not sure if gitlab works with tokens. If not you'll need the following:
The following options are provided, which allow you to connect to the Kubernetes API:

host: Optional Kubernetes apiserver host URL (auto-discovery attempted if not specified)

cert_file: Optional Kubernetes apiserver user auth certificate

key_file: Optional Kubernetes apiserver user auth private key

ca_file: Optional Kubernetes apiserver ca certificate

So in short, you'll have to generate a key-cert combo based on the ca that you kubernetes apiserver uses. The content of your combo can be the following (this is a raw json example config that I use for cfssl):{"CN":"worker","hosts":[],"key":{"algo":"rsa","size":2048},"names":[{"C":"US","L":"OV","OU":"Devops"}]}

Title: Gitlab runner on kubernetes

Body:
I would like to use kubernetes for gitlab runner.

I have a gitlab instance on server 1 and kubernetes on server 2 (with gitlab runner) .
I installed kubernetes with kubeadm and flannel network pod.

When I launch the build, I can connect with kubernetes.
But, the job is not running.
I have this error:

Post https://<master_ip>:<master_port>/api/v1/namespaces/gitlab/pods: x509: certificate signed by unknown authority

So I know it is a ssl issue.

Do I must create a ssl certificates?
And how and which argument?

Thanks for help


问:
How to group days in a week, like a calendar?
I have table that has a column of schedule, I would like to pivot on the Day_Name column so that the dates are displayed as columns like Monday, Tuesday etc.
this is my query:

```<code>SELECT
     Month_Name,Day_Name, Year, Week_Number, Day_Number
    , isnull((Select (CONVERT(varchar(5), empschedfrom, 108) + '-' + convert(varchar(5), empschedto, 108)) from empdayscheds where empno = '0030' and empday_no = DayNumber_of_Month and empday_month = Month_Number and empday_year = Year), 'OFF') as emp_sched
    from dtRule where DATE between '05/28/2017' and '07/08/2017'
</code>```

output:

```<code>   Month_Name | Day_Name | Year | Week_Number |Day_number| emp_sched
   May        |Sunday    | 2017 | 4           | 28       | 11:45-20:45
   May        | Tuesday  | 2017 | 5           | 29       | 14:15-23:15
   May        | Wednesday| 2017 | 5           | 30       | 13:45-22:45
   June       | Thursday | 2017 | 1           |  1       |10:00-19:00
   June       | Friday   | 2017 | 1           |  2       |10:00-19:00
   June       | Saturday | 2017 | 1           |  3       |10:00-19:00
</code>```

I would like it to come out like this:

```<code>Week_Number | Month_Name | Year | Monday | Tuesday | Wednesday | Thursday  | Friday    | Saturday
1           | June       | 2017 |        |         |           |10:00-19:00|10:00-19:00|10:00-19:00
</code>```

答:
```<code>If OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp
 ;With cte( Month_Name , Day_Name , Year , Week_Number ,Day_number, emp_sched )
 AS
 (
 SELECT 'May' ,  'Sunday'  , 2017 , 4  , 28, '11:45-20:45' Union all
 SELECT 'May' , 'Tuesday'  , 2017 , 5  , 29, '14:15-23:15' Union all
 SELECT 'May' , 'Wednesday', 2017 , 5  , 30, '13:45-22:45' Union all
 SELECT 'June', 'Thursday' , 2017 , 1  ,  1,'10:00-19:00'  Union all
 SELECT 'June', 'Friday'   , 2017 , 1  ,  2,'10:00-19:00'  Union all
 SELECT 'June', 'Saturday' , 2017 , 1  ,  3,'10:00-19:00'
 )
 SELECT * INTo #Temp from cte

 Declare
         @Sql nvarchar(max),
         @dynamicCol nvarchar(max),@dynamicCol2 nvarchar(max)

Declare @DynamicColumn Table (ID Int IDentity, WeekName varchar(20))
INsert Into @DynamicColumn(WeekName)
SELECT 'Monday'   Union all
SELECT 'Tuesday'  Union all
SELECT 'Wednesday'Union all
SELECT 'Thursday' Union all
SELECT 'Friday'   Union all
SELECT 'Saturday' Union all
SELECT 'Sunday'

SELECT @dynamicCol=STUFF((SELECT ', ' +WeekName FROM  @DynamicColumn
FOR XML PATH('')),1,1,'')

--SELECT @dynamicCol

SELECT @dynamicCol2=STUFF((SELECT ', ' + 'MAX('+ WeekName +')' +' Over(Order by Week_Number Asc ) AS '
+ WeekName  FROM  @DynamicColumn
FOR XML PATH('')),1,1,'')

--SELECT @dynamicCol2

SET @Sql='
SELECT Top 1 Week_Number,Month_Name,[Year], '+ @dynamicCol2 +' From
(
SELECT Month_Name,Day_Name,[Year],Week_Number,Day_number,[emp_sched] From
#temp
)AS Src
PIVOT
(
MAX([emp_sched]) For [Day_Name ] IN ('+@dynamicCol+')
)
AS Pvt
'

PRINT @Sql

EXEC(@Sql)
</code>```

OutPut

```<code>Week_Number Month_Name  Year    Monday  Tuesday Wednesday   Thursday        Friday          Saturday        Sunday
---------------------------------------------------------------------------------------------------------------------
1           June        2017    NULL    NULL    NULL        10:00-19:00     10:00-19:00     10:00-19:00     NULL
</code>```

Body:
I have table that has a column of schedule, I would like to pivot on the Day_Name column so that the dates are displayed as columns like Monday, Tuesday etc.
this is my query:

SELECT
     Month_Name,Day_Name, Year, Week_Number, Day_Number
    , isnull((Select (CONVERT(varchar(5), empschedfrom, 108) + '-' + convert(varchar(5), empschedto, 108)) from empdayscheds where empno = '0030' and empday_no = DayNumber_of_Month and empday_month = Month_Number and empday_year = Year), 'OFF') as emp_sched
    from dtRule where DATE between '05/28/2017' and '07/08/2017'

output:

   Month_Name | Day_Name | Year | Week_Number |Day_number| emp_sched
   May        |Sunday    | 2017 | 4           | 28       | 11:45-20:45
   May        | Tuesday  | 2017 | 5           | 29       | 14:15-23:15
   May        | Wednesday| 2017 | 5           | 30       | 13:45-22:45
   June       | Thursday | 2017 | 1           |  1       |10:00-19:00
   June       | Friday   | 2017 | 1           |  2       |10:00-19:00
   June       | Saturday | 2017 | 1           |  3       |10:00-19:00

I would like it to come out like this:

Week_Number | Month_Name | Year | Monday | Tuesday | Wednesday | Thursday  | Friday    | Saturday
1           | June       | 2017 |        |         |           |10:00-19:00|10:00-19:00|10:00-19:00

Body:
If OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp
 ;With cte( Month_Name , Day_Name , Year , Week_Number ,Day_number, emp_sched )
 AS
 (
 SELECT 'May' ,  'Sunday'  , 2017 , 4  , 28, '11:45-20:45' Union all
 SELECT 'May' , 'Tuesday'  , 2017 , 5  , 29, '14:15-23:15' Union all
 SELECT 'May' , 'Wednesday', 2017 , 5  , 30, '13:45-22:45' Union all
 SELECT 'June', 'Thursday' , 2017 , 1  ,  1,'10:00-19:00'  Union all
 SELECT 'June', 'Friday'   , 2017 , 1  ,  2,'10:00-19:00'  Union all
 SELECT 'June', 'Saturday' , 2017 , 1  ,  3,'10:00-19:00'
 )
 SELECT * INTo #Temp from cte

 Declare
         @Sql nvarchar(max),
         @dynamicCol nvarchar(max),@dynamicCol2 nvarchar(max)

Declare @DynamicColumn Table (ID Int IDentity, WeekName varchar(20))
INsert Into @DynamicColumn(WeekName)
SELECT 'Monday'   Union all
SELECT 'Tuesday'  Union all
SELECT 'Wednesday'Union all
SELECT 'Thursday' Union all
SELECT 'Friday'   Union all
SELECT 'Saturday' Union all
SELECT 'Sunday'

SELECT @dynamicCol=STUFF((SELECT ', ' +WeekName FROM  @DynamicColumn
FOR XML PATH('')),1,1,'')

--SELECT @dynamicCol

SELECT @dynamicCol2=STUFF((SELECT ', ' + 'MAX('+ WeekName +')' +' Over(Order by Week_Number Asc ) AS '
+ WeekName  FROM  @DynamicColumn
FOR XML PATH('')),1,1,'')

--SELECT @dynamicCol2

SET @Sql='
SELECT Top 1 Week_Number,Month_Name,[Year], '+ @dynamicCol2 +' From
(
SELECT Month_Name,Day_Name,[Year],Week_Number,Day_number,[emp_sched] From
#temp
)AS Src
PIVOT
(
MAX([emp_sched]) For [Day_Name ] IN ('+@dynamicCol+')
)
AS Pvt
'

PRINT @Sql

EXEC(@Sql)

OutPut

Week_Number Month_Name  Year    Monday  Tuesday Wednesday   Thursday        Friday          Saturday        Sunday
---------------------------------------------------------------------------------------------------------------------
1           June        2017    NULL    NULL    NULL        10:00-19:00     10:00-19:00     10:00-19:00     NULL


问:
insert into an array if value is not found
I have an array built like this:

```<code>test[0].age = "15-24"; test[0].value= "5";

test[1].age = "45-54"; test[1].value= "10";
</code>```

etc

I have another array built like this:

```<code>ageRange[0] = "1-14";

ageRange[1] = "15-24";
</code>```

etc

The ageRange has all age ranges - and the test array only has some of them.

I want to rebuild the test array to include all ages of the ageRange array and if they aren't already in the array, assign them a value of 0. What is the best way of doing this? Also - they need to be sequentially added.

答:
You could iterate the array with the new ranges and iterate the test array while checking the left part. If the left part is not equal, then insert a new object to the test array at the actual position.

var test = [{ age: "15-24", value: "5" }, { age: "45-54", value: "10" }],
    ageRange = ["1-14", "15-24"],
    i = 0;

ageRange.forEach(function (a) {
    function getLeft(s) { return +s.split('-')[0]; }

    var left = getLeft(a);
    while (getLeft(test[i].age) < left) {
        i++;
    }
    getLeft(test[i].age) === left || test.splice(i, 0, { age: a, value: '0' });
});

console.log(test);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array built like this:

test[0].age = "15-24"; test[0].value= "5";

test[1].age = "45-54"; test[1].value= "10";

etc

I have another array built like this:

ageRange[0] = "1-14";

ageRange[1] = "15-24";

etc

The ageRange has all age ranges - and the test array only has some of them.

I want to rebuild the test array to include all ages of the ageRange array and if they aren't already in the array, assign them a value of 0. What is the best way of doing this? Also - they need to be sequentially added.

Body:
You could iterate the array with the new ranges and iterate the test array while checking the left part. If the left part is not equal, then insert a new object to the test array at the actual position.

var test = [{ age: "15-24", value: "5" }, { age: "45-54", value: "10" }],
    ageRange = ["1-14", "15-24"],
    i = 0;

ageRange.forEach(function (a) {
    function getLeft(s) { return +s.split('-')[0]; }

    var left = getLeft(a);
    while (getLeft(test[i].age) < left) {
        i++;
    }
    getLeft(test[i].age) === left || test.splice(i, 0, { age: a, value: '0' });
});

console.log(test);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Callback function with return type
Method "DataOperation" has to return the value in DataResponse type.

I have a callback function inside my async request-reply "LoadDataReply" in which i am applying some business logic on the reply received and returning to main method (I am not sure about return to callback is a right way or not).

Can you guys help me on how to return the value for the caller of LoadData method.

```<code>DataResponse DataOperation::LoadData(const RequestType request)
{
DataResponse dataResponse;
messageAssistant.AsyncRequest("LoadDataList", request)
    .OnReply<MyResponseType>("LoadDataListReply", [this, &dataResponse](auto& reply) { dataResponse = this->LoadDataFromResponse(reply); });

return dataResponse;
}

DataResponse DataOperation::LoadDataFromResponse(const MyResponseType& reply)
{
   ///Doing some operation with reply data
   DataResponse dataResponse;
   dataResponse.Data = reply.Data();
   return dataResponse;
}
</code>```

The above code is not compiling.

I am getting compilation error,

```<code>error C4716: 'DataOperation::LoadData': must return a value
</code>```

NOTE:- I have updated my code and is compiling without any issues. But dataResponse object which I am returning from LoadData at end is not having the values updated in LoadDataFromResponse. it has the initial values.

How i can make sure it returns the updated value rather than initial values?

答: This has been fixed by using callback.</p>

Title: Callback function with return type

Body:
Method "DataOperation" has to return the value in DataResponse type.

I have a callback function inside my async request-reply "LoadDataReply" in which i am applying some business logic on the reply received and returning to main method (I am not sure about return to callback is a right way or not).

Can you guys help me on how to return the value for the caller of LoadData method.

DataResponse DataOperation::LoadData(const RequestType request)
{
DataResponse dataResponse;
messageAssistant.AsyncRequest("LoadDataList", request)
    .OnReply<MyResponseType>("LoadDataListReply", [this, &dataResponse](auto& reply) { dataResponse = this->LoadDataFromResponse(reply); });

return dataResponse;
}

DataResponse DataOperation::LoadDataFromResponse(const MyResponseType& reply)
{
   ///Doing some operation with reply data
   DataResponse dataResponse;
   dataResponse.Data = reply.Data();
   return dataResponse;
}

The above code is not compiling.

I am getting compilation error,

error C4716: 'DataOperation::LoadData': must return a value

NOTE:- I have updated my code and is compiling without any issues. But dataResponse object which I am returning from LoadData at end is not having the values updated in LoadDataFromResponse. it has the initial values.

How i can make sure it returns the updated value rather than initial values?

Body: This has been fixed by using callback.


答:
if i understood your question correctly.

and if your database field contain html code for radio button then u need to:

Use htmlspecialchars_decode

and stripslashes

Replace the following line..

```<code> echo " A) " . $row["Answer1"]."<br>";
</code>```

With

```<code>echo htmlspecialchars_decode(stripslashes($row["Answer1"]));
</code>```

else use simple php code to show front end

```<code><input type='radio' name="ans" value="1" > <?php echo $row["Answer1"]; ?>
<input type='radio' name="ans" value="2" > <?php echo $row["Answer2"]; ?>

<input type='radio' name="ans" value="3" > <?php echo $row["Answer3"]; ?>
<input type='radio' name="ans" value="4" > <?php echo $row["Answer4"]; ?>
</code>```

after that check value and validate ans on post

Title: Fetching data in form of radio button format for quiz game in PHP

Body:
if i understood your question correctly.

and if your database field contain html code for radio button then u need to:

Use htmlspecialchars_decode

and stripslashes

Replace the following line..

 echo " A) " . $row["Answer1"]."<br>";

With

echo htmlspecialchars_decode(stripslashes($row["Answer1"]));

else use simple php code to show front end

<input type='radio' name="ans" value="1" > <?php echo $row["Answer1"]; ?>
<input type='radio' name="ans" value="2" > <?php echo $row["Answer2"]; ?>

<input type='radio' name="ans" value="3" > <?php echo $row["Answer3"]; ?>
<input type='radio' name="ans" value="4" > <?php echo $row["Answer4"]; ?>

after that check value and validate ans on post


问:
RecyclewView with nested gridView adjust height
I'm trying to create this view:

It´s Rerecyclew with a Gridview for each item.
So when you press the plus item I've to add a new item to the Gridview and adjust the RecyclewView item height.

But i can't make it with a wrap_content and i don´t know why.

Activity Layout

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_scenes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</LinearLayout>
</code>```

RecyclewView Item

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView
        android:id="@+id/gv_scene_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:columnWidth="50dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eaeaea" />

</LinearLayout>
</code>```

GridView Item (just for example)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="@color/liloColorBlue">

</LinearLayout>
</code>```

Can you help me to get the example view?

Thank you.

答:
I found the solution creating my own gridview like this:</p>

```<code>public class ScenesGridView  extends GridView {

        public ScenesGridView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public ScenesGridView(Context context) {
            super(context);
        }

        public ScenesGridView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }

}
</code>```

Body:
I'm trying to create this view:

It´s Rerecyclew with a Gridview for each item.
So when you press the plus item I've to add a new item to the Gridview and adjust the RecyclewView item height.

But i can't make it with a wrap_content and i don´t know why.

Activity Layout

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_scenes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</LinearLayout>

RecyclewView Item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView
        android:id="@+id/gv_scene_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:columnWidth="50dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eaeaea" />

</LinearLayout>

GridView Item (just for example)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="@color/liloColorBlue">

</LinearLayout>

Can you help me to get the example view?

Thank you.

Body:
I found the solution creating my own gridview like this:

public class ScenesGridView  extends GridView {

        public ScenesGridView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public ScenesGridView(Context context) {
            super(context);
        }

        public ScenesGridView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }

}


问:
Values not displaying in Listbox from database using mvc5
in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..

Thanks & Regards

in Controller part :-

```<code>[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
    List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
    return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}
</code>```

In view Part:-

```<code> $(document).ready(function () {
      $('#FavouriteReports').change(function () {
          $.ajax({
              type: "POST",
              url: '@Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
              data: { Columns: $('#FavouriteReports').val() },
              datatype: "json",
              traditional: true,
              success: function (data) {

                  $('#SelectedFields').empty();
                  $.each(data, function (key, val) {
                      $('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
                  })

              }
          });
      });

@Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { @class = "form-control editable" })
</code>```

答:
Let me assume Your model class Report

```<code>   public class Report {

    public int ReportId { get; set; }
    public Name ReportName { get; set; }
   }
</code>```

Inside your ajax method

```<code>   if(data!=null) {
    $('#SelectedFields').empty();
     var dd = null ;
    $.each(data, function (key, val) {
       dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
        });
   //append to given id
    $('#SelectedFields').append(dd);
        }
</code>```

I hope this will help your, bind your dropdown list

Body:
in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..

Thanks & Regards

in Controller part :-

[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
    List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
    return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}

In view Part:-

 $(document).ready(function () {
      $('#FavouriteReports').change(function () {
          $.ajax({
              type: "POST",
              url: '@Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
              data: { Columns: $('#FavouriteReports').val() },
              datatype: "json",
              traditional: true,
              success: function (data) {

                  $('#SelectedFields').empty();
                  $.each(data, function (key, val) {
                      $('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
                  })

              }
          });
      });

@Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { @class = "form-control editable" })

Body:
Let me assume Your model class Report

   public class Report {

    public int ReportId { get; set; }
    public Name ReportName { get; set; }
   }

Inside your ajax method

   if(data!=null) {
    $('#SelectedFields').empty();
     var dd = null ;
    $.each(data, function (key, val) {
       dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
        });
   //append to given id
    $('#SelectedFields').append(dd);
        }

I hope this will help your, bind your dropdown list


问:
How to get AppRole for azure active directory user using Microsoft Graph API
I am using Microsoft Graph API to access group and group members of azure active directory. Is there any way to get AppRole for user with Microsoft Graph API, as
there is one example I found "How to check if an azure active directory user is already in an approle", but it uses Azure Active Directory Graph API

Is AppRole functionality available with Microssoft Graph or shall I switch to Microsoft.Azure.ActiveDirectory.GraphClient?

答:
I tried Get appRoleAssignment api in graph explorer with beta version:

```<code>GET /users/{id | userPrincipalName}/appRoleAssignments/{id}
</code>```

but got the Unsupported segment type error , seems microsoft graph api is not exposing appRoleAssignments on users entity .  You could query that using azure ad graph api instead .

Body:
I tried Get appRoleAssignment api in graph explorer with beta version:

GET /users/{id | userPrincipalName}/appRoleAssignments/{id}

but got the Unsupported segment type error , seems microsoft graph api is not exposing appRoleAssignments on users entity .  You could query that using azure ad graph api instead .


问:
Adding an Image as an icon in a scss file rails?
I'm relatively new to the front-end of rails (usually do back-end), and I'm very lost on adding images to a css file and in lieu my show.haml file.
Here is what I have:

scss file:

```<code>@charset "utf-8";
@import "common";
@import "base_grid";

// teacherSearchForm design ================================
#teacherSearchForm{
  position: relative;
  @include size(100%, 70px);
  margin: 10px 0; padding: 10px 0;
}

.search_option_flipIcon{
  @include size(50px, 50px);
  background: #ddd;
  float: left;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}

.search_option_flipIcon:before{
  color: #888;
  font-family: dripicons;
  font-size: 20px;
}

.tutorial:before{
  content: "\e00d";
}
.zip:before{
  @include size(50px,50px);
  display: block;
  background-image: url('assets/images/users/rsz_zipcode.jpg');
  background-position: 0 0;
  background-repeat: no-repeat;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}
</code>```

show.haml file:

```<code>#teacherSearchForm
  .search_option_flipIcon.prev.tutorial
  #navigation_menu
    #navigation_menu_window
      .search_option_item.fourN#tutorial
        .dripicons.tutorial.oneN
        .search_option_item_title.tenN 使い方ガイドを見る
      .search_option_item.fourN#zip
        .dripicons.zip.oneN
        .search_option_item_title.tenN
          .fiveN= text_field_tag 'zip1', '', :max => '999',  :placeholder => '012',  :id => 'addr_zip1', :class => 'zip_input'
          .twoN -
          .fiveN= text_field_tag 'zip2', '', :max => '9999', :placeholder => '3456', :id => 'addr_zip2', :class => 'zip_input'
      .search_option_item.fourN#option
        .dripicons.option.oneN
        .search_option_item_title.tenN 検索の条件を追加する
  .search_option_flipIcon.next.option

  #search_form
    = form_tag user_searches_path, :remote => true, :authenticity_token => true, :id => 'search_form' do
      = hidden_field_tag "mode", 't'
      = hidden_field_tag "zip1", '', :id => "hidden_zip1"
      = hidden_field_tag "zip2", '', :id => "hidden_zip2"
      #search_form_inner.full
        = render :partial => "user_searches/days"
        = render :partial => "user_searches/subjects"
        = render :partial => "user_searches/sex"
        %input.sixN.btn{:type => "button", :value => "キャンセル"}
        = submit_tag "検索", :class => 'sixN btn'
</code>```

Current result: As seen, the highlighted part has no image.

答:
You have to use the rails helpers. image_path in this case.

```<code>background-image: url(image_path('users/rsz_zipcode.jpg'));
</code>```

Body:
I'm relatively new to the front-end of rails (usually do back-end), and I'm very lost on adding images to a css file and in lieu my show.haml file.
Here is what I have:

scss file:

@charset "utf-8";
@import "common";
@import "base_grid";

// teacherSearchForm design ================================
#teacherSearchForm{
  position: relative;
  @include size(100%, 70px);
  margin: 10px 0; padding: 10px 0;
}

.search_option_flipIcon{
  @include size(50px, 50px);
  background: #ddd;
  float: left;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}

.search_option_flipIcon:before{
  color: #888;
  font-family: dripicons;
  font-size: 20px;
}

.tutorial:before{
  content: "\e00d";
}
.zip:before{
  @include size(50px,50px);
  display: block;
  background-image: url('assets/images/users/rsz_zipcode.jpg');
  background-position: 0 0;
  background-repeat: no-repeat;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}

show.haml file:

#teacherSearchForm
  .search_option_flipIcon.prev.tutorial
  #navigation_menu
    #navigation_menu_window
      .search_option_item.fourN#tutorial
        .dripicons.tutorial.oneN
        .search_option_item_title.tenN 使い方ガイドを見る
      .search_option_item.fourN#zip
        .dripicons.zip.oneN
        .search_option_item_title.tenN
          .fiveN= text_field_tag 'zip1', '', :max => '999',  :placeholder => '012',  :id => 'addr_zip1', :class => 'zip_input'
          .twoN -
          .fiveN= text_field_tag 'zip2', '', :max => '9999', :placeholder => '3456', :id => 'addr_zip2', :class => 'zip_input'
      .search_option_item.fourN#option
        .dripicons.option.oneN
        .search_option_item_title.tenN 検索の条件を追加する
  .search_option_flipIcon.next.option

  #search_form
    = form_tag user_searches_path, :remote => true, :authenticity_token => true, :id => 'search_form' do
      = hidden_field_tag "mode", 't'
      = hidden_field_tag "zip1", '', :id => "hidden_zip1"
      = hidden_field_tag "zip2", '', :id => "hidden_zip2"
      #search_form_inner.full
        = render :partial => "user_searches/days"
        = render :partial => "user_searches/subjects"
        = render :partial => "user_searches/sex"
        %input.sixN.btn{:type => "button", :value => "キャンセル"}
        = submit_tag "検索", :class => 'sixN btn'

Current result: As seen, the highlighted part has no image.

Body:
You have to use the rails helpers. image_path in this case.

background-image: url(image_path('users/rsz_zipcode.jpg'));


问:
Color insertion from the biggest value
So I'm working on the cohort analysis, creating a table from the database, and having a trouble when it comes to coloring. I'm not an expert at javascript, so I dont really know how to do it.

So for example, I have 10,2,6,4.

And then in the table, I wanted to give a coloring from the biggest value.

like

```<code>10 => Darkest Green
2 => Lightest Green
6 => Dark Green
4 => Light Green
</code>```

So if we sort it to make it easier,

```<code>10 => Darkest Green
6 => Dark Green
4 => Light Green
2 => Lightest Green
</code>```

Edit:
The 4 number above just a raw example, I'm doing a monthly cohort, which means I will have 12 number, and it will be random, and many months will also have 0, which means it will be white/super light green.

How can I do that? Thanks a lot, and sorry for my english

答:
you can create an array with high priority of colors to low. like:

$colors = array( "Darkest Green", "Dark Green", "Light Green", "Lightest Green" );

now you can use 'foreach' in php to assign that color. like:

```<code>$i = 0;
$new_result = array();

foreach( $cohort_result as $row ) {

    $new_result[ $row ] = $colors[ $i ];
    $i++;

}
</code>```

Regards.

Title: Color insertion from the biggest value

Body:
So I'm working on the cohort analysis, creating a table from the database, and having a trouble when it comes to coloring. I'm not an expert at javascript, so I dont really know how to do it.

So for example, I have 10,2,6,4.

And then in the table, I wanted to give a coloring from the biggest value.

like

10 => Darkest Green
2 => Lightest Green
6 => Dark Green
4 => Light Green

So if we sort it to make it easier,

10 => Darkest Green
6 => Dark Green
4 => Light Green
2 => Lightest Green

Edit:
The 4 number above just a raw example, I'm doing a monthly cohort, which means I will have 12 number, and it will be random, and many months will also have 0, which means it will be white/super light green.

How can I do that? Thanks a lot, and sorry for my english

Body:
you can create an array with high priority of colors to low. like:

$colors = array( "Darkest Green", "Dark Green", "Light Green", "Lightest Green" );

now you can use 'foreach' in php to assign that color. like:

$i = 0;
$new_result = array();

foreach( $cohort_result as $row ) {

    $new_result[ $row ] = $colors[ $i ];
    $i++;

}

Regards.


问:
Talend - Insert/Update versus table-file-table
I have been using insert/update to update or insert a table in mysql from sql server. The job is set up as a cronjob. The job runs every 8 hours. The number of records in the source table is around 400000. Every 8 hours around 100 records might get updated or inserted.

I run the job in such a away that at the source level, I only take the modified runs between the last run and the current run.

I have observed that just to update / insert 100 rows the time taken is 30 minutes.

However, another way was to dump all of the 400000 in a file and then truncate the destination table and insert all of those records all over again. This process is done at every job run

So, now may I know why does insert/update take so much time?

Thanks
Rathi

答:
As you said you run the job in such a away that at the source level, I only take the modified runs between the last run and the current run.

So just insert all these modified rows in a temp table

Take the min date modified date from temp table or use the same criteria which you use to extract only modified rows from source and delete all the rows from the destination table.

Then you can insert all the rows from temp to end table.

Let me know if you have any question.


问:
Why these two constructors become different, after I change its prototype
Say I defined a constructor like

function Person(name) {this.name = name},

and create a new object var p1 = new Person("Peter").

After that, I change the prototype of the constructor as Person.prototype = {species: "human"}, I found p1.species is undefined. However, if I create a new object like p2 = new Person("John"). p2.species is "human".

function Person(name) {this.name = name}

var p1 = new Person("Peter")

Person.prototype = {species: "human"}
console.log(p1.species)

var p2 = new Person("John")
console.log(p2.species)```

After further investigating, I found

p1.constructor === p2.constructor is false

p2.constructor === Person is false

I would like to ask, how these two objects' constructors become different. (especially why p1 does not have the prototype property species) Furthermore, how to explain point 2 above, while p2 is created using function Person. (If so, why p2 has the prototype property species)?

I tested these codes in Chrome console.

Thank you

答:
Don't overwrite the prototype, but add a single key instead:

function Person(name) {
    this.name = name;
}
var p1 = new Person("Peter");
Person.prototype.species = "human";
var p2 = new Person("John");
console.log(p1.species, p2.species);
console.log(p1 instanceof Person, p2 instanceof Person);```

Body:
Say I defined a constructor like

function Person(name) {this.name = name},

and create a new object var p1 = new Person("Peter").

After that, I change the prototype of the constructor as Person.prototype = {species: "human"}, I found p1.species is undefined. However, if I create a new object like p2 = new Person("John"). p2.species is "human".

function Person(name) {this.name = name}

var p1 = new Person("Peter")

Person.prototype = {species: "human"}
console.log(p1.species)

var p2 = new Person("John")
console.log(p2.species)

After further investigating, I found

p1.constructor === p2.constructor is false

p2.constructor === Person is false

I would like to ask, how these two objects' constructors become different. (especially why p1 does not have the prototype property species) Furthermore, how to explain point 2 above, while p2 is created using function Person. (If so, why p2 has the prototype property species)?

I tested these codes in Chrome console.

Thank you


问:
GIT 1.9 - remote: error: 'receive.denyCurrentBranch'
I have an error using Git 1.9.

When I try to "git push" I receive the following error:

```<code>remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
</code>```

So, my first step was to read a lot here in this forum and tried to find some results from google. Sadly all I found was not working in my case.

I am working on Linux x86 and installed Git 1.9.

I can "git clone" one repository from my server and work in it.

For example I "touch testfile" in it to create a new file. Now I will "git commit" this file.

After this step I "git push" it and then I get the error code.

I found in other article's that the problem is solved in git 2.3
And that it should be helpful to change the value from "receive.denyCurrentBranch" in the config file from the repository.
Helpful values should be: refuse, updateInstead and ignore

I tried all of them and the error will be always the same.

On Server the config value ist:

```<code>[receive]
        denyCurrentBranch = refuse
</code>```

and the "git branch"

```<code>*master
</code>```

On client the "git status" is:

```<code>On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
</code>```

So, the error will appear any time, I do not really know how to fix it yet.

How can I avoid that error message?

答:
The general best practice would be to create on your server a bare repo (git init --bare, or convert your existing repo to a bare one), clone it, add and commit new files and then push.

That push would not have the error message you describe.

Note that any feature (2.3 receive.denyCurrentBranch updateInstead, or 2.4 push-to-deploy) allowing to push to a non-bare repo are not present in a Git 1.9.

You should be able to install the latest Git 2.13 from the right ppa.

Body:
I have an error using Git 1.9.

When I try to "git push" I receive the following error:

remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.

So, my first step was to read a lot here in this forum and tried to find some results from google. Sadly all I found was not working in my case.

I am working on Linux x86 and installed Git 1.9.

I can "git clone" one repository from my server and work in it.

For example I "touch testfile" in it to create a new file. Now I will "git commit" this file.

After this step I "git push" it and then I get the error code.

I found in other article's that the problem is solved in git 2.3
And that it should be helpful to change the value from "receive.denyCurrentBranch" in the config file from the repository.
Helpful values should be: refuse, updateInstead and ignore

I tried all of them and the error will be always the same.

On Server the config value ist:

[receive]
        denyCurrentBranch = refuse

and the "git branch"

*master

On client the "git status" is:

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

So, the error will appear any time, I do not really know how to fix it yet.

How can I avoid that error message?