问:
appJar Internationalisation not working
I am trying to use appJar's internationalisation feature with English and Spanish. However, when I use the English config file, everything works fine, but when I use Spanish one, I get errors. When the file is encoded in ANSI, I get the following error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 0: invalid start byte
</code>```

I have also tried to encode it in UTF-8, but again, I get an error:

```<code>configparser.MissingSectionHeaderError: File contains no section headers.
file: 'SPANISH.ini', line: 1
'\ufeff[TABBEDFRAME]\r\n'
</code>```

The English config file is exactly the same as the Spanish one - the only difference being the translation.

I would be grateful for any help and suggestions.

答: It turns out that the Spanish config file seemed to be corrupted - when I copied the contents over to a new file, it worked fine.</p>

Title: appJar Internationalisation not working

Body:
I am trying to use appJar's internationalisation feature with English and Spanish. However, when I use the English config file, everything works fine, but when I use Spanish one, I get errors. When the file is encoded in ANSI, I get the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 0: invalid start byte

I have also tried to encode it in UTF-8, but again, I get an error:

configparser.MissingSectionHeaderError: File contains no section headers.
file: 'SPANISH.ini', line: 1
'\ufeff[TABBEDFRAME]\r\n'

The English config file is exactly the same as the Spanish one - the only difference being the translation.

I would be grateful for any help and suggestions.


来源: stackexchange

问:
How to open rabbitmq in browser using docker container?
This was probably asked already, but so far I can't find any detailed explanation at all, and the existing documentation seems as if it was written for some kind on psychic who supposed to know everything.

As per this manual, I added the container

```<code>docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:latest
</code>```

Then I checked it to receive the container ip

```<code>docker inspect some-rabbit
</code>```

Checked ports with

```<code>docker ps
</code>```

And tried to connect in the browser with this formula

```<code>https://{container-ip}:{port}
</code>```

It did't work.

Am I'm doing something wrong, or maybe I am supposed to add something additional, like a container for apache or other stuff?

EDIT

As I understand, after creating some-rabbit container, now I need to run Dockerfile to create image? (This whole thing is confusing to me). How am I supposed to do that? I mean, I saw command docker build -f /path/to/a/Dockerfile but if for example I placed the Dockerfile in second path D:\Docker\rabbitmq, how I supposed to get there? (the path doesn't seems to be recognized)

答:
First off, you need the management image (eg. rabbitmq:3-management) to access it through the browser. If your docker is running locally, then you should be able to access it by navigating to http://localhost:{port} or http://127.0.0.1:{port} (15672 by default).

Here is an example of a simple docker-compose.yml:

```<code>version: "3"
services:
 rabbitmq:
    image: "rabbitmq:3-management"
    ports:
      - "5672:5672"
      - "15672:15672"
    volumes:
      - 'rabbitmq_data:/data'

volumes:
  rabbitmq_data:
</code>```

After starting the container, Rabbitmq is now accessible at http://127.0.0.1:15672. The default username and password should be guest:guest. More details here.

ContentLicense: CC BY-SA 4.0

Body:
This was probably asked already, but so far I can't find any detailed explanation at all, and the existing documentation seems as if it was written for some kind on psychic who supposed to know everything.

As per this manual, I added the container

docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:latest

Then I checked it to receive the container ip

docker inspect some-rabbit

Checked ports with

docker ps

And tried to connect in the browser with this formula

https://{container-ip}:{port}

It did't work.

Am I'm doing something wrong, or maybe I am supposed to add something additional, like a container for apache or other stuff?

EDIT

As I understand, after creating some-rabbit container, now I need to run Dockerfile to create image? (This whole thing is confusing to me). How am I supposed to do that? I mean, I saw command docker build -f /path/to/a/Dockerfile but if for example I placed the Dockerfile in second path D:\Docker\rabbitmq, how I supposed to get there? (the path doesn't seems to be recognized)

Body:
First off, you need the management image (eg. rabbitmq:3-management) to access it through the browser. If your docker is running locally, then you should be able to access it by navigating to http://localhost:{port} or http://127.0.0.1:{port} (15672 by default).

Here is an example of a simple docker-compose.yml:

version: "3"
services:
 rabbitmq:
    image: "rabbitmq:3-management"
    ports:
      - "5672:5672"
      - "15672:15672"
    volumes:
      - 'rabbitmq_data:/data'

volumes:
  rabbitmq_data:

After starting the container, Rabbitmq is now accessible at http://127.0.0.1:15672. The default username and password should be guest:guest. More details here.


问:
Json Template Validation error with Split Function
I am getting below error while doing deployment through Visual studio Team services.

"The template language function 'split' expects its first parameter to be of type 'String'. The provided value is of type 'Uri"

Points:-
1.I am using linked templates.
2.I am sending "linked template URL" to the split function.

The things were working just fine until today.
Now the issue is there.

Any help is highly appreciated.

Regards
RatZ

答:
it might be a temporary thing, i saw a thread somewhere about deployment.uri functions is broken. that being said try casting your uri to string explicitly:</p>

```<code>split(string(bla-bla-bla), ...)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
it might be a temporary thing, i saw a thread somewhere about deployment.uri functions is broken. that being said try casting your uri to string explicitly:

split(string(bla-bla-bla), ...)


问:
Test the exist validator in Yii2 without database with mockeryBuilder()
I want to test my AR model without connect to database in Yii 2 so I use mockBuilder() but I dont know how can I pass the mock object to the model exist validator, for example:

```<code>class Comment extends ActiveRecord
{
  public function rules()
  {
    return [
      [['id', 'user_id', 'post_id'], 'comment'],
      ['comment', 'string',
        'max' => 200
      ],
      ['user_id', 'exist',
        'targetClass'     => User::className(),
        'targetAttribute' => 'id'
      ],
      ['post_id', 'exist',
        'targetClass'     => Post::className(),
        'targetAttribute' => 'id'
      ]
    ];
  }
}

class CommentTest extends TestCase
{
  public function testValidateCorrectData()
  {
    $user = $this->getMockBuilder(User::className())
      ->setMethods(['find'])
      ->getMock();

    $user->method('find')->willReturn(new User([
      'id' => 1
    ]));

    $post = $this->getMockBuilder(Post::className())
      ->setMethods(['find'])
      ->getMock();

    $post->method('find')->willReturn(new Post([
      'id' => 1
    ]));

    // How can I pass to $user and $post to exist validator in Comment model?

    $comment = new Comment([
      'user_id' => 1,
      'post_id' => 1,
      'comment' => 'test...'
    ]);

    expect_that($comment->validate());
  }
}
</code>```

ok, It's not a best code just I'd like to introduce what I want to do.

答:
Yii2 ExistValidator uses ActiveQuery::exists() for check existence and you should replace generated validator to mockobject where the method createQuery returns mockobject of ActiveQuery where ::exists() return something you want (true/false) e.g.</p>

```<code>$activeQueryMock = $this->getMockBuilder(ActiveQuery::className())
    ->disableOriginalConstructor()
    ->setMethods(['exists'])
    ->getMock();

$activeQueryMock->expects($this->any())
    ->method('exists')
    ->willReturn($value); //Your value here true/false

$model = $this->getMockBuilder(Comment::className())
    ->setMethods(['getActiveValidators'])
    ->getMock();

$model->expects($this->any())
    ->method('getActiveValidators')
    ->willReturnCallback(function () use ($activeQueryMock) {
        $validators = (new Comment())->activeValidators;
        foreach ($validators as $key => $validator) {
            if (($validator instanceof ExistValidator) && ($validator->attributes = ['user_id'])) {

                $mock = $this->getMockBuilder(ExistValidator::className())
                    ->setConstructorArgs(['config' => get_object_vars($validator)])
                    ->setMethods(['createQuery'])
                    ->getMock();

                $mock->expects($this->any())
                    ->method('createQuery')
                    ->willReturn($activeQueryMock);

                $validators[$key] = $mock;
                break;
            }
        }
        return $validators;
    });

$model->validate();
</code>```

Body:
I want to test my AR model without connect to database in Yii 2 so I use mockBuilder() but I dont know how can I pass the mock object to the model exist validator, for example:

class Comment extends ActiveRecord
{
  public function rules()
  {
    return [
      [['id', 'user_id', 'post_id'], 'comment'],
      ['comment', 'string',
        'max' => 200
      ],
      ['user_id', 'exist',
        'targetClass'     => User::className(),
        'targetAttribute' => 'id'
      ],
      ['post_id', 'exist',
        'targetClass'     => Post::className(),
        'targetAttribute' => 'id'
      ]
    ];
  }
}

class CommentTest extends TestCase
{
  public function testValidateCorrectData()
  {
    $user = $this->getMockBuilder(User::className())
      ->setMethods(['find'])
      ->getMock();

    $user->method('find')->willReturn(new User([
      'id' => 1
    ]));

    $post = $this->getMockBuilder(Post::className())
      ->setMethods(['find'])
      ->getMock();

    $post->method('find')->willReturn(new Post([
      'id' => 1
    ]));

    // How can I pass to $user and $post to exist validator in Comment model?

    $comment = new Comment([
      'user_id' => 1,
      'post_id' => 1,
      'comment' => 'test...'
    ]);

    expect_that($comment->validate());
  }
}

ok, It's not a best code just I'd like to introduce what I want to do.

Body:
Yii2 ExistValidator uses ActiveQuery::exists() for check existence and you should replace generated validator to mockobject where the method createQuery returns mockobject of ActiveQuery where ::exists() return something you want (true/false) e.g.

$activeQueryMock = $this->getMockBuilder(ActiveQuery::className())
    ->disableOriginalConstructor()
    ->setMethods(['exists'])
    ->getMock();

$activeQueryMock->expects($this->any())
    ->method('exists')
    ->willReturn($value); //Your value here true/false

$model = $this->getMockBuilder(Comment::className())
    ->setMethods(['getActiveValidators'])
    ->getMock();

$model->expects($this->any())
    ->method('getActiveValidators')
    ->willReturnCallback(function () use ($activeQueryMock) {
        $validators = (new Comment())->activeValidators;
        foreach ($validators as $key => $validator) {
            if (($validator instanceof ExistValidator) && ($validator->attributes = ['user_id'])) {

                $mock = $this->getMockBuilder(ExistValidator::className())
                    ->setConstructorArgs(['config' => get_object_vars($validator)])
                    ->setMethods(['createQuery'])
                    ->getMock();

                $mock->expects($this->any())
                    ->method('createQuery')
                    ->willReturn($activeQueryMock);

                $validators[$key] = $mock;
                break;
            }
        }
        return $validators;
    });

$model->validate();


问:
Filtering inside the List
Firstly,i fill in the list with some objects with different propetries and afterwards I'd like to remove all inappropriate objects from this list.
For sure, it throws an exception, saying that the list has been modified and it leads to problems with enumeration. How to manage this and remove all inappropriate objects without using another List, for example, ListFiltred, where I can add all appropriate objects?    </p>

```<code>MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "01" });
MyList.Add(new Houses() { Number = "02" });
MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "04" });
foreach (var item in MyList)
{
    if (item.Number != "04")
    {
        MyList.Remove(item);
    }
}
</code>```

答:
Use RemoveAll direct method

```<code>MyList.RemoveAll(val=>val.Number != "04");
</code>```

Title: Filtering inside the List

Body:
Firstly,i fill in the list with some objects with different propetries and afterwards I'd like to remove all inappropriate objects from this list.
For sure, it throws an exception, saying that the list has been modified and it leads to problems with enumeration. How to manage this and remove all inappropriate objects without using another List, for example, ListFiltred, where I can add all appropriate objects?

MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "01" });
MyList.Add(new Houses() { Number = "02" });
MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "04" });
foreach (var item in MyList)
{
    if (item.Number != "04")
    {
        MyList.Remove(item);
    }
}

Body:
Use RemoveAll direct method

MyList.RemoveAll(val=>val.Number != "04");


问:
Passing data from one component to another
On component1.vue I have

```<code>  export default {
    data () {
      return {
        editItemNumber: null,
        editBreakdownNumber: null
      }
    }
</code>```

On component2.vue I have a table populated by an array

On that table is an edit button.  Among the item in that table is itemNumber value.  Which I need to assign from that particular row clicked to the editItemNumber on component1.vue

```<code><b-table show-empty bordered striped hover :items="itemTableList" :fields="fields">
  <template slot="actions" scope="row">
<b-btn variant='success' size="sm" @click.stop="edit(row.item,row.index,$event.target)">Edit</b-btn>
</template>
</b-table>
</code>```

As you see above originally all of this was on one component and I was just calling to an edit function which repopulated the v-models with that rows contents.  But now with everything split among components I don't know how to edit this to do what I've been tasked with.

I've never used JavaScript, vue or much of anything beyond basic HTML.  I'm a .NET dev who's been tasked with helping out on some web based work and I'm floundering.  So any help is appreciated.

答:
The preferred way to move data between components is with events.

Normally you use props to pass data from a parent component to a child, and events to pass from a child up to a parent.

So the editmethod of C2 can be something like

```<code>edit(item, index, target) {
    const payload = {
        item,
        index,
        target
    };

    this.$emit('edit', payload);
}
</code>```

Then you just have to listen to that event in C1. Notice the @edit attribute: that means when the edit event is fired from component-one, run my "edit" method.

```<code><template>
<div>
   <p>{{ editItemNumber }}</p>
  <component-two @edit="edit" />
</div>

<script>
export default {
data () {
  return {
    editItemNumber: null,
    editBreakdownNumber: null
  };
},

methods: {
    edit(eventPayload) {
        this.editItemNumber = eventPayload.item.editItemNumber
    }
}
</script>
</code>```

If you both C1 and C2 are children of the same parent P the idea is the same, except C1 can't listen directly to C2. Instead P will listen to the edit event and pass the needed changes down to C1 through its props.

The docs on components are really good, pay special attention to the sections on props and custom events.
https://v2.vuejs.org/v2/guide/components.html

Body:
On component1.vue I have

  export default {
    data () {
      return {
        editItemNumber: null,
        editBreakdownNumber: null
      }
    }

On component2.vue I have a table populated by an array

On that table is an edit button.  Among the item in that table is itemNumber value.  Which I need to assign from that particular row clicked to the editItemNumber on component1.vue

  <template slot="actions" scope="row">
Edit
</template>

As you see above originally all of this was on one component and I was just calling to an edit function which repopulated the v-models with that rows contents.  But now with everything split among components I don't know how to edit this to do what I've been tasked with.

I've never used JavaScript, vue or much of anything beyond basic HTML.  I'm a .NET dev who's been tasked with helping out on some web based work and I'm floundering.  So any help is appreciated.

Body:
The preferred way to move data between components is with events.

Normally you use props to pass data from a parent component to a child, and events to pass from a child up to a parent.

So the editmethod of C2 can be something like

edit(item, index, target) {
    const payload = {
        item,
        index,
        target
    };

    this.$emit('edit', payload);
}

Then you just have to listen to that event in C1. Notice the @edit attribute: that means when the edit event is fired from component-one, run my "edit" method.

<template>
<div>
   <p>{{ editItemNumber }}</p>
  <component-two @edit="edit" />
</div>

<script>
export default {
data () {
  return {
    editItemNumber: null,
    editBreakdownNumber: null
  };
},

methods: {
    edit(eventPayload) {
        this.editItemNumber = eventPayload.item.editItemNumber
    }
}
</script>

If you both C1 and C2 are children of the same parent P the idea is the same, except C1 can't listen directly to C2. Instead P will listen to the edit event and pass the needed changes down to C1 through its props.

The docs on components are really good, pay special attention to the sections on props and custom events.
https://v2.vuejs.org/v2/guide/components.html


问:
Query if array column contains one or more values
I have a Rails 5 application, with a PostgreSQL 9.6 database.

The application has Report model, with a department_ids array field, which is defined in schema.rb as:

```<code>t.integer "department_ids", default: [], array: true
</code>```

I need to write a query which returns report rows where the department_ids column contains one or more of a given set of department_ids.

My current workaround is to do this in Ruby with:

```<code>department_ids = [2, 5]

reports = Report.all.select do |report|
  (report.department_ids & department_ids).any?
end
</code>```

However, using select has the downside of returning an Array instead of ActiveRecord::Relation, which means I need to hydrate the filtered results back into ActiveRecord::Relation objects.

```<code>Report.where(id: reports.map(&:id))
</code>```

I'd like to avoid that step, and handle this all in a single query.

How can I write query like this with Active Record?

答:
Something like this should work:

```<code>Report.where('department_ids @> ARRAY[?]::integer[]', [2, 5])
</code>```

You could find more information about array functions and operators here

Body:
I have a Rails 5 application, with a PostgreSQL 9.6 database.

The application has Report model, with a department_ids array field, which is defined in schema.rb as:

t.integer "department_ids", default: [], array: true

I need to write a query which returns report rows where the department_ids column contains one or more of a given set of department_ids.

My current workaround is to do this in Ruby with:

department_ids = [2, 5]

reports = Report.all.select do |report|
  (report.department_ids & department_ids).any?
end

However, using select has the downside of returning an Array instead of ActiveRecord::Relation, which means I need to hydrate the filtered results back into ActiveRecord::Relation objects.

Report.where(id: reports.map(&:id))

I'd like to avoid that step, and handle this all in a single query.

How can I write query like this with Active Record?

Body:
Something like this should work:

Report.where('department_ids @> ARRAY[?]::integer[]', [2, 5])

You could find more information about array functions and operators here


问:
HTTP API Authentification in R via 0auth
I got some problems accessing tracking API via 0auth;

I have sign key, secret and Authorization_key.

Sign key and secret should form a sig file as I understand and authorization_key that should be added as header.

The code:

```<code>auth_info <-
  read.csv2('./Data/auth_info.csv',
            encoding = 'UTF-8',
            stringsAsFactors = F)

express <-
  oauth_app("express", key = 'Ur1475', secret = auth_info$sign_key)

sig <- sign_oauth1.0(express)

order <-
  GET(
    "http://www.express.ru/api/v2/getOrder?orderNumber=WEBN3141018",
    authenticate("Ur1475", auth_info$sign_key),
    add_headers(Authorization = auth_info$auth_key),
    sig
  )

order_info <- content(order)

order_info
</code>```

Returns me auth error;

Official api documentation tells that should be formed md5(client key . URL  . GET params . POST params . sign key).

Also I've looked at 0auth function code it does not use http.
Could it cause the problem?

Could you please comment on how to get data from API via R?

API doc (in russian)): https://www.express.ru/docs/APIExpressRu.pdf

答:
The major of API's (Google, Twitter, Facebook) need a token that you must to obtain from an oauth authentication. Depending from the API's you must to use the functions GETor POST. And you must to provide your key encoded in base64. So what I think you need is:

First: Authenticate.

```<code>if(!require("jsonlite")){library("jsonlite")}
if(!require("httr")){library("httr")}

#Create your own appication key
consumer_key <- "your consumer key" #needed
consumer_secret <- "your consumer secret" #some api's don't need.

#Use basic auth
secret <- jsonlite::base64_enc(paste(consumer_key, consumer_secret, sep = ":"))
req <- httr::POST("https://url.of.your.api/oauth/token", #"oauth" and "token" are not parameters, they are fixed.
                  httr::add_headers(
                    "Authorization" = paste("Basic", gsub("\n", "", secret)),
                    "Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"
                  ),
                  body = "grant_type=client_credentials"
)

#Extract the access token
token <- paste("Bearer", httr::content(req)$access_token)
</code>```

Next: Make a request.

```<code>url<-"http://url.of.your.api/search?parameter1=value&parameter2=value"

req <- httr::POST(url, httr::add_headers("Authorization" = token))

json <- httr::content(req)
json
</code>```

As I said, some API's need GETand others POST, try both.

Body:
I got some problems accessing tracking API via 0auth;

I have sign key, secret and Authorization_key.

Sign key and secret should form a sig file as I understand and authorization_key that should be added as header.

The code:

auth_info <-
  read.csv2('./Data/auth_info.csv',
            encoding = 'UTF-8',
            stringsAsFactors = F)

express <-
  oauth_app("express", key = 'Ur1475', secret = auth_info$sign_key)

sig <- sign_oauth1.0(express)

order <-
  GET(
    "http://www.express.ru/api/v2/getOrder?orderNumber=WEBN3141018",
    authenticate("Ur1475", auth_info$sign_key),
    add_headers(Authorization = auth_info$auth_key),
    sig
  )

order_info <- content(order)

order_info

Returns me auth error;

Official api documentation tells that should be formed md5(client key . URL  . GET params . POST params . sign key).

Also I've looked at 0auth function code it does not use http.
Could it cause the problem?

Could you please comment on how to get data from API via R?

API doc (in russian)): https://www.express.ru/docs/APIExpressRu.pdf

Body:
The major of API's (Google, Twitter, Facebook) need a token that you must to obtain from an oauth authentication. Depending from the API's you must to use the functions GETor POST. And you must to provide your key encoded in base64. So what I think you need is:

First: Authenticate.

if(!require("jsonlite")){library("jsonlite")}
if(!require("httr")){library("httr")}

#Create your own appication key
consumer_key <- "your consumer key" #needed
consumer_secret <- "your consumer secret" #some api's don't need.

#Use basic auth
secret <- jsonlite::base64_enc(paste(consumer_key, consumer_secret, sep = ":"))
req <- httr::POST("https://url.of.your.api/oauth/token", #"oauth" and "token" are not parameters, they are fixed.
                  httr::add_headers(
                    "Authorization" = paste("Basic", gsub("\n", "", secret)),
                    "Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"
                  ),
                  body = "grant_type=client_credentials"
)

#Extract the access token
token <- paste("Bearer", httr::content(req)$access_token)

Next: Make a request.

url<-"http://url.of.your.api/search?parameter1=value&parameter2=value"

req <- httr::POST(url, httr::add_headers("Authorization" = token))

json <- httr::content(req)
json

As I said, some API's need GETand others POST, try both.


问:
How to set Encoding UTF8 in the Powershell script that have HTML tag to show persian characters in HTML page?
I'm a beginner of powershell. I want to create a web page with powershell and I put HTML tags inside powershell script like below:

```<code>Import-Module ActiveDirectory

'<!doctype html>
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"/>
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="//cdn.rawgit.com/morteza/bootstrap-rtl/master/dist/css/bootstrap-rtl.min.css">
    <title>جستجو</title>
</head>

<body>
<div class="container-fluid">
    <h2>فهرست همه کاربران</h2>
    <table class="table table-bordered">
        <thead>
        <tr>
            <th>نام</th>
            <th>نام خانوادگی</th>
            <th>نام کاربری</th>
            <th>واحد سازمانی</th>
            <th>دپارتمان</th>
            <th>عنوان شغلی</th>
            <th>آدرس ایمیل</th>
            <th>شماره تلفن</th>
            <th>وضعیت اکانت</th>

        </tr>
        </thead>
        <tbody>
        <tr>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
            <td><input type="text" class="form-control"></td>
        </tr>
        <tr>
            <td>firstName</td>
            <td>lastName</td>
            <td>userName</td>
            <td>OU</td>
            <td>Department</td>
            <td>jobTitle</td>
            <td>emailAd</td>
            <td>phonNo</td>
            <td>Enabled</td>
        </tr>

        </tbody>
    </table>
</div>

</body>
</html>'
</code>```

I put the HTML tags inside ' ' in powershell script (.ps1 file). It shows everything correct but I want to find a way to set the encoding to UTF8 to show multi language characters. Any help is appreciating.

答:
You mean you want to write whole HTML contents to a file with UTF-8 encoding, right?

Pass the whole string to Out-File -Encoding utf8 command via pipeline.

'<!doctype html>

 ...
' | Out-File -Encoding utf8 -Path index.html
```

Body:
I'm a beginner of powershell. I want to create a web page with powershell and I put HTML tags inside powershell script like below:

Import-Module ActiveDirectory

'<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"/>
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="//cdn.rawgit.com/morteza/bootstrap-rtl/master/dist/css/bootstrap-rtl.min.css">
    <title>جستجو</title>

فهرست همه کاربران

            نام
            نام خانوادگی
            نام کاربری
            واحد سازمانی
            دپارتمان
            عنوان شغلی
            آدرس ایمیل
            شماره تلفن
            وضعیت اکانت

            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">
            <input type="text" class="form-control">

            firstName
            lastName
            userName
            OU
            Department
            jobTitle
            emailAd
            phonNo
            Enabled

'

I put the HTML tags inside ' ' in powershell script (.ps1 file). It shows everything correct but I want to find a way to set the encoding to UTF8 to show multi language characters. Any help is appreciating.

Body:
You mean you want to write whole HTML contents to a file with UTF-8 encoding, right?

Pass the whole string to Out-File -Encoding utf8 command via pipeline.

'<!doctype html>
<html lang="fa">
 ...
</html>' | Out-File -Encoding utf8 -Path index.html


问:
Scheme: how to get first atom from list
I need help with one issue: I can't handle how to get the first atom from the list in SCHEME language. I think I should make a loop, something like "while" and compare each element on boolean (?atom) and print first matched item.
Unfortunately, It's difficult for me to handle scheme syntax.
Please, can you propose any solution for me?</p>

```<code>define func ?atom:
(define (atom? x) (not (or (pair? x) (null? x))))
</code>```

答:
Recursion is not that different from the usual way yo solve problems - you just have to be careful and set some meaningful base cases. For instance, how would you solve this problem in Java? by traversing all the list, and stoping when either 1) we found the element that matches the condition or 2) there are no more elements. This is exactly what we need to do:

```<code>(define (first-atom lst)
  (cond ((null? lst) #f)           ; there are no more elements in the list
        ((atom? (car lst))         ; current element is an atom
         (car lst))                ; return it
        (else                      ; otherwise
         (first-atom (cdr lst))))) ; look in the rest of the list
</code>```

It works as expected:

```<code>(first-atom '((2) 42 (3)))
=> 42
(first-atom '((1) (2)(3)))
=> #f
</code>```

Title: Scheme: how to get first atom from list

Body:
I need help with one issue: I can't handle how to get the first atom from the list in SCHEME language. I think I should make a loop, something like "while" and compare each element on boolean (?atom) and print first matched item.
Unfortunately, It's difficult for me to handle scheme syntax.
Please, can you propose any solution for me?

define func ?atom:
(define (atom? x) (not (or (pair? x) (null? x))))

Body:
Recursion is not that different from the usual way yo solve problems - you just have to be careful and set some meaningful base cases. For instance, how would you solve this problem in Java? by traversing all the list, and stoping when either 1) we found the element that matches the condition or 2) there are no more elements. This is exactly what we need to do:

(define (first-atom lst)
  (cond ((null? lst) #f)           ; there are no more elements in the list
        ((atom? (car lst))         ; current element is an atom
         (car lst))                ; return it
        (else                      ; otherwise
         (first-atom (cdr lst))))) ; look in the rest of the list

It works as expected:

(first-atom '((2) 42 (3)))
=> 42
(first-atom '((1) (2)(3)))
=> #f


问:
CSS align and size
I am designing a layout and I am having two difficulties:

1) Don' t understand why the height of the div where calendar is in (green), is different from its parent.

2) I put a ul inside a div and want to set background color '#d1d2e0' to it (full width). It's going only to the 'Link four'.

div.container
{
width:100%;
margin:0px;
background: #005884;
}

div.left
{
float:left;
width:160px;
margin:0;
padding:1em;
color: #d1d2e0;
background: green;
}

h3.header
{
padding:0;
margin:0;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 color: 5px soldi red;
    display: table-cell;
    vertical-align: middle;
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left"><h3 class="header">Calendar</h3></div>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
</div>
<div class="nav">
  <ul>
    <li class="nav">Link one</li>
    <li class="nav">Link two</li>
    <li class="nav">Link three</li>
    <li class="nav">Link four</li>
  </ul>
</div>
<div class="form"></div>
<div class="content"></div>
<div class="footer"></div></code>```

Regards,
Elio Fernandes

答:
1

You should be using border-box to make sizing easier:

```<code>* {
    box-sizing: border-box;
}
</code>```

Then give your .container a height and tell it's children to inherit it.

2

Next, get rid of display: table-cell; on div.nav and actually give it a background color. I don't see where you were trying to set it, at all.

```<code>background: #d1d2e0;
</code>```

Also, this property makes no sense:

```<code>color: 5px solid red;
</code>```

It should be either border: 5px solid red; or color: red;.

* {
    box-sizing: border-box;
}

div.container
{
width:100%;
margin:0px;
background: #005884;
height: 62px;
}

div.left
{
float:left;
width:160px;
margin:0;
/*padding:1em; don't need this */
color: #d1d2e0;
background: green;
height: 100%;
}

h3.header
{
padding: 0 0 0 1em;
margin:0;
line-height: 62px;
height: 62px;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 /*color: 5px solid red; was this supposed to be "border" ? */
    /*display: table-cell; don't need this */
    vertical-align: middle;
    background: #d1d2e0; /* you weren't setting this */
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left"><h3 class="header">Calendar</h3></div>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
</div>
<div class="nav">
  <ul>
    <li class="nav">Link one</li>
    <li class="nav">Link two</li>
    <li class="nav">Link three</li>
    <li class="nav">Link four</li>
  </ul>
</div>
<div class="form"></div>
<div class="content"></div>
<div class="footer"></div></code>```

Title: CSS align and size

Body:
I am designing a layout and I am having two difficulties:

1) Don' t understand why the height of the div where calendar is in (green), is different from its parent.

2) I put a ul inside a div and want to set background color '#d1d2e0' to it (full width). It's going only to the 'Link four'.

div.container
{
width:100%;
margin:0px;
background: #005884;
}

div.left
{
float:left;
width:160px;
margin:0;
padding:1em;
color: #d1d2e0;
background: green;
}

h3.header
{
padding:0;
margin:0;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 color: 5px soldi red;
    display: table-cell;
    vertical-align: middle;
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}

Calendar

    Year<select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>

Link one

Link two

Link three

Link four

Regards,
Elio Fernandes

Body:
1

You should be using border-box to make sizing easier:

* {
    box-sizing: border-box;
}

Then give your .container a height and tell it's children to inherit it.

2

Next, get rid of display: table-cell; on div.nav and actually give it a background color. I don't see where you were trying to set it, at all.

background: #d1d2e0;

Also, this property makes no sense:

color: 5px solid red;

It should be either border: 5px solid red; or color: red;.

* {
    box-sizing: border-box;
}

div.container
{
width:100%;
margin:0px;
background: #005884;
height: 62px;
}

div.left
{
float:left;
width:160px;
margin:0;
/*padding:1em; don't need this */
color: #d1d2e0;
background: green;
height: 100%;
}

h3.header
{
padding: 0 0 0 1em;
margin:0;
line-height: 62px;
height: 62px;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 /*color: 5px solid red; was this supposed to be "border" ? */
    /*display: table-cell; don't need this */
    vertical-align: middle;
    background: #d1d2e0; /* you weren't setting this */
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}

<div class="container">
  <div class="left"><h3 class="header">Calendar</h3></div>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
</div>
<div class="nav">
  <ul>
    <li class="nav"><a href="#">Link one</a></li>
    <li class="nav"><a href="#">Link two</a></li>
    <li class="nav"><a href="#">Link three</a></li>
    <li class="nav"><a href="#" class="last">Link four</a></li>
  </ul>
</div>
<div class="form"></div>
<div class="content"></div>
<div class="footer"></div>


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
Another option would be to create a helper function:

```<code>def first_true(*args):
    true_vals = (arg for arg in args if arg[0])
    return next(true_vals)[1]

name = first_true((a and b and c, 'first'),
                  (a and b and not c, 'second'),
                  (a and not b and c, 'third'),
                  (a and not b and not c, 'fourth'),
                  (not a and b and c, 'fifth'),
                  (not a and b and not c, 'sixth'),
                  (not a and not b and c, 'seventh'),
                  (not a and not b and not c, 'eighth'))
</code>```

This method assumes that one of the tests passed in will be true. It could also be made lazier with lambdas.

ContentLicense: CC BY-SA 2.5

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
Another option would be to create a helper function:

def first_true(*args):
    true_vals = (arg for arg in args if arg[0])
    return next(true_vals)[1]

name = first_true((a and b and c, 'first'),
                  (a and b and not c, 'second'),
                  (a and not b and c, 'third'),
                  (a and not b and not c, 'fourth'),
                  (not a and b and c, 'fifth'),
                  (not a and b and not c, 'sixth'),
                  (not a and not b and c, 'seventh'),
                  (not a and not b and not c, 'eighth'))

This method assumes that one of the tests passed in will be true. It could also be made lazier with lambdas.


问:
(PHP) after clicking the approve button next form should appear
Iam working on this website where I have to output form data as a table from the database. I have also included approve and disapprove buttons beside the form. My problem is when ever i click the approve button the current table, the next table should appear.
Here is the code.

```<code>  echo '<table width = "30%" cellpadding = "2" cellspacing ="2" border = "2px">
                <tr>
                    <td><strong> ID</strong></td>
                    <td><strong> username</strong> </td>
                    <td><strong> email</strong> </td>
                    <td><strong> EC. no</strong> </td>
                    <td><strong> GradePay</strong> </td>
                    <td><strong> Division</strong> </td>
                    <td><strong> ProjectCode</strong> </td>
                    <td><strong> purpose of jourmey</strong> </td>
                    <td><strong> TA</strong> </td>
                    <td><strong> Address</strong> </td>
                    <td><strong> Telephone</strong> </td>
                    <td><strong> date of journey</strong> </td>
                    <td><strong> return date</strong> </td>
                    <td><strong> From </strong> </td>
                    <td><strong> To</strong> </td>
                </tr>
                <tr>
                    <td>'.$row['ID'].'</td>
                    <td>'.$row['username'].'</td>
                    <td>'.$row['email'].'</td>
                    <td>'.$row['ecno'].'</td>
                    <td>'.$row['gradepay'].'</td>
                    <td>'.$row['division'].'</td>
                    <td>'.$row['code'].'</td>
                    <td>'.$row['journey'].'</td>
                    <td>'.$row['ta'].'</td>
                    <td>'.$row['address'].'</td>
                    <td>'.$row['tel'].'</td>
                    <td>'.$row['doj'].'</td>
                    <td>'.$row['dor'].'</td>
                    <td>'.$row['fc'].'</td>
                    <td>'.$row['tc'].'</td>
                    <td>  <input type= "submit" name="submit" value="approve" onclick ="myFunction()"></td>
                    <td>  <input type= "submit" name="submit1" value="decline" onclick ="myFunction1()"></td>
                </tr>
                </table>';

    }
}
}
?>
</code>```

The image of this output

as shown in the image whenever i click the approve button , the next form should appear and this should move away from the page.
please help me with this problem

答:
```<code>function myfunction(){
header("location:nextform.php");
}
</code>```

I think this is what u want...

Body:
Iam working on this website where I have to output form data as a table from the database. I have also included approve and disapprove buttons beside the form. My problem is when ever i click the approve button the current table, the next table should appear.
Here is the code.

  echo '

                     ID
                     username
                     email
                     EC. no
                     GradePay
                     Division
                     ProjectCode
                     purpose of jourmey
                     TA
                     Address
                     Telephone
                     date of journey
                     return date
                     From
                     To

                    '.$row['ID'].'
                    '.$row['username'].'
                    '.$row['email'].'
                    '.$row['ecno'].'
                    '.$row['gradepay'].'
                    '.$row['division'].'
                    '.$row['code'].'
                    '.$row['journey'].'
                    '.$row['ta'].'
                    '.$row['address'].'
                    '.$row['tel'].'
                    '.$row['doj'].'
                    '.$row['dor'].'
                    '.$row['fc'].'
                    '.$row['tc'].'
                      <input type= "submit" name="submit" value="approve" onclick ="myFunction()">
                      <input type= "submit" name="submit1" value="decline" onclick ="myFunction1()">

';

    }
}
}
?>

The image of this output

as shown in the image whenever i click the approve button , the next form should appear and this should move away from the page.
please help me with this problem

Body:
function myfunction(){
header("location:nextform.php");
}

I think this is what u want...


问:
Differences between .call(this) and () on a immediately self invoking function
I came across this code in one of our online AngularJS apps, and was wondering what this does. Is it different than just calling a immediately self invoking function with parenthesis.

```<code>(function() {

}).call(this); // What was in TFS
</code>```

vs

```<code>(function() {

})(); // Are these the same?
</code>```

Is there any benefits of calling one over the other, or is it merely coding preference?

答:
They're very different. The first uses whatever the current this is (at global scope, this is a reference to the global object; in other scopes, it could be just about anything). The second will use the default this, which is a reference to the global object in loose mode but undefined in strict mode.

Gratuitous example :-) :

console.log("At global scope:");
(function() {
  console.log(this === window); // true
}).call(this); // What was in TFS
(function() {
  console.log(this === window); // true
})();
(function() {
  "use strict";
  console.log(this === window); // false (this === undefined)
})();

console.log("Not at global scope:");
(function() {
  (function() {
    console.log(this === window); // false
  }).call(this); // What was in TFS
  (function() {
    console.log(this === window); // true
  })();
}).call({});// Using something other than the default```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

Body:
I came across this code in one of our online AngularJS apps, and was wondering what this does. Is it different than just calling a immediately self invoking function with parenthesis.

(function() {

}).call(this); // What was in TFS

vs

(function() {

})(); // Are these the same?

Is there any benefits of calling one over the other, or is it merely coding preference?

Body:
They're very different. The first uses whatever the current this is (at global scope, this is a reference to the global object; in other scopes, it could be just about anything). The second will use the default this, which is a reference to the global object in loose mode but undefined in strict mode.

Gratuitous example :-) :

console.log("At global scope:");
(function() {
  console.log(this === window); // true
}).call(this); // What was in TFS
(function() {
  console.log(this === window); // true
})();
(function() {
  "use strict";
  console.log(this === window); // false (this === undefined)
})();

console.log("Not at global scope:");
(function() {
  (function() {
    console.log(this === window); // false
  }).call(this); // What was in TFS
  (function() {
    console.log(this === window); // true
  })();
}).call({});// Using something other than the default

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


问:
bootstrap multiple modal structure
I have a structure as below. Modal1 for displaying my content and Modal2 pops up when a alert modal when deleting.

I have first modal1 loading in Ajax

Second modal is not Ajax call.

Is it advisable to have this structure with multiple modals? Otherwise what is the alternative to get alert message in a modal?
Because right now I am facing weird issues with closing modals and events. It is working some times and some time it doesn't . Not sure what causes the weirdness.
Any leads on do and don'ts will be helpful.
https://plnkr.co/edit/ZaUfPntbVp3QMubaw8xg?p=preview

```<code><button type="button" class="btn btn-info btn-lg" data-toggle="modal"
data-target="#myModal">Open Modal</button>
 <!-- Modal -->
 <div class="modal fade" id="myModal" role="dialog">
 <div class="modal-dialog">

 <!-- Modal content-->
<div class="modal-content">
  <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
  <h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
  <p>Some text in the modal.</p>
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal</button>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</code>```

```<code>  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">Alert : Are you sure?</h4>
    </div>
    <div class="modal-body">
      <p>Some text in the modal.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
  </div>

</div>
</code>```

答:
Nested modals are not supported in bootstrap 3 that's why you are getting wired results

From bootstrap docs:

Multiple open modals not supported
  Be sure not to open a modal while another is still visible. Showing more than one modal at a time requires custom code.

Instead of using a second modal You can use an alert to show notification msg inside the first modal

Title: bootstrap multiple modal structure

Body:
I have a structure as below. Modal1 for displaying my content and Modal2 pops up when a alert modal when deleting.

I have first modal1 loading in Ajax

Second modal is not Ajax call.

Is it advisable to have this structure with multiple modals? Otherwise what is the alternative to get alert message in a modal?
Because right now I am facing weird issues with closing modals and events. It is working some times and some time it doesn't . Not sure what causes the weirdness.
Any leads on do and don'ts will be helpful.
https://plnkr.co/edit/ZaUfPntbVp3QMubaw8xg?p=preview

<button type="button" class="btn btn-info btn-lg" data-toggle="modal"
data-target="#myModal">Open Modal</button>

  <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal</button>

  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

      <button type="button" class="close" data-dismiss="modal">×</button>

Alert : Are you sure?

Some text in the modal.

      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


问:
Zabbix Upgrade - Database upgrade failed
EDIT : I should have created this post on ServerFault, wrong tab, sorry.

I'm trying to upgrade my Zabbix Server today (MySQL DB).
Current version is 2.4.8, I want to update it to 3.4.4

Installation went well. When I start the zabbix-server process, the database starts upgrading, and it then stops with the following error message :

```<code>[Z3005] query failed: [1034] Incorrect key file for table 'alerts'; try to repair it [alter table alerts add p_eventid bigint unsigned]
</code>```

So, I stopped zabbix-server, did the "alter table alerts add p_eventid bigint unsigned", restarted zabbix-server, and now got this error message :

```<code>[Z3005] query failed: [1060] Duplicate column name 'p_eventid' [alter table alerts add p_eventid bigint unsigned]
</code>```

Which is a bit troubling for me, as the error message is different, but the proposed solution is still the same, and has been done already.

I did some research, found out this ZBX bug report that can be useful but I have no idea how to apply the workaround, as I'm no expert in SQL. As far as I can tell, I have a missing index in the alerts table (alerts_7). I tried to create it with the following command, after googling a bit :

```<code>create INDEX on alerts (p_eventid) USING BTREE;
</code>```

Still got an error (the second one).

Anyone had that situation already, and found out how to solve it ?

答:
The part in the square brackets was not a suggestion, it was the command that was attempted. Now it fails because the column already exists.

In this case, it might be enough to drop that column and start Zabbix server again. Make sure to have database backup before you even started the upgrade.

Body:
EDIT : I should have created this post on ServerFault, wrong tab, sorry.

I'm trying to upgrade my Zabbix Server today (MySQL DB).
Current version is 2.4.8, I want to update it to 3.4.4

Installation went well. When I start the zabbix-server process, the database starts upgrading, and it then stops with the following error message :

[Z3005] query failed: [1034] Incorrect key file for table 'alerts'; try to repair it [alter table alerts add p_eventid bigint unsigned]

So, I stopped zabbix-server, did the "alter table alerts add p_eventid bigint unsigned", restarted zabbix-server, and now got this error message :

[Z3005] query failed: [1060] Duplicate column name 'p_eventid' [alter table alerts add p_eventid bigint unsigned]

Which is a bit troubling for me, as the error message is different, but the proposed solution is still the same, and has been done already.

I did some research, found out this ZBX bug report that can be useful but I have no idea how to apply the workaround, as I'm no expert in SQL. As far as I can tell, I have a missing index in the alerts table (alerts_7). I tried to create it with the following command, after googling a bit :

create INDEX on alerts (p_eventid) USING BTREE;

Still got an error (the second one).

Anyone had that situation already, and found out how to solve it ?


问:
Sports Simple Rating System Implementaion in R
I am attempting to implement the sports Simple Rating System in R and am having a lot of trouble.  I can do it in excel, which you can see in this video: http://www.screencast.com/users/Sports-Reference/folders/PFR/media/cea8d1e3-ed91-431f-a0df-1336c03b1268

To test this out I am using the same data (basically) as in the video, which you can access here: https://drive.google.com/file/d/0Bzr6jaapQdMRUFhpU0h4NDBNaTQ/view?usp=sharing

The first lines lines of the data frame could be built like this, but there are 206 records:

```<code>dat$Week <- c(1,1,1)
dat$Team <- c("Arizona Cardinals", "Arizona Cardinals", "Arizona Cardinals")
dat$Location <- c("HOME", "AWAY", "HOME")
dat$Opponent <- c("San Francisco 49ers", "Jacksonville Jaguars", "Indianapolis Colts")
dat$Points.For <- c(16, 31, 10)
dat$Points.Against <- c(20, 17, 31)
</code>```

I set up the data with the following code:

```<code>library(dplyr)
## Load data
dat <- read.csv("data/footballsrstestdata.csv", stringsAsFactors = FALSE)

## Delete last row
dat <- dat[-207,]

## Create MOV and adjusted MOV variables
dat <- mutate(dat, mov = Points.For - Points.Against)
dat <- mutate(dat, adjMOV = mapply(function(x, y)
  {if(y == "HOME") x - 1.3529 else x + 1.3529}, dat$mov, dat$Location))

## Create SRS df
srsTable <- data.frame(teams = unique(dat$Team), stringsAsFactors = FALSE)

## Create average MOV
srsTable <- mutate(srsTable,
                   avgAdjMOV = sapply(teams, function(x) {
                     mean(dat$adjMOV[dat$Team == x])
                   }, USE.NAMES = FALSE))

## Create placeholder varaiables
dat$oSRS <- NA
srsTable$SOS <- NA
srsTable$SRS <- NA
</code>```

In excel, you would have two sheets that are referenced to each other creating a circular reference that iterates until they reach stability. Each line in the games data would have the opponent's SRS, and on the team SRS sheet, the SRS would be equal to the avgAdjMOV + the average opponents SRS from the game data sheets. I am assuming that I need to create a function with a series of equations and use the optim function to solve them, but can't figure how to set this up so that they work over both the game data dataframe and the teams dataframe simultaneously.

Does anyone have any ideas on how to proceed?
Thank you!

答:
So I suggest setting up everything as a System of Equations Problem :

Ratings = adjMOV+(1/nGames)*Sched*Ratings

Where Ratings is a size N vector with the ratings of each team, adjMOV a size N vector with the adjusted Margin of Victory for each team, and Sched a NxN matrix of how many times each team faced each other. The order of rows in the vectors and rows and columns in the matrix should be the same. Now with some linear algebra your system of equations should look like:

(I-(1/nGames)*Sched)*Ratings = adjMOV

Now it is easy to solve it using any Non-Linear Solver, I have used the lsei() method in the limSolve package, so your code should look like:

```<code>library(limSolve)
A = (diag(N)-(1/nGames)*Sched)
b = adjMOV
solution = lsei(A=A,B=b)
Ratings = solution$X
</code>```

I know it has been a more than a year but I hope this helps.

Body:
I am attempting to implement the sports Simple Rating System in R and am having a lot of trouble.  I can do it in excel, which you can see in this video: http://www.screencast.com/users/Sports-Reference/folders/PFR/media/cea8d1e3-ed91-431f-a0df-1336c03b1268

To test this out I am using the same data (basically) as in the video, which you can access here: https://drive.google.com/file/d/0Bzr6jaapQdMRUFhpU0h4NDBNaTQ/view?usp=sharing

The first lines lines of the data frame could be built like this, but there are 206 records:

dat$Week <- c(1,1,1)
dat$Team <- c("Arizona Cardinals", "Arizona Cardinals", "Arizona Cardinals")
dat$Location <- c("HOME", "AWAY", "HOME")
dat$Opponent <- c("San Francisco 49ers", "Jacksonville Jaguars", "Indianapolis Colts")
dat$Points.For <- c(16, 31, 10)
dat$Points.Against <- c(20, 17, 31)

I set up the data with the following code:

library(dplyr)
## Load data
dat <- read.csv("data/footballsrstestdata.csv", stringsAsFactors = FALSE)

## Delete last row
dat <- dat[-207,]

## Create MOV and adjusted MOV variables
dat <- mutate(dat, mov = Points.For - Points.Against)
dat <- mutate(dat, adjMOV = mapply(function(x, y)
  {if(y == "HOME") x - 1.3529 else x + 1.3529}, dat$mov, dat$Location))

## Create SRS df
srsTable <- data.frame(teams = unique(dat$Team), stringsAsFactors = FALSE)

## Create average MOV
srsTable <- mutate(srsTable,
                   avgAdjMOV = sapply(teams, function(x) {
                     mean(dat$adjMOV[dat$Team == x])
                   }, USE.NAMES = FALSE))

## Create placeholder varaiables
dat$oSRS <- NA
srsTable$SOS <- NA
srsTable$SRS <- NA

In excel, you would have two sheets that are referenced to each other creating a circular reference that iterates until they reach stability. Each line in the games data would have the opponent's SRS, and on the team SRS sheet, the SRS would be equal to the avgAdjMOV + the average opponents SRS from the game data sheets. I am assuming that I need to create a function with a series of equations and use the optim function to solve them, but can't figure how to set this up so that they work over both the game data dataframe and the teams dataframe simultaneously.

Does anyone have any ideas on how to proceed?
Thank you!

Body:
So I suggest setting up everything as a System of Equations Problem :

Ratings = adjMOV+(1/nGames)*Sched*Ratings

Where Ratings is a size N vector with the ratings of each team, adjMOV a size N vector with the adjusted Margin of Victory for each team, and Sched a NxN matrix of how many times each team faced each other. The order of rows in the vectors and rows and columns in the matrix should be the same. Now with some linear algebra your system of equations should look like:

(I-(1/nGames)*Sched)*Ratings = adjMOV

Now it is easy to solve it using any Non-Linear Solver, I have used the lsei() method in the limSolve package, so your code should look like:

library(limSolve)
A = (diag(N)-(1/nGames)*Sched)
b = adjMOV
solution = lsei(A=A,B=b)
Ratings = solution$X

I know it has been a more than a year but I hope this helps.


问:
warning: Unable to read symbols
When I try to run my app in iOS 4.2.1, I am getting following warning messages;

```<code>[Switching to thread 11523]
[Switching to thread 11523]
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
continue
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
warning: Unable to read symbols for /xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/info/dns.so (file not found).</code>```

I don't know what is happening here.

Is there any issues, when we get this kind of warning messages ?

答:
The problem is that Xcode and the debugger expect iOS 4.2, but your device runs iOS 4.2.1.

What you can do to avoid this error; Let Xcode gather the needed symbols from your device (you may have to delete previous ones). After this, it will work without any problem.

Title: warning: Unable to read symbols

Body:
When I try to run my app in iOS 4.2.1, I am getting following warning messages;

[Switching to thread 11523]
[Switching to thread 11523]
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
continue
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
`/xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/dyld' has changed; re-reading symbols.
warning: Unable to read symbols for /xcode iOS/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/info/dns.so (file not found).

I don't know what is happening here.

Is there any issues, when we get this kind of warning messages ?


问:
Pagination keeps showing the same portion of SQL data
I have a really large data set from SQL that i need to paginate.

I have an issue with my pagination code. The code does show the page number in the URL and it does give me pagination hyperlinks at the bottom of the table. However, any page I click on, it outputs the same exact portion of the sql datatable.

Also, I'm doing this in wordpress.

```<code>// define how many results you want per page
$results_per_page = 10;

// find out the number of results stored in database
$sql='SELECT * FROM ETF';
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);

// determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);

// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
  $page = 1;
} else {
  $page = $_GET['page'];
}

// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;

// retrieve selected results from database and display them on page
$sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;

$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '<br>';
}

// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
  echo '<a href="index.php/stocks/sec-forms/?page=' . $page . '">' . $page. '</a>';
}
</code>```

答:
You should change

```<code>$sql='SELECT * FROM ETF';
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);
</code>```

to something like this

```<code>$count = mysqli_fetch_assoc(mysqli_query($con,"SELECT COUNT(*) AS RC FROM ETF"));
$number_of_results=$count['RC'];
</code>```

because it is faster to get count from mysql (index if its a large table) instead of fetching all table data (because SELECT *...) for looping trough it just for row counting.

```<code>// retrieve selected results from database and display them on page
$sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;
</code>```

You using good query, but using wrong function to get its results.

Query should be

```<code>$sql='SELECT * FROM ETF LIMIT ' . $results_per_page . "," .$this_page_first_result;
</code>```

or:

```<code>$sql='SELECT * FROM ETF LIMIT ' . $results_per_page . " OFFSET " .$this_page_first_result;
</code>```

Both of these work.

Change

```<code>while($row = mysqli_fetch_array($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '<br>';
}
</code>```

to

```<code>while($row = mysqli_fetch_assoc($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '<br>';
}
</code>```

because "mysqli_fetch_array" fetch array width numbered indexes (for example 0, 1, 2...) not a text ones you are trying to use, but "mysqli_fetch_assoc" does that you need.

Full code should be

```<code><?php
$con=mysqli_connect('your server','login to database','database logins password','database name');
// define how many results you want per page
$results_per_page=10;
// find out the number of results stored in database
$count=mysqli_fetch_assoc(mysqli_query($con,"SELECT COUNT(*) AS RC FROM ETF"));
$number_of_results=$count['RC'];
// determine number of total pages available
$number_of_pages=ceil($number_of_results/$results_per_page);
// determine which page number visitor is currently on
if(!isset($_GET['page']))
{
    $page=1;
}
else
{
    $page=$_GET['page'];
}
// determine the sql LIMIT starting number (OFFSET) for the results on the displaying page
$this_page_first_result=($page-1)*$results_per_page;
// retrieve selected results from database and display them on page
$sql="SELECT * FROM ETF LIMIT $results_per_page,$this_page_first_result";
$result=mysqli_query($con, $sql);
// Loop to show results
while($row = mysqli_fetch_assoc($result))
{
    echo $row['ETF'].' '.$row['ETF NAME'].'<br>';
}
// display the links to the pages
for($page=1;$page<=$number_of_pages;$page++)
{
    echo'<a href="?page='.$page.'">'.$page.'</a> ';
}
mysqli_close($con);
    ?>
</code>```

Body:
I have a really large data set from SQL that i need to paginate.

I have an issue with my pagination code. The code does show the page number in the URL and it does give me pagination hyperlinks at the bottom of the table. However, any page I click on, it outputs the same exact portion of the sql datatable.

Also, I'm doing this in wordpress.

// define how many results you want per page
$results_per_page = 10;

// find out the number of results stored in database
$sql='SELECT * FROM ETF';
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);

// determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);

// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
  $page = 1;
} else {
  $page = $_GET['page'];
}

// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;

// retrieve selected results from database and display them on page
$sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;

$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '
';
}

// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
  echo '' . $page. '';
}

Body:
You should change

$sql='SELECT * FROM ETF';
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);

to something like this

$count = mysqli_fetch_assoc(mysqli_query($con,"SELECT COUNT(*) AS RC FROM ETF"));
$number_of_results=$count['RC'];

because it is faster to get count from mysql (index if its a large table) instead of fetching all table data (because SELECT *...) for looping trough it just for row counting.

// retrieve selected results from database and display them on page
$sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;

You using good query, but using wrong function to get its results.

Query should be

$sql='SELECT * FROM ETF LIMIT ' . $results_per_page . "," .$this_page_first_result;

or:

$sql='SELECT * FROM ETF LIMIT ' . $results_per_page . " OFFSET " .$this_page_first_result;

Both of these work.

Change

while($row = mysqli_fetch_array($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '<br>';
}

to

while($row = mysqli_fetch_assoc($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '<br>';
}

because "mysqli_fetch_array" fetch array width numbered indexes (for example 0, 1, 2...) not a text ones you are trying to use, but "mysqli_fetch_assoc" does that you need.

Full code should be

<?php
$con=mysqli_connect('your server','login to database','database logins password','database name');
// define how many results you want per page
$results_per_page=10;
// find out the number of results stored in database
$count=mysqli_fetch_assoc(mysqli_query($con,"SELECT COUNT(*) AS RC FROM ETF"));
$number_of_results=$count['RC'];
// determine number of total pages available
$number_of_pages=ceil($number_of_results/$results_per_page);
// determine which page number visitor is currently on
if(!isset($_GET['page']))
{
    $page=1;
}
else
{
    $page=$_GET['page'];
}
// determine the sql LIMIT starting number (OFFSET) for the results on the displaying page
$this_page_first_result=($page-1)*$results_per_page;
// retrieve selected results from database and display them on page
$sql="SELECT * FROM ETF LIMIT $results_per_page,$this_page_first_result";
$result=mysqli_query($con, $sql);
// Loop to show results
while($row = mysqli_fetch_assoc($result))
{
    echo $row['ETF'].' '.$row['ETF NAME'].'<br>';
}
// display the links to the pages
for($page=1;$page<=$number_of_pages;$page++)
{
    echo'<a href="?page='.$page.'">'.$page.'</a> ';
}
mysqli_close($con);
    ?>


问:
Image not load in Google map marker
I am trying to load image in Google map that I have fetched from Firebase Storage in marker window. The thing is, when I try to load it with Glide or Picasso, it's not loading in Google map. Every log I have in the code is visible in logcat. Am I doing something wrong here?

Here is my code

```<code>public class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    Context context;
    LayoutInflater inflater;
    private DatabaseReference mDatabase;
    private StorageReference storageReference;
    private Chalet chalet;
    private boolean query;
    private ImageView img;
    private String lat;
    private String log;

    public MapInfoWindowAdapter(Context context, LayoutInflater inflater) {
        this.context = context;
        this.inflater = inflater;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {

        mDatabase = FirebaseDatabase.getInstance().getReference().child("chalets");
        storageReference=FirebaseStorage.getInstance().getReference();

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View v = inflater.inflate(R.layout.marker_tag,null);

       final LatLng latlng = marker.getPosition();
       Double doubleLat = latlng.latitude;

         lat = String.valueOf(latlng.latitude);
         log = String.valueOf(latlng.longitude);
        Log.i("MarkerPostion",lat);

        img = (ImageView) v.findViewById(R.id.chaletImg);

       // final TextView textView = (TextView) v.findViewById(R.id.markerText);
        final Semaphore semaphore = new Semaphore(0);
       mDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Log.i("MarkerPostion","112211");
                for (DataSnapshot snapm: dataSnapshot.getChildren()) {
                    Log.i("MarkerPostion",snapm.child("latitude").getValue().toString());
                    Log.i("Key",snapm.getKey());
                    if ( lat.equals(snapm.child("latitude").getValue().toString()) && log.equals(snapm.child("longitude").getValue().toString()) ){
                        chalet = snapm.getValue(Chalet.class);
                        Log.i("MarkerPostion","9999");
                        break;
                    }
                }

                storageReference = FirebaseStorage.getInstance().getReference().child(chalet.getOwnerID()).child(chalet.getChaletNm()).child("1");
                storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {

                    @Override
                    public void onSuccess(Uri uri) {
                        Picasso.with(context).load(uri).into(img);
                        Log.i("MarkerPostion","2222");
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return v;
    }
}
</code>```

Here is my XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/markerFrame">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/chaletImg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
             />

    </LinearLayout>

</FrameLayout>
</code>```

答: Try to make the LinearLayout in your xml the root view of the layout. I never realized why, but I faced problems too when I dealt with a custom InfoWindowAdapter without an obvious explanation/bug. Using a LinearLayout as root view of the xml solved my issues.

Title: Image not load in Google map marker

Body:
I am trying to load image in Google map that I have fetched from Firebase Storage in marker window. The thing is, when I try to load it with Glide or Picasso, it's not loading in Google map. Every log I have in the code is visible in logcat. Am I doing something wrong here?

Here is my code

public class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    Context context;
    LayoutInflater inflater;
    private DatabaseReference mDatabase;
    private StorageReference storageReference;
    private Chalet chalet;
    private boolean query;
    private ImageView img;
    private String lat;
    private String log;

    public MapInfoWindowAdapter(Context context, LayoutInflater inflater) {
        this.context = context;
        this.inflater = inflater;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {

        mDatabase = FirebaseDatabase.getInstance().getReference().child("chalets");
        storageReference=FirebaseStorage.getInstance().getReference();

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View v = inflater.inflate(R.layout.marker_tag,null);

       final LatLng latlng = marker.getPosition();
       Double doubleLat = latlng.latitude;

         lat = String.valueOf(latlng.latitude);
         log = String.valueOf(latlng.longitude);
        Log.i("MarkerPostion",lat);

        img = (ImageView) v.findViewById(R.id.chaletImg);

       // final TextView textView = (TextView) v.findViewById(R.id.markerText);
        final Semaphore semaphore = new Semaphore(0);
       mDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Log.i("MarkerPostion","112211");
                for (DataSnapshot snapm: dataSnapshot.getChildren()) {
                    Log.i("MarkerPostion",snapm.child("latitude").getValue().toString());
                    Log.i("Key",snapm.getKey());
                    if ( lat.equals(snapm.child("latitude").getValue().toString()) && log.equals(snapm.child("longitude").getValue().toString()) ){
                        chalet = snapm.getValue(Chalet.class);
                        Log.i("MarkerPostion","9999");
                        break;
                    }
                }

                storageReference = FirebaseStorage.getInstance().getReference().child(chalet.getOwnerID()).child(chalet.getChaletNm()).child("1");
                storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {

                    @Override
                    public void onSuccess(Uri uri) {
                        Picasso.with(context).load(uri).into(img);
                        Log.i("MarkerPostion","2222");
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return v;
    }
}

Here is my XML file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/markerFrame">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/chaletImg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
             />

    </LinearLayout>

</FrameLayout>


问:
CSS: :focus:before doesn't work
I have a Slidemenu within a Sidemenu, when i'm clicking on a text label, some content shows up. :before the text label, i'm having some Arrows, that i want to rotate 90deg, when clicked.

Code:

```<code>li.textClass:focus:before {
  transform: rotate(90deg) !important;
}
</code>```

if i change :focus to :active  it works untill i release the left mouse button, but it should stay rotated.... how do i fix this? i can't get it to work.

答:
Can you provide a little more detail of what you are trying to do?  Maybe an example of your html block?

For an li element, you should not use focus (that would be better for inputs & textareas) - I would use hover.

See full example in this fiddle:
https://jsfiddle.net/wexwnc9b/

HTML:

```<code>    <ul>
      <li class="textClass">TextClass</li>
    </ul>
</code>```

CSS:

```<code>    li.textClass {
      position: relative;
      list-style: none;
      padding: 0 30px;
    }

    li.textClass::before {
      content: 'X';
      position: absolute;
      top: 0;
      left: 0;
    }

    li.textClass:hover::before {
      transform: rotate(90deg);
    }
</code>```

Title: CSS: :focus:before doesn't work

Body:
I have a Slidemenu within a Sidemenu, when i'm clicking on a text label, some content shows up. :before the text label, i'm having some Arrows, that i want to rotate 90deg, when clicked.

Code:

li.textClass:focus:before {
  transform: rotate(90deg) !important;
}

if i change :focus to :active  it works untill i release the left mouse button, but it should stay rotated.... how do i fix this? i can't get it to work.

Body:
Can you provide a little more detail of what you are trying to do?  Maybe an example of your html block?

For an li element, you should not use focus (that would be better for inputs & textareas) - I would use hover.

See full example in this fiddle:
https://jsfiddle.net/wexwnc9b/

HTML:

    <ul>
      <li class="textClass">TextClass</li>
    </ul>

CSS:

    li.textClass {
      position: relative;
      list-style: none;
      padding: 0 30px;
    }

    li.textClass::before {
      content: 'X';
      position: absolute;
      top: 0;
      left: 0;
    }

    li.textClass:hover::before {
      transform: rotate(90deg);
    }


问:
static variables in c
Static variables when declared in a file cannot be accessed from outside the file.
But if we declare a static variable inside a file and a global pointer and then assign the address of the static variable to the pointer and then externing the pointer, it can be accessed.

So is it right saying that static variables can't be accessed directly but it can be accessed indirectly using global pointers and then externing?

答: The static keyword in 'C' just restricts the scope of the variable to that specific translation unit(i.e that 'C' file.).In otherwords it restricts the linkage of that variable.and nothing else.and In C all static,global and auto variables can be accessed via pointers in their lifetime.there is not way to prevent that.</p>

OwnerDisplayName: maddy

Title: static variables in c


问:
Is my understanding of async/await correct?
from what I understand the code below should eventually retrieve the string classification while running other code.

```<code>[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    string classification = GetClassification(property);
    // GetClassification() runs a complex calculation but we don't need
    // the result right away so the code can do other things here related to property

    // ... code removed for brevity

    property.ClassificationCode = await classification;
    // all other code has been completed and we now need the classification

    db.Properties.Add(property);
    db.SaveChanges();
    return RedirectToAction("Details", new { id = property.UPRN });
}

public string GetClassification(Property property)
{
    // do complex calculation
    return classification;
}
</code>```

This should work the same way as in the below code from Matthew Jones' article

```<code>public async Task<string> GetNameAndContent()
{
    var nameTask = GetLongRunningName(); //This method is asynchronous
    var content = GetContent(); //This method is synchronous
    var name = await nameTask;
    return name + ": " + content;
}
</code>```

However I get an error on await classification: 'string' does not contain a definition for 'GetAwaiter'

I'm unsure why this is happening.

Additionally, according to MSDN docs for expensive calculations I should instead be using:

```<code>property.ClassificationCode = await Task.Run(() => GetClassification(property));
</code>```

Is this actually achieving what I want or is this just running synchronously anyway?

Thanks in advance for help.

答:
To have the same as in the code from Matthew Jones you have to change your code to

```<code>[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    Task<string> classificationTask = Task.Run( () => GetClassification(property) );
    // GetClassification() runs a complex calculation but we don't need
    // the result right away so the code can do other things here related to property

    // ... code removed for brevity

    property.ClassificationCode = await classificationTask;
    // all other code has been completed and we now need the classification

    db.Properties.Add(property);
    db.SaveChanges();
    return RedirectToAction("Details", new { id = property.UPRN });
}

public string GetClassification(Property property)
{
    // do complex calculation
    return classification;
}
</code>```

But read https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html why not with ASP.NET

Body:
from what I understand the code below should eventually retrieve the string classification while running other code.

[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    string classification = GetClassification(property);
    // GetClassification() runs a complex calculation but we don't need
    // the result right away so the code can do other things here related to property

    // ... code removed for brevity

    property.ClassificationCode = await classification;
    // all other code has been completed and we now need the classification

    db.Properties.Add(property);
    db.SaveChanges();
    return RedirectToAction("Details", new { id = property.UPRN });
}

public string GetClassification(Property property)
{
    // do complex calculation
    return classification;
}

This should work the same way as in the below code from Matthew Jones' article

public async Task<string> GetNameAndContent()
{
    var nameTask = GetLongRunningName(); //This method is asynchronous
    var content = GetContent(); //This method is synchronous
    var name = await nameTask;
    return name + ": " + content;
}

However I get an error on await classification: 'string' does not contain a definition for 'GetAwaiter'

I'm unsure why this is happening.

Additionally, according to MSDN docs for expensive calculations I should instead be using:

property.ClassificationCode = await Task.Run(() => GetClassification(property));

Is this actually achieving what I want or is this just running synchronously anyway?

Thanks in advance for help.

Body:
To have the same as in the code from Matthew Jones you have to change your code to

[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    Task<string> classificationTask = Task.Run( () => GetClassification(property) );
    // GetClassification() runs a complex calculation but we don't need
    // the result right away so the code can do other things here related to property

    // ... code removed for brevity

    property.ClassificationCode = await classificationTask;
    // all other code has been completed and we now need the classification

    db.Properties.Add(property);
    db.SaveChanges();
    return RedirectToAction("Details", new { id = property.UPRN });
}

public string GetClassification(Property property)
{
    // do complex calculation
    return classification;
}

But read https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html why not with ASP.NET