问:
Facebook Like Button error
The facebook 'like' button isn't working on my webpage when i upload it to the web. It works perfectly on my computer though. Any guesses as to why this is happening ?

http://savetheearth.99k.org/pledge.htm is the URL

答:
i think the problem is in the url you have provided. As i check in your page source the i frame has following code :

Where it should have been:

the problem was in your url:

src="http://www.facebook.com/plugins/like.php?href=earthsave.tk

Title: Facebook Like Button error

Body:
i think the problem is in the url you have provided. As i check in your page source the i frame has following code :

<iframe src="http://www.facebook.com/plugins/like.php?href=earthsave.tk&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>

Where it should have been:

<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fsavetheearth.99k.org%2Fpledge.htm&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>

the problem was in your url:

src="http://www.facebook.com/plugins/like.php?href=earthsave.tk


来源: stackexchange

问:
ng-repeat not populating table
I've populated a table with data from a JSON file, and then when the user clicks on an item in the table, a container and it's fields display below and it SHOULD be populated with that specific data, though it isn't.

The function select is invoked through list-patents.htm which contains the table with a list of patents. I have used the $rootScope object so the function is accessible from multiple controllers i.e. patentDetailsCtrl

Why isn't my table in patent-item.htm being populated with the ng-repeat directive?

```<code>var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);

$stateProvider
    .state("patents.list.item", {
        url: "/patent-item",
        templateUrl: "templates/patents/list/patent-item.htm",
        params: {
            id: null,
            appNo: null,
            clientRef: null,
            costToRenew: null,
            renewalDueDate: null,
            basketStatus: null,
            costBandEnd: null,
            nextStage: null
        },
        controller: "patentDetailsCtrl"
    })

app.run(function($rootScope) {
    $rootScope.select = function() {
        return $rootScope.patentItem = item;
    }
});

app.controller('patentDetailsCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.selectedPatent = $scope.patentItem;

    console.log($scope.selectedPatent);

}]);
</code>```

list-patents.htm

```<code><tbody>
    <tr ng-repeat="x in patents">
        <td ng-click="select(x)"><a ui-sref="patents.list.item({id: x.id, appNo: x.applicationNumber, clientRef: x.clientRef, costToRenew: x.costToRenew, renewalDueDate: x.renewalDueDate, basketStatus: x.basketStatus, costBandEnd: x.costBandEnd, nextStage: x.nextStage})">{{x.applicationNumber}}</a></td>
        <td ng-bind="x.clientRef"></td>
        <td ng-bind="x.costToRenew">$</td>
        <td ng-bind="x.renewalDueDate"></td>
        <td><button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button></td>
    </tr>
</tbody>
</code>```

patent-item.htm

```<code><table>
    <tbody>
        <thead>
            <tr>
                <td>applicationNumber</td>
                <td>clientRef</td>
                <td>costToRenew</td>
                <td>renewalDueDate</td>
                <td>basketStatus</td>
                <td>costBandEnd</td>
                <td>nextStage</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="x in selectedPatent">
                <td>{{x.applicationNumber}}</td>
                <td>{{x.clientRef}}</td>
                <td>{{x.costToRenew}}</td>
                <td>{{x.renewalDueDate}}</td>
                <td>{{x.basketStatus}}</td>
                <td>{{x.costBandEnd}}</td>
                <td>{{x.nextStage}}</td>
            </tr>
        </tbody>
    </table>
</tbody>
</code>```

答:
You need to correct below points:

your $rootScope.select() method doesn't accept data (select(x)) passed from your list-patents.htm, So put item as param.,
Like : $rootScope.select = function(item) {  \\ code

Sine you do ng-repeat on $rootScope.patentItem, then I guess you need to make it array, and push the passed data to it. (No need of return statement as well.)

So run block should be like  :

```<code>app.run(function($rootScope) {
 rootScope.patentItem = [];
 $rootScope.select = function(item) {
    $rootScope.patentItem.push(item);
 }
});
</code>```

See this Example Fiddle

ContentLicense: CC BY-SA 3.0

Title: ng-repeat not populating table

Body:
I've populated a table with data from a JSON file, and then when the user clicks on an item in the table, a container and it's fields display below and it SHOULD be populated with that specific data, though it isn't.

The function select is invoked through list-patents.htm which contains the table with a list of patents. I have used the $rootScope object so the function is accessible from multiple controllers i.e. patentDetailsCtrl

Why isn't my table in patent-item.htm being populated with the ng-repeat directive?

var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);

$stateProvider
    .state("patents.list.item", {
        url: "/patent-item",
        templateUrl: "templates/patents/list/patent-item.htm",
        params: {
            id: null,
            appNo: null,
            clientRef: null,
            costToRenew: null,
            renewalDueDate: null,
            basketStatus: null,
            costBandEnd: null,
            nextStage: null
        },
        controller: "patentDetailsCtrl"
    })

app.run(function($rootScope) {
    $rootScope.select = function() {
        return $rootScope.patentItem = item;
    }
});

app.controller('patentDetailsCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.selectedPatent = $scope.patentItem;

    console.log($scope.selectedPatent);

}]);

list-patents.htm

        {{x.applicationNumber}}

        $

        <button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button>

patent-item.htm

                applicationNumber
                clientRef
                costToRenew
                renewalDueDate
                basketStatus
                costBandEnd
                nextStage

                {{x.applicationNumber}}
                {{x.clientRef}}
                {{x.costToRenew}}
                {{x.renewalDueDate}}
                {{x.basketStatus}}
                {{x.costBandEnd}}
                {{x.nextStage}}

Body:
You need to correct below points:

your $rootScope.select() method doesn't accept data (select(x)) passed from your list-patents.htm, So put item as param.,
Like : $rootScope.select = function(item) {  \\ code

Sine you do ng-repeat on $rootScope.patentItem, then I guess you need to make it array, and push the passed data to it. (No need of return statement as well.)

So run block should be like  :

app.run(function($rootScope) {
 rootScope.patentItem = [];
 $rootScope.select = function(item) {
    $rootScope.patentItem.push(item);
 }
});

See this Example Fiddle


问:
How to convert a JSONArray to a JsArray?
My JsonArray looks like this  :

```<code>  JSONArray itemsJsonArray = new JSONArray();
  JSONObject jsobj = new JSONObject();

 jsobj.put("a", new JSONString("hi"));
 jsobj.put("b", new JSONString("hgjjh"));
 jsobj.put("c", new JSONNumber(149077));

 itemsJsonArray.set(0, jsobj);
</code>```

I need the equivalent data as a JsArray (package :com.google.gwt.core.client)  since the api that I need to use only accepts the JsArray.

I need to convert to specific JsArray and not any JsonObject and can't take the overhead of serializing my data.

What will be the structure of the equivalent JsArray to the above data structured as key : value ?

答:
Edited answer according to your comment:

After looking in the Javadoc of the package you mentioned, maybe try this:

```<code>JsArrayMixed jsArray = new JsArrayMixed();
for (int i = 0; i < jsonArray.length(); ++i){
   jsArray.push(jsonArray.get(i));
}
</code>```

Remember you need to parse your object in your jsonArray to JavaScriptObject.

Body:
My JsonArray looks like this  :

  JSONArray itemsJsonArray = new JSONArray();
  JSONObject jsobj = new JSONObject();

 jsobj.put("a", new JSONString("hi"));
 jsobj.put("b", new JSONString("hgjjh"));
 jsobj.put("c", new JSONNumber(149077));

 itemsJsonArray.set(0, jsobj);

I need the equivalent data as a JsArray (package :com.google.gwt.core.client)  since the api that I need to use only accepts the JsArray.

I need to convert to specific JsArray and not any JsonObject and can't take the overhead of serializing my data.

What will be the structure of the equivalent JsArray to the above data structured as key : value ?

Body:
Edited answer according to your comment:

After looking in the Javadoc of the package you mentioned, maybe try this:

JsArrayMixed jsArray = new JsArrayMixed();
for (int i = 0; i < jsonArray.length(); ++i){
   jsArray.push(jsonArray.get(i));
}

Remember you need to parse your object in your jsonArray to JavaScriptObject.


问:
yii2 unique validator only when field not empty
In Yii2 I have two fields in my Database: email and shopId

Email and shopId should be unique together

Email could also be empty (NULL) while shopId is always an integer

These are my rules in the Model:

```<code>[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],
</code>```

This is not working when I have two entries with e.g. email="NULL" and shopId="1".

How can I solve this?

答:
I used the when condition inside the rule</p>

```<code>[
    ['email', 'shopId'],
    'unique',
    'targetAttribute' => ['email', 'shopId'],
    'message' => 'Diese E-Mail Adresse ist bereits registriert!',
    'when' => function ($model) {
        return !empty($model->email);
    }
],
</code>```

Body:
In Yii2 I have two fields in my Database: email and shopId

Email and shopId should be unique together

Email could also be empty (NULL) while shopId is always an integer

These are my rules in the Model:

[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],

This is not working when I have two entries with e.g. email="NULL" and shopId="1".

How can I solve this?

Body:
I used the when condition inside the rule

[
    ['email', 'shopId'],
    'unique',
    'targetAttribute' => ['email', 'shopId'],
    'message' => 'Diese E-Mail Adresse ist bereits registriert!',
    'when' => function ($model) {
        return !empty($model->email);
    }
],


问:
Using Java Robots class to locate things on a screen
I was wondering if it was possible to locate files or programs with this class. I know that there are ways to use mouse coordinates or simple find an application and run it but that's not what I want to do.

And example to be more clear is: Let's say I have Google Chrome, Firefox and Safari on my desktop and I shuffle them around all over. How can I get my mouse to find the browser that I'm looking for without simply using a 'run application' command.

I hope that clarifies it! Thanks for your help =)

答: I'm doing something like that for web-crawling, and I can tell you that the tools on the post below will not work that simple. I'm using Selenium for other purposes but it will not work on images where you've got a canvas on the top of all the visible area. To achieve that, you should use the robot class, but previously you have to know the coordinates where you expect it to be. To use some sort of GUI automated testing tool you have to have the fields simply available to be selected. I don't think that you will find it easily on some webpage. Probably to achieve a working solution you'll have to do digital image processing, which is quite good and not that difficult. There are lots of Java libs to do that. Try OpenCV, I think it's JavaCV the lib name, it's a powerful one. </p>


问:
C# Entity Framework - Multiple Foreign Keys
I have a problem with Entity Framework 6 code first creating multiple foreign keys from my classes when it should only create one. Consider I have 2 classes -

```<code>public class Work
{
    public Work()
    {
        Document1 = new Collection<Document>();
        Document2 = new Collection<Document>();
        Document3 = new Collection<Document>();
    }
    [Key]
    public int WorkId { get; set; }
    public virtual ICollection<Document> Document1 { get; set; }
    public virtual ICollection<Document> Document2 { get; set; }
    public virtual ICollection<Document> Document3 { get; set; }
}

public class Document
{
    public int? WorkId { get; set; }
    [ForeignKey("WorkId")]
    public Work Work { get; set; }
}
</code>```

Now when I run the code first update-database command, in my documents table it creates 3 different foreign keys for the Work table WorkId, Work_Id1, Work_Id2, this should just be one foreign key instead of 3. I know there should be a simple annotation to fix this or a fluent mapping I need to add?

答: Your Work class has three collections of Document, so the Document class requires three keys to denote where it attaches. If I have an instance of Document whose WorkId is 4, where does that exist on the instance of Work with that ID? Does it belong in Document1, Document2, or Document3? With only one key, there is no way to determine this. Entity Framework knows this, and has created three keys to solve the problem.

Body:
I have a problem with Entity Framework 6 code first creating multiple foreign keys from my classes when it should only create one. Consider I have 2 classes -

public class Work
{
    public Work()
    {
        Document1 = new Collection<Document>();
        Document2 = new Collection<Document>();
        Document3 = new Collection<Document>();
    }
    [Key]
    public int WorkId { get; set; }
    public virtual ICollection<Document> Document1 { get; set; }
    public virtual ICollection<Document> Document2 { get; set; }
    public virtual ICollection<Document> Document3 { get; set; }
}

public class Document
{
    public int? WorkId { get; set; }
    [ForeignKey("WorkId")]
    public Work Work { get; set; }
}

Now when I run the code first update-database command, in my documents table it creates 3 different foreign keys for the Work table WorkId, Work_Id1, Work_Id2, this should just be one foreign key instead of 3. I know there should be a simple annotation to fix this or a fluent mapping I need to add?


问:
How to create a stylesheet dynamically and add that to a node
Currently JavaFX does not allow attaching a stylesheet to a node (or scene) that is not in the classpath. So, if a css file is not in the classpath already, it cannot be added to any node. The getStyleSheets().add() method will state 'WARNING Resource [your file] not found'. So is there any workaround to this limitation?</p>

答:
The idea is to create a temporary stlyesheet file, write the new style-class inside, add the style-sheet to the list of sheets of the node and add also the new style-class.

Here is a working example:

```<code>Button button = new Button("My Text");

button.setOnAction(e -> {

    try {
        // Create a new tempfile that will be removed as the application exits
        File tempStyleClass = File.createTempFile("AppXY_TempStyleClass", ".css");
        tempStyleClass.deleteOnExit();

        // Write the stlye-class inside
        try (PrintWriter printWriter = new PrintWriter(tempStyleClass)) {
            printWriter.println(".temp-style { -fx-text-fill: red; }");
        }

        // Add the style-sheet and the style-class to the node
        button.getStylesheets().add(tempStyleClass.toURI().toString());
        button.getStyleClass().add("temp-style");

    } catch (IOException e1) {
        e1.printStackTrace();
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The idea is to create a temporary stlyesheet file, write the new style-class inside, add the style-sheet to the list of sheets of the node and add also the new style-class.

Here is a working example:

Button button = new Button("My Text");

button.setOnAction(e -> {

    try {
        // Create a new tempfile that will be removed as the application exits
        File tempStyleClass = File.createTempFile("AppXY_TempStyleClass", ".css");
        tempStyleClass.deleteOnExit();

        // Write the stlye-class inside
        try (PrintWriter printWriter = new PrintWriter(tempStyleClass)) {
            printWriter.println(".temp-style { -fx-text-fill: red; }");
        }

        // Add the style-sheet and the style-class to the node
        button.getStylesheets().add(tempStyleClass.toURI().toString());
        button.getStyleClass().add("temp-style");

    } catch (IOException e1) {
        e1.printStackTrace();
    }
});


问:
Using sed to replace multiple lines in multiple files
I have thousands of html files in which there are two different pieces of  old google adsense code which needs to be replaced by new ones. The files are on a linux server.

the old code looks like:

```<code>  <script type="text/javascript"><!--
google_ad_client = "pub-xxx";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
//2007-06-09: Forum archive rectangle
google_ad_channel = "1013717472xx";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_text = "000000";
google_color_url = "000000";
//-->
</script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</code>```

I need to match this text "google_ad_channel = "1013717472xx"" within the code, replace the whole code with new one.

the new code is as follows:

```<code><script src="https://pagead2.googlesyndication.com/pub-config/r20160913/ca-pub-xxx.js"></script><script src="http://pagead2.googlesyndication.com/pub-config/r20160913/ca-pub-xxx.js"></script><script type="text/javascript"><!--
google_ad_client = "pub-xxx";
/* frm arch linkunit 200x90, created 5/30/08 */
google_ad_slot = "0112084554";
google_ad_width = 200;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</code>```

How can I use sed to do the replacement in all the html files on my server?

Thank you in advance!

答:
```<code>ls |xargs sed -i 's/google_ad_channel = "1013717472xx"/google_ad_channel = "new_code"/g'
</code>```

Body:
I have thousands of html files in which there are two different pieces of  old google adsense code which needs to be replaced by new ones. The files are on a linux server.

the old code looks like:

I need to match this text "google_ad_channel = "1013717472xx"" within the code, replace the whole code with new one.

the new code is as follows:

How can I use sed to do the replacement in all the html files on my server?

Thank you in advance!


问:
not getting proper base_url in codeigniter app
i am getting this type of url when trying to access pages other than index page

```<code>http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home
</code>```

but url to access page must be

```<code>http://localhost:8012/health-care/index.php/home
</code>```

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

答: .htaccess file was not working. just replaced file and my problem got solved.</p>

Body:
i am getting this type of url when trying to access pages other than index page

http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home

but url to access page must be

http://localhost:8012/health-care/index.php/home

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?


问:
Split a column into separate columns using regex
I have got a single column that includes the information as follows:

```<code>1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid
</code>```

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

```<code>     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid
</code>```

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

答:
We can do this elegantly with tidyverse

```<code>library(tidyverse)
xl <- x %>%
      data_frame(id = .) %>%
      rownames_to_column(., 'rn') %>%
      separate_rows(id, sep = '\t') %>%
      mutate(id = str_extract(id, "[[:alnum:]]+(?=\\=)"))
xl
# A tibble: 9 x 2
#     rn    id
#  <chr> <chr>
#1     1  xid1
#2     1  yid2
#3     1  zid3
#4     2  xid4
#5     2  yid5
#6     3  xid6
#7     3  yid7
#8     3  yid8
#9     3  zid9
</code>```

If we need a wide format

```<code>xl %>%
   group_by(rn) %>%
   mutate(Seq = paste0("V", row_number())) %>%
   spread(Seq, id)
# A tibble: 3 x 5
# Groups: rn [3]
#     rn    V1    V2    V3    V4
#* <chr> <chr> <chr> <chr> <chr>
#1     1  xid1  yid2  zid3  <NA>
#2     2  xid4  yid5  <NA>  <NA>
#3     3  xid6  yid7  yid8  zid9
</code>```

data

```<code>x <- c("xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo",
   "xid4=oljhh88999\tyid5=lop9876666",
   "xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid")
</code>```

Body:
I have got a single column that includes the information as follows:

1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

Body:
We can do this elegantly with tidyverse

library(tidyverse)
xl <- x %>%
      data_frame(id = .) %>%
      rownames_to_column(., 'rn') %>%
      separate_rows(id, sep = '\t') %>%
      mutate(id = str_extract(id, "[[:alnum:]]+(?=\\=)"))
xl
# A tibble: 9 x 2
#     rn    id
#  <chr> <chr>
#1     1  xid1
#2     1  yid2
#3     1  zid3
#4     2  xid4
#5     2  yid5
#6     3  xid6
#7     3  yid7
#8     3  yid8
#9     3  zid9

If we need a wide format

xl %>%
   group_by(rn) %>%
   mutate(Seq = paste0("V", row_number())) %>%
   spread(Seq, id)
# A tibble: 3 x 5
# Groups: rn [3]
#     rn    V1    V2    V3    V4
#* <chr> <chr> <chr> <chr> <chr>
#1     1  xid1  yid2  zid3  <NA>
#2     2  xid4  yid5  <NA>  <NA>
#3     3  xid6  yid7  yid8  zid9

data

x <- c("xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo",
   "xid4=oljhh88999\tyid5=lop9876666",
   "xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid")


问:
Thumb images are not displayed
I am using carrierwave and minimagic gems. This is the code in my index view to display the thumb images:

```<code><div class="panel-body">
  Quantity  :<%= item.qty %><br>
  Price  : <%= number_to_currency(item.price, unit: "RS " ) %><br>
  <%= image_tag item.image_url(:thumb)%>
</div>
</code>```

This is the code available in the Image_uploader:

```<code>class ImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :thumb do
    process :resize_to_fit => [50, 50]
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end
</code>```

It works without :thumb; the image is displayed as is.

```<code><%= image_tag @item.image_url %>
</code>```

But it cannot be viewed in thumb format. It displays the image name and a broken image icon on the localhost preview.

Please help me solve this.

答:
Try this

```<code><%= image_tag item.thumbnail_url(:thumb) %>
</code>```

OR

```<code><%= image_tag item.avatar.thumb.url %>
</code>```

Go Thought this link, it will help you. reference

Title: Thumb images are not displayed

Body:
I am using carrierwave and minimagic gems. This is the code in my index view to display the thumb images:

  Quantity  :<%= item.qty %>

  Price  : <%= number_to_currency(item.price, unit: "RS " ) %>

  <%= image_tag item.image_url(:thumb)%>

This is the code available in the Image_uploader:

class ImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :thumb do
    process :resize_to_fit => [50, 50]
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

It works without :thumb; the image is displayed as is.

<%= image_tag @item.image_url %>

But it cannot be viewed in thumb format. It displays the image name and a broken image icon on the localhost preview.

Please help me solve this.

Body:
Try this

<%= image_tag item.thumbnail_url(:thumb) %>

OR

<%= image_tag item.avatar.thumb.url %>

Go Thought this link, it will help you. reference


问:
Extracting sub arrays from a two dimensional array for each element and displaying them in a table using KnockoutJS
I have used below code in PHP to extract data from MySQL :

```<code><?php
require("connect.php");
$sql = "SELECT `inn_lay_list`, `inner_layer` FROM `da_customer_auto_inner`
where `mpcode` = 'qf017'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)) {
    $data1 = $row['inn_lay_list'];
    $data2 = $row['inner_layer'];
}

$parts1 = explode(';',$data1);
$parts2 = explode(';',$data2);
$layer_cnt = count($parts1);
$array_inner = array_chunk($parts2, 8);

echo json_encode($parts1);
echo json_encode($array_inner);

mysqli_close($conn);
?>
</code>```

I obtained the result as:

["001","011","021","031"]

[["1","2","3","4","5","6","7","8"], ["11","12","13","14","15","16","17","18"], ["21","22","23","24","25","26","27","28"],[31","32","33","34","35","36","37","38"]]

Here for each element in first array there is a sub array in the second array(two dimensional array).
Now I want to display this in HTML page using a table. I am trying to use KnockoutJS “foreach” option with a named template:

```<code><script>
function MyViewModel() {
    this.layer = [{
        name: "<?=@$parts1[0]?>",
        layer_data: "<?=@$array_inner[0]?>"
    },
    {
        name: "<?=@$parts1[1]?>",
        layer_data: "<?=@$array_inner[1]?>"
    },
    {
        name: "<?=@$parts1[2]?>",
        layer_data: "<?=@$array_inner[2]?>"
    },
    {
        name: "<?=@$parts1[3]?>",
        layer_data: "<?=@$array_inner[3]?>"
    }]
}
ko.applyBindings(new MyViewModel());
</script>

<table class="table table-bordered">
    <thead>
    <tr>
      <td>Layer</td>
      <td>P2P</td>
      <td>P2T</td>
      <td>T2T</td>
      <td>Track Width</td>
      <td>PTH To Cu</td>
      <td>NPTH To Cu</td>
      <td>PTH AR</td>
      <td>Via AR</td>
    </tr>
    </thead>
    <tbody data-bind="template:{name:'layer-template', foreach:layer}">
    </tbody>
</table>
<script type="text/html" id="layer-template">
<tr>
    <td data-bind="text: name"></td>
    <td data-bind="text: layer_data[0]"></td>
    <td data-bind="text: layer_data[1]"></td>
    <td data-bind="text: layer_data[2]"></td>
    <td data-bind="text: layer_data[3]"></td>
    <td data-bind="text: layer_data[4]"></td>
    <td data-bind="text: layer_data[5]"></td>
    <td data-bind="text: layer_data[6]"></td>
    <td data-bind="text: layer_data[7]"></td>
</tr>
</script>
</code>```

I want my output as below :

答:
You can use array_shift.</p>

```<code>$tab = array(array(1,2,3), array(4,5,6), array(7,8,9));
$b = array_shift($tab);
print_r($b);
</code>```

Body:
I have used below code in PHP to extract data from MySQL :

<?php
require("connect.php");
$sql = "SELECT `inn_lay_list`, `inner_layer` FROM `da_customer_auto_inner`
where `mpcode` = 'qf017'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)) {
    $data1 = $row['inn_lay_list'];
    $data2 = $row['inner_layer'];
}

$parts1 = explode(';',$data1);
$parts2 = explode(';',$data2);
$layer_cnt = count($parts1);
$array_inner = array_chunk($parts2, 8);

echo json_encode($parts1);
echo json_encode($array_inner);

mysqli_close($conn);
?>

I obtained the result as:

["001","011","021","031"]

[["1","2","3","4","5","6","7","8"], ["11","12","13","14","15","16","17","18"], ["21","22","23","24","25","26","27","28"],[31","32","33","34","35","36","37","38"]]

Here for each element in first array there is a sub array in the second array(two dimensional array).
Now I want to display this in HTML page using a table. I am trying to use KnockoutJS “foreach” option with a named template:

      Layer
      P2P
      P2T
      T2T
      Track Width
      PTH To Cu
      NPTH To Cu
      PTH AR
      Via AR

I want my output as below :

Body:
You can use array_shift.

$tab = array(array(1,2,3), array(4,5,6), array(7,8,9));
$b = array_shift($tab);
print_r($b);


问:
strange problem with reflection and static method
Visual Studio 2008 - framework 3.5 - Visual Basic

Hi!
I have a problem with a static method invoked by reflection.
On the loading of my win-wpf I create a copy of "A4Library.dll" with the name "_temp.dll", in the same directory of the original.
Then, on a button-click event, I invoke a static method on the _temp.dll in this way:

```<code>Dim AssemblyFileName As String = Directory.GetCurrentDirectory() & "\_temp.dll"
Dim oAssembly As Assembly = Assembly.LoadFrom(AssemblyFileName)
Dim TypeName As String = "MyLibrary.MyService"
Dim t As Type = oAssembly.GetType(TypeName)
Dim mi As MethodInfo = t.GetMethod("MyMethod", BindingFlags.Static AndAlso BindingFlags.Public)
Dim bResponse As Boolean = mi.Invoke(Nothing, New Object() {MyPar1, MyPar2})
</code>```

But this works well only if I the .exe file is not in the same directory of the .dll files, otherwise I obtain this error (translated):

InnerException {"Cast impossible of [A]MyType on [B]MyType. The type A is originated from ... in the context 'Default' in the position 'F:\MyPath\A4Library.dll'. The type B is originated from ... in the context 'LoadFrom' in the position 'F:\MyPath_temp.dll'."}

It's strange: it seems to be a conflict with the same method in the original .dll, but I can't undertend why it looks at the original and not at the copy. If the .exe file relative to the principal assembly is placed in another directory, all runs well.

I neet to have the .exe in the same folder of the .dll, how can I solve the problem?

Thank you!
Pileggi

答: Why create a copy of assembly before executing static method? If creating a copy is needed, load that assembly in another AppDomain and execute the method in there.

ContentLicense: CC BY-SA 2.5

Body:
Visual Studio 2008 - framework 3.5 - Visual Basic

Hi!
I have a problem with a static method invoked by reflection.
On the loading of my win-wpf I create a copy of "A4Library.dll" with the name "_temp.dll", in the same directory of the original.
Then, on a button-click event, I invoke a static method on the _temp.dll in this way:

Dim AssemblyFileName As String = Directory.GetCurrentDirectory() & "\_temp.dll"
Dim oAssembly As Assembly = Assembly.LoadFrom(AssemblyFileName)
Dim TypeName As String = "MyLibrary.MyService"
Dim t As Type = oAssembly.GetType(TypeName)
Dim mi As MethodInfo = t.GetMethod("MyMethod", BindingFlags.Static AndAlso BindingFlags.Public)
Dim bResponse As Boolean = mi.Invoke(Nothing, New Object() {MyPar1, MyPar2})

But this works well only if I the .exe file is not in the same directory of the .dll files, otherwise I obtain this error (translated):

InnerException {"Cast impossible of [A]MyType on [B]MyType. The type A is originated from ... in the context 'Default' in the position 'F:\MyPath\A4Library.dll'. The type B is originated from ... in the context 'LoadFrom' in the position 'F:\MyPath_temp.dll'."}

It's strange: it seems to be a conflict with the same method in the original .dll, but I can't undertend why it looks at the original and not at the copy. If the .exe file relative to the principal assembly is placed in another directory, all runs well.

I neet to have the .exe in the same folder of the .dll, how can I solve the problem?

Thank you!
Pileggi


问:
How to order by custom time format in laravel?
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

```<code>            ->orderBy('time_schedule.start_time', 'asc');
</code>```

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

答:
Try this!

addSelect(\Illuminate\Support\Facades\DB::raw('TIME_FORMAT(start_time,"%H:%i") as st_time'))->orderBy('st_time','asc');```

Body:
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

            ->orderBy('time_schedule.start_time', 'asc');

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.


问:
Nhibernate query entity with enum property
I need to query the entity Person with enum property TargetBookingSystemType

```<code>public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual TargetBookingSystemType TargetBookingSystemType { get; set; }
}

 public class PersonMap : ClassMap<Person>
 {
     public PersonMap()
     {
        this.CompositeId(x => x.Id).KeyProperty(y => y.AccountName, "[AccountName]").KeyProperty(y => y.Domain, "[Domain]");
        this.Table("Person");
        this.Map(x => x.Key).Column("[Key]");
        this.Map(x => x.TargetBookingSystemType).Column("[TargetBookingSystemType]");//.CustomType<TargetBookingSystemType>();
     }
 }

public enum TargetBookingSystemType
    {
        GoogleCalendarAPIv3 = 1,
        MSExchange2007 = 2,
        MSExchange2010 = 3,
        MSExchange2013 = 4,
        MSOnline = 5
    }

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [nvarchar](20) NULL
 )
</code>```

I know that a possible solution is to change the type of the property to string but how can I achieve that using NHibernate I can have the property as an enum and still get a successful query?

Tried CustomType() but with no luck getting an error Input string was not in a correct format.

please note that the query is working when I comment out the line with mapping of TargetBookingSystemType

EDIT:

I would like to have one call to DB and after that filtering the result based on the enum.
This is the method doing the query using NHibernate:

```<code>public IList<Domain.DomainObjects.Entities.Person> GetAllPersons()
        {
            IList<Domain.DomainObjects.Entities.Person> list = new List<Domain.DomainObjects.Entities.Person>();
            string queryString = "select MR from Person MR";
            return this.Session.CreateQuery(queryString).SetCacheable(true).SetCacheRegion("LongTerm").List<Domain.DomainObjects.Entities.Person>();
        }
</code>```

How can I get the enum property in the result aswell?

答:
I didn't think that NH required anything special to handle an enum type?()?

Once the column's underlying data type is OK (based on @Jehof's comment), I would expect this query to be adequate:

```<code>var results = session.Query<Person>().Where(p => p.TargetBookingSystemType == TargetBookingSystemType.MSExchange2010).ToList();
</code>```

Body:
I need to query the entity Person with enum property TargetBookingSystemType

public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual TargetBookingSystemType TargetBookingSystemType { get; set; }
}

 public class PersonMap : ClassMap<Person>
 {
     public PersonMap()
     {
        this.CompositeId(x => x.Id).KeyProperty(y => y.AccountName, "[AccountName]").KeyProperty(y => y.Domain, "[Domain]");
        this.Table("Person");
        this.Map(x => x.Key).Column("[Key]");
        this.Map(x => x.TargetBookingSystemType).Column("[TargetBookingSystemType]");//.CustomType<TargetBookingSystemType>();
     }
 }

public enum TargetBookingSystemType
    {
        GoogleCalendarAPIv3 = 1,
        MSExchange2007 = 2,
        MSExchange2010 = 3,
        MSExchange2013 = 4,
        MSOnline = 5
    }

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [nvarchar](20) NULL
 )

I know that a possible solution is to change the type of the property to string but how can I achieve that using NHibernate I can have the property as an enum and still get a successful query?

Tried CustomType() but with no luck getting an error Input string was not in a correct format.

please note that the query is working when I comment out the line with mapping of TargetBookingSystemType

EDIT:

I would like to have one call to DB and after that filtering the result based on the enum.
This is the method doing the query using NHibernate:

public IList<Domain.DomainObjects.Entities.Person> GetAllPersons()
        {
            IList<Domain.DomainObjects.Entities.Person> list = new List<Domain.DomainObjects.Entities.Person>();
            string queryString = "select MR from Person MR";
            return this.Session.CreateQuery(queryString).SetCacheable(true).SetCacheRegion("LongTerm").List<Domain.DomainObjects.Entities.Person>();
        }

How can I get the enum property in the result aswell?

Body:
I didn't think that NH required anything special to handle an enum type?()?

Once the column's underlying data type is OK (based on @Jehof's comment), I would expect this query to be adequate:

var results = session.Query<Person>().Where(p => p.TargetBookingSystemType == TargetBookingSystemType.MSExchange2010).ToList();


问:
Access external URL with Ajax. Works in PC, but not in mobile
I'm creating a test project to learn about the phonegap build.
I make a simple index.html with a jquery code, to access a external URL and return me success or error.
The project works in my PC, returning sucess. But after compile in Phonegap Build and install in Android, the ajax returns error.
I already looked for tips in google, but nothind worked for me.
Here is my html file:
http://pastebin.com/R0SvDf03
And here is my config.xml file: http://pastebin.com/KsVc8Dsh
Thank you.</p>

答:
In the index.html file change following line

```<code>    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
</code>```

to

```<code><meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src *">
</code>```

Body:
In the index.html file change following line

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

to

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src *">


问:
duplicated data over serial
im sending some binary data over serial between two computers. I do it like this :

Receive

```<code>cat < /dev/ttyO5 >> $file
</code>```

Send

```<code>cat < $file > /dev/ttyO5
</code>```

When i check the files, sometimes the receiver machine copies some bytes of the beggining of file at the end. Something like this:

```<code>ce16 8fa7 bf54 dc6b 238a #Original file
ce16 8fa7 bf54 dc6b 238a ce16 8fa7 #Generated file on receive machine
</code>```

The number of bytes added at the end is not fixed, sometimes is 3 bytes, sometimes 4....And i dont know why, I flush the memories before sending and receiving ....

Any clue?

EDIT: SOLVED; the option -echo needs to be disabled on the port confirguration.

答: As a rule of thumb, you shall not copy binary data over serial port with unknown configuration. Either encode the data to the text file (uuencode, base64, quoted printable, implement your own) or make sure the serial port is configured to transfer 8bit raw data. Look for this example to see how it is achieved in C code. To manipulate the serial port configuration from shell script or CLI you can use stty command. What is important: set 8 data bits, disable software control flow and select raw data to be transmitted. Make sure you set the same configuration on both side.</p>

Title: duplicated data over serial

Body:
im sending some binary data over serial between two computers. I do it like this :

Receive

cat < /dev/ttyO5 >> $file

Send

cat < $file > /dev/ttyO5

When i check the files, sometimes the receiver machine copies some bytes of the beggining of file at the end. Something like this:

ce16 8fa7 bf54 dc6b 238a #Original file
ce16 8fa7 bf54 dc6b 238a ce16 8fa7 #Generated file on receive machine

The number of bytes added at the end is not fixed, sometimes is 3 bytes, sometimes 4....And i dont know why, I flush the memories before sending and receiving ....

Any clue?

EDIT: SOLVED; the option -echo needs to be disabled on the port confirguration.


问:
Unit test to check if an action method called the service layer
I have a controller called NewsController, the constructor of this controller receives an INewsService as parameter.

I have a method in this controller called GetAllNews() that returns a JSON result that I use to populate a YUI datatable.  I want to write a unit test that checks if the news service's FindAll method was called to return all the news items.  How would I do this?  What I currently have is:

```<code>public JsonResult GetAllNews()
{
   var items = newsService.FindAll();
   var jsonResult = Json(items);

   return jsonResult;
}
</code>```

My unit test for the controller looks like:

```<code>public NewsControllerTest()
{
   newsServiceStub = MockRepository.GenerateStub<INewsService>();
   newsController = new NewsController(newsServiceStub);
}

[Test]
public void GetAllNews_should_use_news_service()
{
   // Arrange
   List<News> newsList = new List<News>();
   newsServiceStub.Stub(s => s.FindAll()).Return(newsList);

   // Act
   var actual = newsController.GetAllNews();

   // Assert
   newsServiceStub.VerifyAllExpectations();
}
</code>```

The test passes with the above code.  But if I were to change GetAllNews() to look like below then it also passes.  Shouldn't it fail?  What I am trying to test is if GetAllNews() uses the news service:

```<code>public JsonResult GetAllNews()
{
   return null;
}
</code>```

答:
You might find this article by Martin Fowler interesting on the differences between mocks and stubs.

http://www.martinfowler.com/articles/mocksArentStubs.html

Fowler points out stubs are used for state verification while mocks are used for behavior verification.

Body:
I have a controller called NewsController, the constructor of this controller receives an INewsService as parameter.

I have a method in this controller called GetAllNews() that returns a JSON result that I use to populate a YUI datatable.  I want to write a unit test that checks if the news service's FindAll method was called to return all the news items.  How would I do this?  What I currently have is:

public JsonResult GetAllNews()
{
   var items = newsService.FindAll();
   var jsonResult = Json(items);

   return jsonResult;
}

My unit test for the controller looks like:

public NewsControllerTest()
{
   newsServiceStub = MockRepository.GenerateStub<INewsService>();
   newsController = new NewsController(newsServiceStub);
}

[Test]
public void GetAllNews_should_use_news_service()
{
   // Arrange
   List<News> newsList = new List<News>();
   newsServiceStub.Stub(s => s.FindAll()).Return(newsList);

   // Act
   var actual = newsController.GetAllNews();

   // Assert
   newsServiceStub.VerifyAllExpectations();
}

The test passes with the above code.  But if I were to change GetAllNews() to look like below then it also passes.  Shouldn't it fail?  What I am trying to test is if GetAllNews() uses the news service:

public JsonResult GetAllNews()
{
   return null;
}


问:
Preventing users from resizing columns widths in ListView?
I have a ListView In My Winform that has 4columns, Name, Money, ID and Level.

The problem is when I run my app, I still have the ability to mess with the columns widths
and change them.

I searched And found that I should do something like this:

```<code>private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
  e.Cancel = true;
  e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
}
</code>```

But the problem is that when I debugged and Ccanged the columns widths, this event didn't even fire!

Why didn't it fire?

And how can I make the column widths fixed?

I made a new winform app just in case if there was something wrong in my old one,
it fired, but only for the first time running the app .. here's the code:

```<code>namespace CsharpWinformTestingStuff
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      listView1.ColumnWidthChanging += new ColumnWidthChangingEventHandler(listView1_ColumnWidthChanging);
    }

    void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
    {

      e.Cancel = true;
      e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
    }
  }
}
</code>```

here is the initialize component just in case you might wanna know:

```<code>private void InitializeComponent()
{
  this.listView1 = new System.Windows.Forms.ListView();
  this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
  this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
  this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
  this.SuspendLayout();
  //
  // listView1
  //
  this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
        this.columnHeader1,
        this.columnHeader2,
        this.columnHeader3});
  this.listView1.GridLines = true;
  this.listView1.Location = new System.Drawing.Point(12, 12);
  this.listView1.Name = "listView1";
  this.listView1.Size = new System.Drawing.Size(284, 275);
  this.listView1.TabIndex = 0;
  this.listView1.UseCompatibleStateImageBehavior = false;
  this.listView1.View = System.Windows.Forms.View.Details;
  //
  // columnHeader1
  //
  this.columnHeader1.Text = "Name";
  this.columnHeader1.Width = 97;
  //
  // columnHeader2
  //
  this.columnHeader2.Text = "Age";
  this.columnHeader2.Width = 52;
  //
  // columnHeader3
  //
  this.columnHeader3.Text = "Email";
  this.columnHeader3.Width = 157;
  //
  // Form1
  //
  this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  this.ClientSize = new System.Drawing.Size(308, 299);
  this.Controls.Add(this.listView1);
  this.Name = "Form1";
  this.Text = "Form1";
  this.ResumeLayout(false);

}
</code>```

答:
Just click on the Properties>>Events>>ColumnWidthChanging.

Then add this code:

```<code>private void lstItems_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
    {
        e.Cancel = true;
        e.NewWidth = lstItems.Columns[e.ColumnIndex].Width;
    }
</code>```

Happy coding! ^_^

Body:
I have a ListView In My Winform that has 4columns, Name, Money, ID and Level.

The problem is when I run my app, I still have the ability to mess with the columns widths
and change them.

I searched And found that I should do something like this:

private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
  e.Cancel = true;
  e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
}

But the problem is that when I debugged and Ccanged the columns widths, this event didn't even fire!

Why didn't it fire?

And how can I make the column widths fixed?

I made a new winform app just in case if there was something wrong in my old one,
it fired, but only for the first time running the app .. here's the code:

namespace CsharpWinformTestingStuff
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      listView1.ColumnWidthChanging += new ColumnWidthChangingEventHandler(listView1_ColumnWidthChanging);
    }

    void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
    {

      e.Cancel = true;
      e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
    }
  }
}

here is the initialize component just in case you might wanna know:

private void InitializeComponent()
{
  this.listView1 = new System.Windows.Forms.ListView();
  this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
  this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
  this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
  this.SuspendLayout();
  //
  // listView1
  //
  this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
        this.columnHeader1,
        this.columnHeader2,
        this.columnHeader3});
  this.listView1.GridLines = true;
  this.listView1.Location = new System.Drawing.Point(12, 12);
  this.listView1.Name = "listView1";
  this.listView1.Size = new System.Drawing.Size(284, 275);
  this.listView1.TabIndex = 0;
  this.listView1.UseCompatibleStateImageBehavior = false;
  this.listView1.View = System.Windows.Forms.View.Details;
  //
  // columnHeader1
  //
  this.columnHeader1.Text = "Name";
  this.columnHeader1.Width = 97;
  //
  // columnHeader2
  //
  this.columnHeader2.Text = "Age";
  this.columnHeader2.Width = 52;
  //
  // columnHeader3
  //
  this.columnHeader3.Text = "Email";
  this.columnHeader3.Width = 157;
  //
  // Form1
  //
  this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  this.ClientSize = new System.Drawing.Size(308, 299);
  this.Controls.Add(this.listView1);
  this.Name = "Form1";
  this.Text = "Form1";
  this.ResumeLayout(false);

}

Body:
Just click on the Properties>>Events>>ColumnWidthChanging.

Then add this code:

private void lstItems_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
    {
        e.Cancel = true;
        e.NewWidth = lstItems.Columns[e.ColumnIndex].Width;
    }

Happy coding! ^_^


问:
Xamarin.Android app "READ_CONTACTS" permission always added automatically
My problem is that I do not want to set a privacy policy for my app, I would rather remove all of the unnecessary permission requests.

I have removed the "READ_CONTACTS" permission from my AndroidManifest.xml, but when trying to upload to Play Store, it always says:

The apk has permissions that require a privacy policy set for the app, e.g: android.permission.READ_CONTACTS. [403]

It seems to me, that "READ_CONTACTS" permission is always added automatically.
Is there a way to remove this?

I only use the following permissions:

```<code><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

答: It was definitely a 3rd-party library issue.</p>

Body:
My problem is that I do not want to set a privacy policy for my app, I would rather remove all of the unnecessary permission requests.

I have removed the "READ_CONTACTS" permission from my AndroidManifest.xml, but when trying to upload to Play Store, it always says:

The apk has permissions that require a privacy policy set for the app, e.g: android.permission.READ_CONTACTS. [403]

It seems to me, that "READ_CONTACTS" permission is always added automatically.
Is there a way to remove this?

I only use the following permissions:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


问:
ASP MVC Resource in javascript variable encodes string
I have the following string in resource file.

You can't do this.

And I display it as a tooltip on some button from it's attribute.

```<code>$(".completedButton").attr("title", "@(Resources.CompleteBtn)");
</code>```

It shows the quotation mark like this.

&#8217 ; //without the space

I tried with HttpUtility.JavaScriptStringEncodewith no luck.
Any ideas on how should I do this?

答:
You can use Html.Raw()

```<code>$(".completedButton").attr("title", "@Html.Raw(Resources.CompleteBtn)");
</code>```

Body:
I have the following string in resource file.

You can't do this.

And I display it as a tooltip on some button from it's attribute.

$(".completedButton").attr("title", "@(Resources.CompleteBtn)");

It shows the quotation mark like this.

&#8217 ; //without the space

I tried with HttpUtility.JavaScriptStringEncodewith no luck.
Any ideas on how should I do this?

Body:
You can use Html.Raw()

$(".completedButton").attr("title", "@Html.Raw(Resources.CompleteBtn)");


问:
In CMake how do I deal with generated source files which number and names are not known before?
Imagine a code generator which reads an input file (say a UML class diagram) and produces an arbitrary number of source files which I want to be handled in my project. (to draw a simple picture let's assume the code generator just produces .cpp files).

The problem is now the number of files generated depends on the input file and thus is not known when writing the CMakeLists.txt file or even in CMakes configure step. E.g.:

```<code>>>> code-gen uml.xml
generate class1.cpp..
generate class2.cpp..
generate class3.cpp..
</code>```

What's the recommended way to handle generated files in such a case? You could use FILE(GLOB.. ) to collect the file names after running code-gen the first time but this is discouraged because CMake would not know any files on the first run and later it would not recognize when the number of files changes.

I could think of some approaches but I don't know if CMake covers them, e.g.:

(somehow) define a dependency from an input file (uml.xml in my example) to a variable (list with generated file names)

in case the code generator can be convinced to tell which files it generates the output of code-gen could be used to create a list of input file names. (would lead to similar problems but at least I would not have to use GLOB which might collect old files)

just define a custom target which runs the code generator and handles the output files without CMake (don't like this option)

Update: This question targets a similar problem but just asks how to glob generated files which does not address how to re-configure when the input file changes.

答:
Together with Tsyvarev's answer and some more googling I came up with the following CMakeList.txt which does what I want:

```<code>project(generated)
cmake_minimum_required(VERSION 3.6)
set(IN_FILE "${CMAKE_SOURCE_DIR}/input.txt")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${IN_FILE}")
execute_process(
    COMMAND python3 "${CMAKE_SOURCE_DIR}/code-gen" "${IN_FILE}"
    WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
    INPUT_FILE "${IN_FILE}"
    OUTPUT_VARIABLE GENERATED_FILES
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
add_executable(generated main.cpp ${GENERATED_FILES})
</code>```

It turns an input file (input.txt) into output files using code-gen and compiles them.

execute_process is being executed in the configure step and the set_property() command makes sure CMake is being re-run when the input file changes.

Note: in this example the code-generator must print a CMake-friendly list on stdout which is nice if you can modify the code generator. FILE(GLOB..) would do the trick too but this would for sure lead to problems (e.g. old generated files being compiled, too, colleagues complaining about your code etc.)

PS: I don't like to answer my own questions - If you come up with a nicer or cleaner solution in the next couple of days I'll take yours!

Body:
Imagine a code generator which reads an input file (say a UML class diagram) and produces an arbitrary number of source files which I want to be handled in my project. (to draw a simple picture let's assume the code generator just produces .cpp files).

The problem is now the number of files generated depends on the input file and thus is not known when writing the CMakeLists.txt file or even in CMakes configure step. E.g.:

>>> code-gen uml.xml
generate class1.cpp..
generate class2.cpp..
generate class3.cpp..

What's the recommended way to handle generated files in such a case? You could use FILE(GLOB.. ) to collect the file names after running code-gen the first time but this is discouraged because CMake would not know any files on the first run and later it would not recognize when the number of files changes.

I could think of some approaches but I don't know if CMake covers them, e.g.:

(somehow) define a dependency from an input file (uml.xml in my example) to a variable (list with generated file names)

in case the code generator can be convinced to tell which files it generates the output of code-gen could be used to create a list of input file names. (would lead to similar problems but at least I would not have to use GLOB which might collect old files)

just define a custom target which runs the code generator and handles the output files without CMake (don't like this option)

Update: This question targets a similar problem but just asks how to glob generated files which does not address how to re-configure when the input file changes.

Body:
Together with Tsyvarev's answer and some more googling I came up with the following CMakeList.txt which does what I want:

project(generated)
cmake_minimum_required(VERSION 3.6)
set(IN_FILE "${CMAKE_SOURCE_DIR}/input.txt")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${IN_FILE}")
execute_process(
    COMMAND python3 "${CMAKE_SOURCE_DIR}/code-gen" "${IN_FILE}"
    WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
    INPUT_FILE "${IN_FILE}"
    OUTPUT_VARIABLE GENERATED_FILES
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
add_executable(generated main.cpp ${GENERATED_FILES})

It turns an input file (input.txt) into output files using code-gen and compiles them.

execute_process is being executed in the configure step and the set_property() command makes sure CMake is being re-run when the input file changes.

Note: in this example the code-generator must print a CMake-friendly list on stdout which is nice if you can modify the code generator. FILE(GLOB..) would do the trick too but this would for sure lead to problems (e.g. old generated files being compiled, too, colleagues complaining about your code etc.)

PS: I don't like to answer my own questions - If you come up with a nicer or cleaner solution in the next couple of days I'll take yours!


问:
repeating background image which is from 'image map' using CSS
I have a image map (sorry for sloppy drawing...)

The number means x-coordinate, y-coordinate, width, height.
For example, 5, 5, 25, 25 means that this image is located at (5, 5) and has width 25px and height 25px.

(the last image's size is wrong. 100, 5, 5, 25 is correct size.

And I want to make

using above image map with width 100px and height 25px.

At this time, I use image map as following.

```<code>#aDiv {
    width: 25px; height 25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}
</code>```

with one tag

```<code><div></div>
</code>```

for background.

But I have no idea that making something like second image using first image (image map).
How can I do this?

The above code is what I have done. I have no idea totally. The last idea I have is

```<code>#one {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

#two {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-100px -5px;
}

#three {
    display:inline-block;
    width:5px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-50px -5px;
}

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</code>```

But in this way, the total width is just 75 pixel. I need to repeat #two, i.e., repeating the third drawing of image map.

答:
Since you're doing fine with your CSS, I think the only pointer you'll need is that you can just adapt an HTML structure which fit your needs:

```

In this way you can add CSS to target .panel__top-left, .panel__top and .panel__top-right.

Body:
I have a image map (sorry for sloppy drawing...)

The number means x-coordinate, y-coordinate, width, height.
For example, 5, 5, 25, 25 means that this image is located at (5, 5) and has width 25px and height 25px.

(the last image's size is wrong. 100, 5, 5, 25 is correct size.

And I want to make

using above image map with width 100px and height 25px.

At this time, I use image map as following.

#aDiv {
    width: 25px; height 25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

with one tag

for background.

But I have no idea that making something like second image using first image (image map).
How can I do this?

The above code is what I have done. I have no idea totally. The last idea I have is

#one {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

#two {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-100px -5px;
}

#three {
    display:inline-block;
    width:5px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-50px -5px;
}

But in this way, the total width is just 75 pixel. I need to repeat #two, i.e., repeating the third drawing of image map.

Body:
Since you're doing fine with your CSS, I think the only pointer you'll need is that you can just adapt an HTML structure which fit your needs:

<div class="panel">
    <div class="panel__top-left"></div>
    <div class="panel__top"></div>
    <div class="panel__top-right"></div>
</div>

In this way you can add CSS to target .panel__top-left, .panel__top and .panel__top-right.


问:
String copy using character pointers
Consider the following code, which works fine asusual for copying string

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

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}
</code>```

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

```<code>char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2
</code>```

I tried to copy pointer values as shown below

```<code>void strcp(char *s1, char *s2) {

s1=s2;
}
</code>```

But it didn't work.

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

void strcp(char *s1, char *s2);

int main() {
    char *s1 = "Hi, I am a good boy";                   //1
    char *s2 = "Really!! I am a good boy";              //2

    strcp(&s1,&s2); //Pass Address to function

    printf("s1 = %s", s1);
    printf("\ns2 = %s", s2);

    return 0;
}

/*
 * This method takes pointer address as arguments and simply swap the address
 * pointing to string (i.e. char array).
 */
void strcp(char *s1, char *s2) {
    char *temp = *s1;
           *s1 = *s2;
           *s2 = temp;
}
</code>```

O/P :

s1 = Really!! I am a good boy

s2 = Hi, I am a good boy

http://ideone.com/wTH4VO

Title: String copy using character pointers

Body:
Consider the following code, which works fine asusual for copying string

#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2

I tried to copy pointer values as shown below

void strcp(char *s1, char *s2) {

s1=s2;
}

But it didn't work.

Body:
#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {
    char *s1 = "Hi, I am a good boy";                   //1
    char *s2 = "Really!! I am a good boy";              //2

    strcp(&s1,&s2); //Pass Address to function

    printf("s1 = %s", s1);
    printf("\ns2 = %s", s2);

    return 0;
}

/*
 * This method takes pointer address as arguments and simply swap the address
 * pointing to string (i.e. char array).
 */
void strcp(char *s1, char *s2) {
    char *temp = *s1;
           *s1 = *s2;
           *s2 = temp;
}

O/P :

s1 = Really!! I am a good boy

s2 = Hi, I am a good boy

http://ideone.com/wTH4VO


问:
Show image in a popup when I click button
I have a button and i need to show an image in a popup when i click this button.

Why this code doesn't work? I try with a window.open in onclick event but it doesn't work

```<code><input type="button" value="Mostra Immagine" onclick=window.open(src="../img/mypicture.jpg")>
</code>```

Where is my error?

答:
try this:

HTML:

```<code><div class="popup" onclick="myFunction()">Click me!
  <span class="popuptext" id="myPopup">Popup text...</span>
</div>
</code>```

CSS:

```<code>/* Popup container */
.popup {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

/* The actual popup (appears on top) */
.popup .popuptext {
    visibility: hidden;
    width: 160px;
    background-color: #555;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 8px 0;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -80px;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}
</code>```

JavaScript:

```<code><script>
// When the user clicks on <div>, open the popup
function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}
</script>
</code>```

You can read more here https://www.w3schools.com/howto/howto_js_popup.asp
Hope Helpful

Body:
I have a button and i need to show an image in a popup when i click this button.

Why this code doesn't work? I try with a window.open in onclick event but it doesn't work

<input type="button" value="Mostra Immagine" onclick=window.open(src="../img/mypicture.jpg")>

Where is my error?

Body:
try this:

HTML:

<div class="popup" onclick="myFunction()">Click me!
  <span class="popuptext" id="myPopup">Popup text...</span>
</div>

CSS:

/* Popup container */
.popup {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

/* The actual popup (appears on top) */
.popup .popuptext {
    visibility: hidden;
    width: 160px;
    background-color: #555;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 8px 0;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -80px;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}

JavaScript:

<script>
// When the user clicks on <div>, open the popup
function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}
</script>

You can read more here https://www.w3schools.com/howto/howto_js_popup.asp
Hope Helpful


问:
Newtonsoft.Json 10.0.0.2 pulling .NET framework standard edition in a old MVC 5 application
I have a MVC 5 application which uses the full .NET framework ( v 4.6.2)

When i updated my packages on this project , the Json.Net package has been upgraded to 10.0.0.2
If i run the application after the updated i get the error

Could not load file or assembly 'System.Runtime, Version=4.1.1.0,
  Culture=neutral, .... The system cannot find the file specified.

The only way to fix this error is to either :

Remove the following dependency line from my web.config

```<code> <dependentAssembly>
    <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" />
  </dependentAssembly>
</code>```

or

Add the System.Runtime dll as a Nuget package.

I find it very odd that I have to add all the core dll's of the full .NET framework as Nuget packages.

My question is :

Is there something wrong with the Json.Net package and its dependencies ?
As a nuget package should be able to pull its dependencies automatically but I have to manually install the System.Runtime nuget package for my application to work

or

Has Nuget messed up the dependencies  ?

or

Maybe this is what microsoft expect you to do going forward ?  i.e use nuget packages for even the basic dll's like System.Runtime  even for projects which are not based on .NET core or .NET standard libraries.

Edit : Added clarity to question based on comments

答:
I was able to find a solution to this,
I am posting it here as it might end up being useful to someone else.

TL;DR  Nuget messed up.

Long answer ,

I have a Solution with around 100 CSProj files , one of them (Project X) had mistakenly installed the .NET standard library.

A couple of weeks later , a new version of Json.Net got released and I went to the consolidate tab on nuget manager to update and Consolidate the version of Json.Net across the 100 projects in my solution.

This is where the mess up occurred , for some reason Nuget decided to take the Json.Net package which it installed in project X ( with the .NET standard assembly dependency )  and apply it across all my projects including the main Web project.

This meant the web project now wanted version of basic DLL which did not exist in the full .NET framework . E.g , it expected v4.1.1.0 for System.Runtime which is the version .NETStandard 1.3 library expects
as shown in the dependency map here

This resulted in the error in question above.

The solution in my case was to remove the incorrect package that got added in Project X , uninstall Json.Net package and re install it in all the other projects. This time it got the correct dependency map.

Body:
I have a MVC 5 application which uses the full .NET framework ( v 4.6.2)

When i updated my packages on this project , the Json.Net package has been upgraded to 10.0.0.2
If i run the application after the updated i get the error

Could not load file or assembly 'System.Runtime, Version=4.1.1.0,
  Culture=neutral, .... The system cannot find the file specified.

The only way to fix this error is to either :

Remove the following dependency line from my web.config

 <dependentAssembly>
    <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" />
  </dependentAssembly>

or

Add the System.Runtime dll as a Nuget package.

I find it very odd that I have to add all the core dll's of the full .NET framework as Nuget packages.

My question is :

Is there something wrong with the Json.Net package and its dependencies ?
As a nuget package should be able to pull its dependencies automatically but I have to manually install the System.Runtime nuget package for my application to work

or

Has Nuget messed up the dependencies  ?

or

Maybe this is what microsoft expect you to do going forward ?  i.e use nuget packages for even the basic dll's like System.Runtime  even for projects which are not based on .NET core or .NET standard libraries.

Edit : Added clarity to question based on comments


问:
Entity Framework Filtering
I want to apply filters on my query something like this

```<code>filters.Aggregate(query, (current, filter) => current.Where(filter));
</code>```

But this creates query with AND as binder for example, if my filters are name="abc" , state="xyz"
Applying the above expression i get my query as

```<code>select * from SomeTable where name="abc" **AND** state="xyz"
</code>```

But i want it work like

```<code>select * from SomeTable where name="abc" **OR** state="xyz" instead
</code>```

how should I change it, Please help

答:
```<code>var result = from a in db.tablename
             where a.name=="abc" || a.state== "xyz"
             select a;
OR

var result =  db.tablename.where(a=> (a.name.Equals("abc")) ||
              (a.state.Equals("xyz"));
</code>```

Title: Entity Framework Filtering

Body:
I want to apply filters on my query something like this

filters.Aggregate(query, (current, filter) => current.Where(filter));

But this creates query with AND as binder for example, if my filters are name="abc" , state="xyz"
Applying the above expression i get my query as

select * from SomeTable where name="abc" **AND** state="xyz"

But i want it work like

select * from SomeTable where name="abc" **OR** state="xyz" instead

how should I change it, Please help


问:
.NET proxy detection
I am having an issue with .NET detecting the proxy settings configured through internet explorer.

I'm writing a client application that supports proxies, and to test I set up an array of 9 squid servers to support various authentication methods for HTTP and HTTPs. I have a script that updates IE to whichever configuration I choose (which proxy, detection via "Auto", PAC, or hardcode).

I have tried the 3 methods below to detect the IE configuration through .NET. On occassion I notice that .NET picks up the wrong set of proxy servers. IE has the correct settings, and if I browse the web with IE, I can see I am hitting the correct servers via wireshark.

WebRequest.GetSystemWebProxy().GetProxy(destination);

GlobalProxySelection.Select.GetProxy(destination);

WebRequest.DefaultWebProxy

Here are the following tips I have:

My script sets a PAC file on a webserver, and updates the configuration in IE, then clears IE's cache

.NET seems to get "stuck" on a certain proxy configuration, and I have to set another configuration for .NET to realize there was a change. Occasionally it seems to pick some random set of servers (I'm sure they're not random, just a set of servers I used once and are in some cached PAC file or something). As in, I will check the proxy for the destination "https://www.secure.com" and I may have IE configured for and thus expect to get "http://squidserver:18" and instead it will return "http://squidserver:28" (port 18 runs NTLM, 28 runs without authentication). All the squid servers work.

This does not appear to be an issue on XP, only Vista, 2003, and windows 7.

Hardcoding the proxy servers in IE ALWAYS works

Time always solves the issue - if I leave the computer for about 20 or 30 minutes and come back, .NET picks up the correct proxy settings, as if a cached PAC script expired.

答:
I had the same issue and I succeded getting/setting the proxy setting in registry:</p>

```<code>[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"ProxyServer"="<your proxy IP address>:8080"
"ProxyEnable"=dword:00000001
"ProxyOverride"="<local>"
</code>```

Title: .NET proxy detection

Body:
I had the same issue and I succeded getting/setting the proxy setting in registry:

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"ProxyServer"="&lt;your proxy IP address&gt;:8080"
"ProxyEnable"=dword:00000001
"ProxyOverride"="&lt;local&gt;"


问:
Check the answer and verify from database whether it is correct or not in PHP
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.

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
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
} else {
echo "0 results";
}
$conn->close();

?>
</code>```

答:
Because all of the radio inputs have the same name. They all will be considered as same radio group. You need to have different names for different questions. Something like -

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

You also can use the row id instead of the of $i.

Body:
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.

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
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "
Question: " . $row["Question"] . "
";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '
';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '
';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '
';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '
';
$i++;
}
} else {
echo "0 results";
}
$conn->close();

?>

Body:
Because all of the radio inputs have the same name. They all will be considered as same radio group. You need to have different names for different questions. Something like -

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

You also can use the row id instead of the of $i.