问:
How do I Find Categories within in Contained Model in CakePHP
I had a recent question here regarding Finding records via conditions in habtm. Now, I could search for posts within a category I searched for.

Now, my questions is how to I retrieve the categories of each post. Sometimes a post has one or more categories in this query:

```<code>$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post')
    )
));
</code>```

I'd imagine something like this:

```<code>$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post' => array(
            'contain' => 'Category'
        ))
    )
));
</code>```

Here's what my models look like.

```<code>// Category Model
class Category extends AppModel {
    var $name = 'Category';
    var $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post'
        )
    );
    var $actsAs = array('Containable');
}

// Post Model
    class Post extends AppModel {
        var $name = 'Post';
        var $hasAndBelongsToMany = array(
            'Category' => array(
                'className' => 'Category'
            )
        );
        var $actsAs = array('Containable');
        var $virtualFields = array(
            'date_posted' => 'DATE_SUB(Post.created, INTERVAL 7 DAY)'
        );
    }
</code>```

A sample data would be like this:

```<code>categories
id name
1  holidays
2  destinations

posts
id title
1  I am a post
2  I am another post

categories_posts
post_id category_id
1       1
2       2
2       1
</code>```

I am retrieving posts from holidays.

```<code>Array
(
    [Category] => Array
        (
            [id] => 3
            [name] => holidays
            [uri] => holidays
            [created] => 2010-11-25 20:43:03
            [modified] => 2010-11-25 20:43:03
        )

    [Post] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [title] => I am a post
                ),
            [1] => Array
                (
                    [id] => 2
                    [title] => I am a another post
                )
        )
)
</code>```

The problem is that 1 of the posts are in two categories. I'd like to have that information also available.

答:
I actually did this to get what I want:

```<code>function getPostsFromCategory($uri) {
        return $this->populatePosts($this->find(
            'first',
            array(
                'conditions' => array(
                    'Category.uri' => $uri
                ),
                'contain' => array('Post' => array('Category'))
            )
        ));
    }

    function populatePosts($categoryPosts) {
        $posts = $categoryPosts['Post'];
        $count = count($categoryPosts['Post']);

        for ($i = 0; $i < $count; $i++) {
            $categories = $this->Post->find('first', array('conditions' => array('Post.id' => $categoryPosts['Post'][$i]['id']),
            'contains' => array('Category')));

            // unset($categories['Post']);
            foreach ($categories['Category'] as $cat) {
                $categoryPosts['Post'][$i]['Categories'][] = $cat;
            }
            unset($categories);
        }
        return $categoryPosts;
    }
</code>```

I really don't know if this can be done in a more CakePHP-y way though:

I returns something like this:

```<code>Array
(
    [Category] => Array
        (
            [id] => 3
            [name] => festivals
            [uri] => festivals
            [created] => 2010-11-25 20:43:03
            [modified] => 2010-11-25 20:43:03
        )

    [Post] => Array
        (
            [0] => Array
                (
                    [id] => 28
                    [title] => A Post
                    [Categories] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 3
                                    [name] => festivals
                                    [uri] => festivals
                                    [created] => 2010-11-25 20:43:03
                                    [modified] => 2010-11-25 20:43:03
                                )

                            [1] => Array
                                (
                                    [id] => 4
                                    [name] => destinations
                                    [uri] => destinations
                                    [created] => 2010-11-28 13:04:52
                                    [modified] => 2010-11-28 13:04:52
                                )

                        )

                )
)
</code>```

Body:
I had a recent question here regarding Finding records via conditions in habtm. Now, I could search for posts within a category I searched for.

Now, my questions is how to I retrieve the categories of each post. Sometimes a post has one or more categories in this query:

$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post')
    )
));

I'd imagine something like this:

$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post' => array(
            'contain' => 'Category'
        ))
    )
));

Here's what my models look like.

// Category Model
class Category extends AppModel {
    var $name = 'Category';
    var $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post'
        )
    );
    var $actsAs = array('Containable');
}

// Post Model
    class Post extends AppModel {
        var $name = 'Post';
        var $hasAndBelongsToMany = array(
            'Category' => array(
                'className' => 'Category'
            )
        );
        var $actsAs = array('Containable');
        var $virtualFields = array(
            'date_posted' => 'DATE_SUB(Post.created, INTERVAL 7 DAY)'
        );
    }

A sample data would be like this:

categories
id name
1  holidays
2  destinations

posts
id title
1  I am a post
2  I am another post

categories_posts
post_id category_id
1       1
2       2
2       1

I am retrieving posts from holidays.

Array
(
    [Category] => Array
        (
            [id] => 3
            [name] => holidays
            [uri] => holidays
            [created] => 2010-11-25 20:43:03
            [modified] => 2010-11-25 20:43:03
        )

    [Post] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [title] => I am a post
                ),
            [1] => Array
                (
                    [id] => 2
                    [title] => I am a another post
                )
        )
)

The problem is that 1 of the posts are in two categories. I'd like to have that information also available.

Body:
I actually did this to get what I want:

function getPostsFromCategory($uri) {
        return $this->populatePosts($this->find(
            'first',
            array(
                'conditions' => array(
                    'Category.uri' => $uri
                ),
                'contain' => array('Post' => array('Category'))
            )
        ));
    }

    function populatePosts($categoryPosts) {
        $posts = $categoryPosts['Post'];
        $count = count($categoryPosts['Post']);

        for ($i = 0; $i < $count; $i++) {
            $categories = $this->Post->find('first', array('conditions' => array('Post.id' => $categoryPosts['Post'][$i]['id']),
            'contains' => array('Category')));

            // unset($categories['Post']);
            foreach ($categories['Category'] as $cat) {
                $categoryPosts['Post'][$i]['Categories'][] = $cat;
            }
            unset($categories);
        }
        return $categoryPosts;
    }

I really don't know if this can be done in a more CakePHP-y way though:

I returns something like this:

Array
(
    [Category] => Array
        (
            [id] => 3
            [name] => festivals
            [uri] => festivals
            [created] => 2010-11-25 20:43:03
            [modified] => 2010-11-25 20:43:03
        )

    [Post] => Array
        (
            [0] => Array
                (
                    [id] => 28
                    [title] => A Post
                    [Categories] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 3
                                    [name] => festivals
                                    [uri] => festivals
                                    [created] => 2010-11-25 20:43:03
                                    [modified] => 2010-11-25 20:43:03
                                )

                            [1] => Array
                                (
                                    [id] => 4
                                    [name] => destinations
                                    [uri] => destinations
                                    [created] => 2010-11-28 13:04:52
                                    [modified] => 2010-11-28 13:04:52
                                )

                        )

                )
)


来源: stackexchange

问:
Applying a media query to jQuery
I'm trying to have my header (which has some jQuery applied to it) hidden on mobile.

I have a header which I've used jQuery to have slide in and out at a certain scroll point. It works well.

By default the header has display: none, the jQuery below makes the header visible.

I was hoping if I added a media query (for iphone) to hide the header with !important it would hide the header in all circumstances - but that hasn't had the desired effect.

jQuery (working fine):

```<code><script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
    $( document ).ready(function() {
        $(window).scroll(function(){
            scroll = $(window).scrollTop();
            if (scroll > 700 && scroll < 1000){
                $('#why-jquery').slideDown();
            }

            if (scroll < 700 && scroll < 1000){
                $('#why-jquery').slideUp();
            }

        });
    });
</script>
</code>```

main css:

```<code>#why-jquery {
    position: fixed;
    top:0;
    z-index: 99;
    width: 100%;
    height: 100px;
    display: none;
}
</code>```

media query:

```<code>@media screen and (max-width: 1000px) {
    #why-jquery {
        display: none !important;
    }
}
</code>```

答:
I have encountered your mistake. You are writing the correct code but there is a small problem in the way you have written your media query . There is a small syntax problem.

So change your media query from:

```<code>@media screen and (max-width: 1000px)
    #why-jquery {
        display: none !important;
    }
}
</code>```

to

```<code>@media screen and (max-width: 1000px){
    #why-jquery {
        display: none !important;
    }
}
</code>```

Basically in your media query CSS a { was missing.

Also Created a dummy example using your code :

$(document).ready(function() {
  $(window).scroll(function() {
    scroll = $(window).scrollTop();
    if (scroll > 700 && scroll < 1000) {
      $('#why-jquery').slideDown();
    }

    if (scroll < 700 && scroll < 1000) {
      $('#why-jquery').slideUp();
    }

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#why-jquery {
  position: fixed;
  top: 0;
  z-index: 99;
  width: 100%;
  height: 100px;
  display: none;
  background: green;
}

.container {
  height: 1600px;
  width: 100%;
  background: red;
}

@media screen and (max-width: 1000px){ #why-jquery {
  display: none !important;
}

}</code>```

```

ContentLicense: CC BY-SA 3.0

Title: Applying a media query to jQuery

Body:
I'm trying to have my header (which has some jQuery applied to it) hidden on mobile.

I have a header which I've used jQuery to have slide in and out at a certain scroll point. It works well.

By default the header has display: none, the jQuery below makes the header visible.

I was hoping if I added a media query (for iphone) to hide the header with !important it would hide the header in all circumstances - but that hasn't had the desired effect.

jQuery (working fine):

main css:

#why-jquery {
    position: fixed;
    top:0;
    z-index: 99;
    width: 100%;
    height: 100px;
    display: none;
}

media query:

@media screen and (max-width: 1000px) {
    #why-jquery {
        display: none !important;
    }
}

Body:
I have encountered your mistake. You are writing the correct code but there is a small problem in the way you have written your media query . There is a small syntax problem.

So change your media query from:

@media screen and (max-width: 1000px)
    #why-jquery {
        display: none !important;
    }
}

to

@media screen and (max-width: 1000px){
    #why-jquery {
        display: none !important;
    }
}

Basically in your media query CSS a { was missing.

Also Created a dummy example using your code :

$(document).ready(function() {
  $(window).scroll(function() {
    scroll = $(window).scrollTop();
    if (scroll > 700 && scroll < 1000) {
      $('#why-jquery').slideDown();
    }

    if (scroll < 700 && scroll < 1000) {
      $('#why-jquery').slideUp();
    }

  });
});

#why-jquery {
  position: fixed;
  top: 0;
  z-index: 99;
  width: 100%;
  height: 100px;
  display: none;
  background: green;
}

.container {
  height: 1600px;
  width: 100%;
  background: red;
}

@media screen and (max-width: 1000px){ #why-jquery {
  display: none !important;
}

}

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div class="container">
  <div id="why-jquery"></div>
</div>


问:
after crypt password,validation not function well
now i using this code to crypt my password on database,it function when login or validation.
But it only valid the first 7 character.
let say my password is miow12345, but i can just type in miow123 or miow12312q... to login

```<code>$pas = crypt($_POST["pas"], "MiO1!");
</code>```

validation.php

```<code>    if(isset($_POST['username']))
{
$username = $_POST['username'];
}
if (isset($_POST['password']))
{
$password=crypt($_POST["password"], "MiO1!");
}

$q = 'SELECT * FROM users WHERE username=:username AND password=:password';

$query = $dbh->prepare($q);

$query->execute(array(':username' => $username, ':password' => $password));

if($query->rowCount() == 0)
{
header('Location: login.php?err=1');
}
</code>```

another method(same problem)

```<code>if( crypt($_POST["pas"], "TmP2!") != $row["password"])
</code>```

答:
PHP's crypt function only uses the first eight characters, that's by design (http://php.net/manual/en/function.crypt.php).

You should use password_hash instead when storing a password in the database and use password_verify to compare it to the password the user entered:

```<code>if (password_verify($_POST["pas"], $row["password"]))
</code>```

(this code won't work for you right now, since you have crypt-hashed passwords in your DB, you will have to re-hash them using password_hash)

Body:
now i using this code to crypt my password on database,it function when login or validation.
But it only valid the first 7 character.
let say my password is miow12345, but i can just type in miow123 or miow12312q... to login

$pas = crypt($_POST["pas"], "MiO1!");

validation.php

    if(isset($_POST['username']))
{
$username = $_POST['username'];
}
if (isset($_POST['password']))
{
$password=crypt($_POST["password"], "MiO1!");
}

$q = 'SELECT * FROM users WHERE username=:username AND password=:password';

$query = $dbh->prepare($q);

$query->execute(array(':username' => $username, ':password' => $password));

if($query->rowCount() == 0)
{
header('Location: login.php?err=1');
}

another method(same problem)

if( crypt($_POST["pas"], "TmP2!") != $row["password"])

Body:
PHP's crypt function only uses the first eight characters, that's by design (http://php.net/manual/en/function.crypt.php).

You should use password_hash instead when storing a password in the database and use password_verify to compare it to the password the user entered:

if (password_verify($_POST["pas"], $row["password"]))

(this code won't work for you right now, since you have crypt-hashed passwords in your DB, you will have to re-hash them using password_hash)


问:
Loop through workbook and sheets in each workbook vba
I want to loop through all Workbooks in a folder and then loop through all worksheets of each workbook. I have the code below but currently the problem is with the line For Each ws in StrFile.Sheets:

```<code>Sub LoopThroughFiles()
    Dim StrFile As String
    StrFile = Dir("C:\Users\A9900899\Desktop\bob\VBAProject\Raw\")
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        For Each ws In StrFile.Sheets
            Debug.Print ws.Name
        Next ws
        StrFile = Dir
    Loop
End Sub
</code>```

What is my mistake here?

答:
In order to loop through all Workbook.Sheets you need to Set wb to the current StrFile, and then loop through wb.Sheets.

Using Application.ScreenUpdating = False and Application.DisplayAlerts = False will minimize all screen flickering and Excel alerts.

Code

```<code>Option Explicit

Sub LoopThroughFiles()

    Dim StrFile As Variant
    Dim fPath As String
    Dim wb As Workbook
    Dim ws As Worksheet

    fPath = "C:\Users\A9900899\Desktop\bob\VBAProject\Raw\"
    StrFile = Dir(fPath)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    While StrFile <> ""
        Debug.Print StrFile
        If StrFile Like "*xls*" Then ' check that current file is Excel type
            Set wb = Workbooks.Open(fPath & StrFile)
            For Each ws In wb.Sheets
                Debug.Print ws.Name
            Next ws
            wb.Close False ' close workbook and don't save changes
        End If
        StrFile = Dir
    Wend
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub
</code>```

Body:
I want to loop through all Workbooks in a folder and then loop through all worksheets of each workbook. I have the code below but currently the problem is with the line For Each ws in StrFile.Sheets:

Sub LoopThroughFiles()
    Dim StrFile As String
    StrFile = Dir("C:\Users\A9900899\Desktop\bob\VBAProject\Raw\")
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        For Each ws In StrFile.Sheets
            Debug.Print ws.Name
        Next ws
        StrFile = Dir
    Loop
End Sub

What is my mistake here?

Body:
In order to loop through all Workbook.Sheets you need to Set wb to the current StrFile, and then loop through wb.Sheets.

Using Application.ScreenUpdating = False and Application.DisplayAlerts = False will minimize all screen flickering and Excel alerts.

Code

Option Explicit

Sub LoopThroughFiles()

    Dim StrFile As Variant
    Dim fPath As String
    Dim wb As Workbook
    Dim ws As Worksheet

    fPath = "C:\Users\A9900899\Desktop\bob\VBAProject\Raw\"
    StrFile = Dir(fPath)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    While StrFile <> ""
        Debug.Print StrFile
        If StrFile Like "*xls*" Then ' check that current file is Excel type
            Set wb = Workbooks.Open(fPath & StrFile)
            For Each ws In wb.Sheets
                Debug.Print ws.Name
            Next ws
            wb.Close False ' close workbook and don't save changes
        End If
        StrFile = Dir
    Wend
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub


问:
"application need 1.6 or higher version of java" error while installing glassfish server?
I have downloaded glassfish server 3.1 and i have installed java 1.7, but while installing glassfish server I have the error below:

My java version is:

```<code>C:\Users\viksa>java -version
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b22)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)
</code>```

答:
Go to your glassfish download location:

C:\Users\J Balakrishna\Downloads

Take your Java installed location:

C:\Program Files\Java\jdk1.8.0_112

Run:

C:\Users\J Balakrishna\Downloads>glassfish-3.1.2-windows.exe -j "C:\Program Files\Java\jdk1.8.0_112"

Body:
I have downloaded glassfish server 3.1 and i have installed java 1.7, but while installing glassfish server I have the error below:

My java version is:

C:\Users\viksa>java -version
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b22)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)


问:
Replace [string : string] at specific index Swift
To replace a string at specific index from

```<code>var stringArray:[String] = ["value1", "value2", "value3", "value4"]
</code>```

We use

```<code>stringArray[2] = "new string"
</code>```

var myNewDictArray = [Dictionary< String, String> ] ()

In my case i have

```<code>key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
</code>```

In my array

When i try to replace dictionary at specific index say 5,
It shows up error:

Swift:: Error: contextual type '[String : String]' cannot be used with
  array lit eral
          myNewDictArray[index] = ["answer", "option3"]

Code im using is

```<code>for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index] = ["answer", "option3"]

    }

}
</code>```

I also tried

```<code>for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index].value(forKey:"answer") = "option3"

    }

}
</code>```

Then error is

Swift:: Error: value of type '[String : String]' has no member 'value'
          myNewDictArray[index].value(forKey:"answer") = "option3"

答:
You probably looking for subscript with your array of dictionary.

```<code>var myNewDictArray = [[String:String]]()// OR [Dictionary< String, String>]()
//If you want to update specific key value pair
myNewDictArray[index]["answer"] = "option3"
//If you want to replace whole dictionary with new one
myNewDictArray[index] = ["answer" : "option3"]
</code>```

Body:
To replace a string at specific index from

var stringArray:[String] = ["value1", "value2", "value3", "value4"]

We use

stringArray[2] = "new string"

var myNewDictArray = [Dictionary< String, String> ] ()

In my case i have

key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"

In my array

When i try to replace dictionary at specific index say 5,
It shows up error:

Swift:: Error: contextual type '[String : String]' cannot be used with
  array lit eral
          myNewDictArray[index] = ["answer", "option3"]

Code im using is

for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index] = ["answer", "option3"]

    }

}

I also tried

for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index].value(forKey:"answer") = "option3"

    }

}

Then error is

Swift:: Error: value of type '[String : String]' has no member 'value'
          myNewDictArray[index].value(forKey:"answer") = "option3"

Body:
You probably looking for subscript with your array of dictionary.

var myNewDictArray = [[String:String]]()// OR [Dictionary< String, String>]()
//If you want to update specific key value pair
myNewDictArray[index]["answer"] = "option3"
//If you want to replace whole dictionary with new one
myNewDictArray[index] = ["answer" : "option3"]


问:
Azure App Service app settings are not available through ConfigurationManager
I am using Azure App Service. I am trying to add several parameters in section Application settings -> App settings and Connection strings to override values from web.config

I cannot get access to these settings using ConfigurationManager.
My project is based on .Net 4.6.

I can get access to these app settings and connection strings using Environment.GetEnvironmentVariable("name").

Also these settings are not visible on page https://.scm.azurewebsites.net/Env.cshtml in sections AppSettings and Connection Strings, only in section Environment variables

I read a lot of articles and haven't not found an answer.

Is it by design or I am doing something wrong?

Update 1
I created a test project in VS 2015 update 3 - Webforms App and it works, but it contains OWIN, by my project does not.

Update 2
Looks like I described my problem incorrectly. ConfigurationManager works, and I can access settings from web.config, but after deployment to Azure I am expecting that values will be substituted by values that I entered in Azure App Service -> Application settings -> App settings and Connection strings. But it does not happen.

My web.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>

 <appSettings>
    <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="dummy" />
 </appSettings>

 <connectionStrings>
    <add name="default" providerName="System.Data.SqlClient" connectionString="empty" />
    <add name="ApolloTI" providerName="System.Data.SqlClient" connectionString="empty" />
    <add name="TestData" providerName="System.Data.SqlClient" connectionString="empty" />
 </connectionStrings>
   ...
</configuration>
</code>```

Screenshot - Setting in Azure

Update 3
I just created an empty web project and it works, so looks like the problem is somewhere in my code or in project configuration.

答:
I can get access to these app settings and connection strings using Environment.GetEnvironmentVariable("name").
  Also these settings are not visible on page https://.scm.azurewebsites.net/Env.cshtml in sections AppSettings and Connection Strings, only in section Environment variables

As far as I know, the kudu’s environment page will only show the default appsettings and Connection Strings.
It will not contain the webconfig’s appsettings and the appsettings you set in the portal.

According to this article，you will find below information:

App settings
  For .NET apps, these settings are injected into your .NET configuration AppSettings at runtime, overriding existing settings.
  Connection strings
  For each app setting, two environment variables are created; one with the name specified by the app setting entry, and another with a prefix of APPSETTING_. Both contain the same value.

For .NET apps, these connection strings are injected into your .NET configuration connectionStrings settings at runtime, overriding existing entries where the key equals the linked database name.
  These settings will also be available as environment variables at runtime, prefixed with the connection type. The environment variable prefixes are as follows:

SQL Server: SQLCONNSTR_

  MySQL: MYSQLCONNSTR_

  SQL Database: SQLAZURECONNSTR_

  Custom: CUSTOMCONNSTR_

For example, if a Custom connection string were named Redis, it would be accessed through the environment variable CUSTOMCONNSTR_Redis.

So you could find your appsettings and connectionstring in the environment variable.

And this value will replace the webconfig value when your application is running.

I also write a test demo on my computer by using the ConfigurationManager class, it works well.

So I guess maybe something wrong with your codes.

Here is my test demo, hope it gives you some tips:

```<code>public void ReadAllSettings()
{
    string o = "";
    try
    {
        var appSettings = ConfigurationManager.AppSettings;

        if (appSettings.Count == 0)
        {
            o =  "AppSettings is empty.";
        }
        else
        {
            foreach (var key in appSettings.AllKeys)
            {
                o +=  string.Format("Key: {0} Value: {1}", key, appSettings[key]);
            }
        }
    }
    catch (ConfigurationErrorsException)
    {
        o = "AppSettings is empty.";
    }

    Label1.Text = o;
    Label2.Text = ConfigurationManager.ConnectionStrings["ConnStringDb2"].ConnectionString;
}
</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
I am using Azure App Service. I am trying to add several parameters in section Application settings -> App settings and Connection strings to override values from web.config

I cannot get access to these settings using ConfigurationManager.
My project is based on .Net 4.6.

I can get access to these app settings and connection strings using Environment.GetEnvironmentVariable("name").

Also these settings are not visible on page https://.scm.azurewebsites.net/Env.cshtml in sections AppSettings and Connection Strings, only in section Environment variables

I read a lot of articles and haven't not found an answer.

Is it by design or I am doing something wrong?

Update 1
I created a test project in VS 2015 update 3 - Webforms App and it works, but it contains OWIN, by my project does not.

Update 2
Looks like I described my problem incorrectly. ConfigurationManager works, and I can access settings from web.config, but after deployment to Azure I am expecting that values will be substituted by values that I entered in Azure App Service -> Application settings -> App settings and Connection strings. But it does not happen.

My web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

 <appSettings>
    <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="dummy" />
 </appSettings>

 <connectionStrings>
    <add name="default" providerName="System.Data.SqlClient" connectionString="empty" />
    <add name="ApolloTI" providerName="System.Data.SqlClient" connectionString="empty" />
    <add name="TestData" providerName="System.Data.SqlClient" connectionString="empty" />
 </connectionStrings>
   ...
</configuration>

Screenshot - Setting in Azure

Update 3
I just created an empty web project and it works, so looks like the problem is somewhere in my code or in project configuration.

Body:
I can get access to these app settings and connection strings using Environment.GetEnvironmentVariable("name").
  Also these settings are not visible on page https://.scm.azurewebsites.net/Env.cshtml in sections AppSettings and Connection Strings, only in section Environment variables

As far as I know, the kudu’s environment page will only show the default appsettings and Connection Strings.
It will not contain the webconfig’s appsettings and the appsettings you set in the portal.

According to this article，you will find below information:

App settings
  For .NET apps, these settings are injected into your .NET configuration AppSettings at runtime, overriding existing settings.
  Connection strings
  For each app setting, two environment variables are created; one with the name specified by the app setting entry, and another with a prefix of APPSETTING_. Both contain the same value.

For .NET apps, these connection strings are injected into your .NET configuration connectionStrings settings at runtime, overriding existing entries where the key equals the linked database name.
  These settings will also be available as environment variables at runtime, prefixed with the connection type. The environment variable prefixes are as follows:

SQL Server: SQLCONNSTR_

  MySQL: MYSQLCONNSTR_

  SQL Database: SQLAZURECONNSTR_

  Custom: CUSTOMCONNSTR_

For example, if a Custom connection string were named Redis, it would be accessed through the environment variable CUSTOMCONNSTR_Redis.

So you could find your appsettings and connectionstring in the environment variable.

And this value will replace the webconfig value when your application is running.

I also write a test demo on my computer by using the ConfigurationManager class, it works well.

So I guess maybe something wrong with your codes.

Here is my test demo, hope it gives you some tips:

public void ReadAllSettings()
{
    string o = "";
    try
    {
        var appSettings = ConfigurationManager.AppSettings;

        if (appSettings.Count == 0)
        {
            o =  "AppSettings is empty.";
        }
        else
        {
            foreach (var key in appSettings.AllKeys)
            {
                o +=  string.Format("Key: {0} Value: {1}", key, appSettings[key]);
            }
        }
    }
    catch (ConfigurationErrorsException)
    {
        o = "AppSettings is empty.";
    }

    Label1.Text = o;
    Label2.Text = ConfigurationManager.ConnectionStrings["ConnStringDb2"].ConnectionString;
}

Result:


问:
Command prompt won't change directory to another drive
I'm trying to compile some java (learning java currently), and to do so I need to change command-prompt's directory.

```<code>C:\...\Admin> cd D:\Docs\Java
C:\...\Admin> cd
C:\...\Admin
</code>```

It doesn't change the directory. I try again using quotes:

```<code>C:\...\Admin> cd "D:\Docs\Java"
C:\...\Admin>
</code>```

Again it doesn't change the directory. What am I doing wrong?

答:
You can change directory using this command
like : currently if you current working directoris c:\ drive the
if you want to go to your  D:\ drive then type this command

```<code>cd /d D:\
</code>```

now your current working directory is D:\ drive so you want go to  Java directory under Docs so type below command :

```<code>cd Docs\Java
</code>```

note : d stands for drive

Body:
I'm trying to compile some java (learning java currently), and to do so I need to change command-prompt's directory.

C:\...\Admin> cd D:\Docs\Java
C:\...\Admin> cd
C:\...\Admin

It doesn't change the directory. I try again using quotes:

C:\...\Admin> cd "D:\Docs\Java"
C:\...\Admin>

Again it doesn't change the directory. What am I doing wrong?

Body:
You can change directory using this command
like : currently if you current working directoris c:\ drive the
if you want to go to your  D:\ drive then type this command

cd /d D:\

now your current working directory is D:\ drive so you want go to  Java directory under Docs so type below command :

cd Docs\Java

note : d stands for drive


问:
How to find out in which Wiki software a website is built on?
Some websites have a small logo or something at the bottom of their web page indicating that for example, that website is powered by MediaWiki.

How to find out what Wiki software does a website use in case of the owner removing the "Powered by ..." logo?

答: To check for mediawiki sites, I check for the Special:Version page. For example, https://codex.wordpress.org/Special:Version.</p>


问:
Count number of male and female
i want to count  no of male and female in a table called Gender having entry given below. Answer should be female=2 Male=3 in count.
Is there any query in SQL.</p>

```<code>Gender
MALE
MaLE
FEMALE
Female
</code>```

答:
```<code>SELECT UPPER([Gender]),count(*)
  FROM [test].[dbo].[TableName] group by UPPER([Gender])
</code>```

Title: Count number of male and female

Body:
i want to count  no of male and female in a table called Gender having entry given below. Answer should be female=2 Male=3 in count.
Is there any query in SQL.

Gender
MALE
MaLE
FEMALE
Female


问:
Laravel 5.0 Undefined variable result
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

```<code>Route::get('/shopsales', 'shopsalescontroller@index');
</code>```

Controller

```<code>class shopsalescontroller extends Controller
</code>```

{

```<code> public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}
</code>```

}

shopsales view

```<code><section>
  <center><h1><STRONG>Query Data</STRONG></h1></center>
    <ul>
      @foreach ($result as $results)
        <li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
        </li>
        <br>
      @endforeach
    </ul>

</section>
</code>```

I have used the exact code for the query that is working, struggling to understand why this is not.

答:
```<code>public function index()
{
   $storeNum = request('storeNum');
   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();
    return view('shopsales',['result'=>compact('result')]);
}
</code>```

Change your controller code like above.
Also check if $result is not null.

Title: Laravel 5.0 Undefined variable result

Body:
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

Route::get('/shopsales', 'shopsalescontroller@index');

Controller

class shopsalescontroller extends Controller

{

 public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}

}

shopsales view

Query Data

      @foreach ($result as $results)

Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}

      @endforeach

I have used the exact code for the query that is working, struggling to understand why this is not.

Body:
public function index()
{
   $storeNum = request('storeNum');
   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();
    return view('shopsales',['result'=>compact('result')]);
}

Change your controller code like above.
Also check if $result is not null.


问:
Twitter Top Tweets like jQuery Plugin
I'm looking for a JavaScript or a jQuery plugin has an effect like the twitter top tweets. Thanks in advance.

http://img52.imageshack.us/img52/6899/twitterl.jpg

答:
Hi guy you find this type of plugin here

http://www.amitpatil.me/tweeter-like-top-tweet-jquery-plugin/

ContentLicense: CC BY-SA 2.5

Title: Twitter Top Tweets like jQuery Plugin


问:
Check the existence of a record before inserting a new record
I'm using the Ado.net Entity Framework for the first time and I need to check if this record exist before I insert it to the database. Preferably I'd search if AuthodSSID exists  and not the key (AuthorID). I'm using VS2010, Framework 4. System.Data.Entity is 3.5.0.0.

I googled, but found no answer for this question.

```<code>PublishingCompanyEntities publishContext;
publishContext = new PublishingCompanyEntities();

private void createNew_Click(object sender, EventArgs e)
{
    Author newAuthor = new Author();
    newAuthor.FirstName = firstName.Text;
    newAuthor.LastName = lastName.Text;
    newAuthor.AuthodSSID = 20;
    newAuthor.AuthorID = 10
//Check if record exist here
    publishContext.AddToAuthor(newAuthor);//insert if does not exist

}
</code>```

答:
This method is advised to only be used for migrations to seed data, not as an upsert method

There is so called "upsert" operation available in EF v5.0+

```<code>publishContext.Author.AddOrUpdate(x => x.Id, newAuthor)
</code>```

AddOrUpdate can be found in the "System.Data.Entity.Migrations" namespace, so don't forget to add:

```<code>using System.Data.Entity.Migrations;
</code>```

The AddOrUpdate operation is not atomic. But *if (existingAuthorCount == 0) {// Do your insert} isn't also.

Body:
I'm using the Ado.net Entity Framework for the first time and I need to check if this record exist before I insert it to the database. Preferably I'd search if AuthodSSID exists  and not the key (AuthorID). I'm using VS2010, Framework 4. System.Data.Entity is 3.5.0.0.

I googled, but found no answer for this question.

PublishingCompanyEntities publishContext;
publishContext = new PublishingCompanyEntities();

private void createNew_Click(object sender, EventArgs e)
{
    Author newAuthor = new Author();
    newAuthor.FirstName = firstName.Text;
    newAuthor.LastName = lastName.Text;
    newAuthor.AuthodSSID = 20;
    newAuthor.AuthorID = 10
//Check if record exist here
    publishContext.AddToAuthor(newAuthor);//insert if does not exist

}

Body:
This method is advised to only be used for migrations to seed data, not as an upsert method

There is so called "upsert" operation available in EF v5.0+

publishContext.Author.AddOrUpdate(x => x.Id, newAuthor)

AddOrUpdate can be found in the "System.Data.Entity.Migrations" namespace, so don't forget to add:

using System.Data.Entity.Migrations;

The AddOrUpdate operation is not atomic. But *if (existingAuthorCount == 0) {// Do your insert} isn't also.


问:
How to set custom status codes in error with spring boot?
Hi i need to throw custom errors with custom status.The response status should be always 200 /201.Please help me to reslove this issue.Current status in given below

{
  "timestamp": "2017-03-30T05:59:56.010+0000",
  "status": 400,
  "error": "Bad Request",
  "exception": "custom exception",
  "message": "custom message",
  "path": "/api/sjsdj"
}
What i expect as response is

{
  "timestamp": "2017-03-30T05:59:56.010+0000",
  "status": 600,
  "error": "custom error",
  "exception": "web.rest.errors.custom exception",
  "message": "custom message",
  "path": "/api/hgdsh/3"
}

答:
You can use @ExceptionHandler.

Create a @ControllerAdvice with methods annotated with @ExceptionHandler that cache your custom exceptions / generic one and return your custom status/message etc there.

Example:

```<code>@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        return new ResponseEntity<Object>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
</code>```

Body:
You can use @ExceptionHandler.

Create a @ControllerAdvice with methods annotated with @ExceptionHandler that cache your custom exceptions / generic one and return your custom status/message etc there.

Example:

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        return new ResponseEntity<Object>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}


问:
Response to preflight request doesn't pass access control check
I'm getting this error using ngResource to call a REST API on Amazon Web Services:

XMLHttpRequest cannot load
http://server.apiurl.com:8000/s/login?login=facebook. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Error 405

Service:

```<code>socialMarkt.factory('loginService', ['$resource', function ($resource) {
    var apiAddress = "http://server.apiurl.com:8000/s/login/";
    return $resource(apiAddress, {
        login: "facebook",
        access_token: "@access_token",
        facebook_id: "@facebook_id"
    }, {
        getUser: {
            method: 'POST'
        }
    });
}]);
</code>```

Controller:

```<code>[...]
loginService.getUser(JSON.stringify(fbObj)),
    function (data) {
        console.log(data);
    },
    function (result) {
        console.error('Error', result.status);
    }
[...]
</code>```

I'm using Chrome. What else can I do in order to fix this problem?

I've even configured the server to accept headers from origin localhost.

答:
JavaScript XMLHttpRequest and Fetch follow the same-origin policy. So,
  a web application using XMLHttpRequest or Fetch could only make HTTP
  requests to its own domain.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

You have to send the Access-Control-Allow-Origin: * HTTP header from your server side.

If you are using Apache as your HTTP server then you can add it to your Apache configuration file like this:

```<code><IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
</code>```

Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled by running:

```<code> a2enmod headers
</code>```

Body:
I'm getting this error using ngResource to call a REST API on Amazon Web Services:

XMLHttpRequest cannot load
http://server.apiurl.com:8000/s/login?login=facebook. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Error 405

Service:

socialMarkt.factory('loginService', ['$resource', function ($resource) {
    var apiAddress = "http://server.apiurl.com:8000/s/login/";
    return $resource(apiAddress, {
        login: "facebook",
        access_token: "@access_token",
        facebook_id: "@facebook_id"
    }, {
        getUser: {
            method: 'POST'
        }
    });
}]);

Controller:

[...]
loginService.getUser(JSON.stringify(fbObj)),
    function (data) {
        console.log(data);
    },
    function (result) {
        console.error('Error', result.status);
    }
[...]

I'm using Chrome. What else can I do in order to fix this problem?

I've even configured the server to accept headers from origin localhost.

Body:
JavaScript XMLHttpRequest and Fetch follow the same-origin policy. So,
  a web application using XMLHttpRequest or Fetch could only make HTTP
  requests to its own domain.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

You have to send the Access-Control-Allow-Origin: * HTTP header from your server side.

If you are using Apache as your HTTP server then you can add it to your Apache configuration file like this:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled by running:

 a2enmod headers


问:
What are some practical use cases of GraphQL? When should one choose GraphQL over REST?
As I am interested in the concept of graphql I want to understand the benefits of graphql and when to use it?</p>

答:
There are many excellent online resources on this subject, for example https://philsturgeon.uk/api/2017/01/24/graphql-vs-rest-overview/

Main points from this article:

REST and GraphQL are totally different

GraphQL isn't a magic bullet, nor is it "better"

You can definitely use both at the same time

GraphQL is dope if used for the right thing


问:
Module instance methods and Module "regular" methods in Ruby
I'm trying to figure out the true difference between a module's instance methods and a module's "regular" methods.

To do that I fired up an irb and did the following:

```<code>>> Kernel.instance_methods
>> Kernel.methods
</code>```

I noticed that the output between these two is different.

For example, Kernel.methods includes a method :readline while Kernel.instance_methods does not.

Why and how is this happening?

Thanks.

答:
you can reference the Ruby Help file(https://ruby-doc.org/core-2.2.3/Kernel.html), there is words about module Kernel:

"The Kernel module is included by class Object, so its methods are
  available in every Ruby object."

Kernel.methods includes all Kernel.instance_methods's methods, you can try this code to verify it:

```<code>p Kernel.instance_methods&Kernel.methods == Kernel.instance_methods
</code>```

in my opinion, Kernel.instance_methods can be called by any objects you created, but some of Kernel.methods can't be called by objects(like the Array/ String/ Hash).

Body:
I'm trying to figure out the true difference between a module's instance methods and a module's "regular" methods.

To do that I fired up an irb and did the following:

>> Kernel.instance_methods
>> Kernel.methods

I noticed that the output between these two is different.

For example, Kernel.methods includes a method :readline while Kernel.instance_methods does not.

Why and how is this happening?

Thanks.

Body:
you can reference the Ruby Help file(https://ruby-doc.org/core-2.2.3/Kernel.html), there is words about module Kernel:

"The Kernel module is included by class Object, so its methods are
  available in every Ruby object."

Kernel.methods includes all Kernel.instance_methods's methods, you can try this code to verify it:

p Kernel.instance_methods&Kernel.methods == Kernel.instance_methods

in my opinion, Kernel.instance_methods can be called by any objects you created, but some of Kernel.methods can't be called by objects(like the Array/ String/ Hash).


问:
How do I access string-array item attributes in XAML xamarin
Is it possible to access the attributes of string-array item when Spinner get selected?
I have the following string-array:

```<code><string-array name="paypal_selling_rates">
        <item fee="0.026">Under $2,500</item>
        <item fee="0.022">$2,500.01 - $5,000</item>
        <item fee="0.020">$5,000.01 - $15,000</item>
        <item fee="0.015">$15,000.01 - $150,000</item>
        <item fee="0.011">Over $150,000</item>
    </string-array>
</code>```

Now i can get the value of selected item like this:

```<code>paypalSellingRates.SelectedItem.ToString();
</code>```

But how I can access the attribute fee?

答:
This looks like an Android question. On Android, string array resources can't have attributes on the items.

So the answer is that you can't.

Read more about this in the official Android documentation.

Body:
Is it possible to access the attributes of string-array item when Spinner get selected?
I have the following string-array:

<string-array name="paypal_selling_rates">
        <item fee="0.026">Under $2,500</item>
        <item fee="0.022">$2,500.01 - $5,000</item>
        <item fee="0.020">$5,000.01 - $15,000</item>
        <item fee="0.015">$15,000.01 - $150,000</item>
        <item fee="0.011">Over $150,000</item>
    </string-array>

Now i can get the value of selected item like this:

paypalSellingRates.SelectedItem.ToString();

But how I can access the attribute fee?


问:
How can we display ModelAndView model value in a jsp page in a popup
I have a jsp submit-cot.jsp from where I hit the controller below and the form is sucessfully submitted, and I am redirected to the submit-cot.jsp page again.

```<code>@RequestMapping(value = "/submitform", method = RequestMethod.POST)
    public ModelAndView submitform(
            ModelAndView model,
            @ModelAttribute("cot") Cot cot,
            @ModelAttribute("platformUrl") PlatformUrlView platformUrl,
            final HttpServletRequest request)
    {
        cotService.save(cot,platformUrl);
        model.setViewName("redirect:/submit-cot");
        model.addObject("msg", resource.getMsg("A45"));
        return model;
    }
</code>```

The problem is that the message 'msg' comes in the url, as
    http://localhost:8080/submit-cot?msg=Cot+is+submitted+successfully.
I need to display the message 'msg' in a popup.

Can anybody please suggest how to get the message in a popup.
Thanks in advance.

答: Pass the parameters you want in the model object itself. model.addAttribute(key, value). This will be available in the JSP. Use ${keyname} to retrieve the attribute in the client side and display it. I hope this will solve your problem.</p>

Body:
I have a jsp submit-cot.jsp from where I hit the controller below and the form is sucessfully submitted, and I am redirected to the submit-cot.jsp page again.

@RequestMapping(value = "/submitform", method = RequestMethod.POST)
    public ModelAndView submitform(
            ModelAndView model,
            @ModelAttribute("cot") Cot cot,
            @ModelAttribute("platformUrl") PlatformUrlView platformUrl,
            final HttpServletRequest request)
    {
        cotService.save(cot,platformUrl);
        model.setViewName("redirect:/submit-cot");
        model.addObject("msg", resource.getMsg("A45"));
        return model;
    }

The problem is that the message 'msg' comes in the url, as
    http://localhost:8080/submit-cot?msg=Cot+is+submitted+successfully.
I need to display the message 'msg' in a popup.

Can anybody please suggest how to get the message in a popup.
Thanks in advance.


问:
Reason to take more loading time of asp.net page and how to reduce it
I have the following queries regarding the loading time of asp.net page.
Anyone can help.
What are the possibilities of asp.net page consuming more loading time?.
How to reduce the loading time of asp.net web page?</p>

答:
Images used

The images used should be optimized and consider low file size.

Allow Caching of images

Reduce number of scripts and stylesheets

Try minimizing and combining CSS  and script files

Enable HTTP Compression

Compilation should be on release mode ie, remove <compilation debug="true"/> from web.config

Check the Viewstate, big viewstates slow downs the page.

If you are consuming the database, try database level paging, if the number of records are higher. Consider fetching only the required fields.


问:
I'm new with angular.js, I just try to create a login form using angular.js

All working find when I try to login first time, but second time after logout submit button not working.

Can We do this code shorter and better way using anguler.js Please help

HTML

```<code><div ng-app="app">

    <div ng-controller="HttpGetController">
        <div ng-hide ="logedin">
            <p>User: <input type="text" name="firstName" ng-model="firstName" required /></p>
            <p>Password: <input type="text" name="lastName" ng-model="lastName" required /></p>
            <button ng-click="SendData()">Submit</button>
        </div>
        <div class="userDetail" ng-hide="userDetail">
                {{message.result[0].FIRST_NAME + " " + message.result[0].LAST_NAME}}
                <div class="logout"><a href="#" title="title" ng-click='logout()'>Logout</a></div>
        </div>
        </div>
</div>
</code>```

Javascript (angular)

```<code>var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
    $scope.userDetail = true;
    if(!localStorage.getItem('logedin')){
        $scope.SendData = function () {
            var creds = 'username=' + $scope.firstName + '&password=' + $scope.lastName;
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var res = $http.post('http://api.example.com/beta/login.php', creds, config);
            res.success(function(data, status, headers, config) {
                if(data.success){
                    $scope.logedin = true;
                    $scope.message = data;
                    localStorage.setItem("logedin", angular.toJson(data));
                    $scope.userDetail = false;
                } else {
                    alert(data.description);
                }
            });
        };
    } else {
        $scope.logedin = true;
        $scope.message = JSON.parse(localStorage.getItem('logedin'));
        $scope.userDetail = false;
    }
    $scope.logout = function(){
        window.localStorage.removeItem('logedin');
        $scope.logedin = false;
        $scope.userDetail = true;
    }
});
</code>```

答:
Your code is working fine on my side.
May be your page is getting refreshed on logout before ng-click trigger, because of href="#"
Though, I am not seeing this refresh on my side, as I have not hosted the pages, you can try href="javascript:void(0)" in place of  href="#"
to stop page from refreshing.

Body:
All working find when I try to login first time, but second time after logout submit button not working.

Can We do this code shorter and better way using anguler.js Please help

HTML

User: <input type="text" name="firstName" ng-model="firstName" required />

Password: <input type="text" name="lastName" ng-model="lastName" required />

            <button ng-click="SendData()">Submit</button>

                {{message.result[0].FIRST_NAME + " " + message.result[0].LAST_NAME}}

Logout

Javascript (angular)

var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
    $scope.userDetail = true;
    if(!localStorage.getItem('logedin')){
        $scope.SendData = function () {
            var creds = 'username=' + $scope.firstName + '&password=' + $scope.lastName;
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var res = $http.post('http://api.example.com/beta/login.php', creds, config);
            res.success(function(data, status, headers, config) {
                if(data.success){
                    $scope.logedin = true;
                    $scope.message = data;
                    localStorage.setItem("logedin", angular.toJson(data));
                    $scope.userDetail = false;
                } else {
                    alert(data.description);
                }
            });
        };
    } else {
        $scope.logedin = true;
        $scope.message = JSON.parse(localStorage.getItem('logedin'));
        $scope.userDetail = false;
    }
    $scope.logout = function(){
        window.localStorage.removeItem('logedin');
        $scope.logedin = false;
        $scope.userDetail = true;
    }
});


问:
triggering same function for multiple select box in different containers
I have select box inside multiple divs which shows the selected option value in span div. the jquery function executes only for the first div select box and not for the rest. i want a single function that works for all the divs without repeating code for each and every div.

```<code><div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format3" class="selectpicker" name="for" >
    <option value="48.00" selected="selected">Paperback</option>
    <option value="40.00">eBook</option>
  </select>
  <span id="price-div3" >
    <span class="price"></span>
  </span>
</div>

<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format4" class="selectpicker" name="for" >
    <option value="48.00" selected="selected">Paperback</option>
    <option value="40.00">eBook</option>
  </select>
  <span id="price-div4">
    <span class="price"></span>
  </span>
</div>
</code>```

$(document).ready(function() {
  var format_div = $(".format-block select").attr("id");
  $(".format-block span.price").html("£" + $("#" + format_div).val());

  $('.format-block').on("change", "select", function() {
    $(".format-block span.price").html("£" + $("#" + format_div).val());
  });
});
```

pls let me know what im doing wrong here..

答:
You need use event.target, the DOM element that initiated the event. You need to perform operation in its context.

$('.format-block').on("change", "select", function(event) {
  $(event.target).closest(".format-block").find("span.price").html("£" + $(event.target).val());
});

//Tigger event handler, to set the price
$('.format-block select').trigger('change');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format3" class="selectpicker" name="for">
    <option value="48.00" selected>Paperback</option>
    <option value="40.00">eBook</option>
  </select>
  <span id="price-div3">
    <span class="price"></span>
  </span>
</div>

<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format4" class="selectpicker" name="for">
    <option value="48.00">Paperback</option>
    <option value="40.00" selected>eBook</option>
  </select>
  <span id="price-div4">
    <span class="price"></span>
  </span>
</div></code>```

References

.closest()

.find()

.trigger()

Body:
I have select box inside multiple divs which shows the selected option value in span div. the jquery function executes only for the first div select box and not for the rest. i want a single function that works for all the divs without repeating code for each and every div.

  Format:
  <select id="format3" class="selectpicker" name="for" >
    <option value="48.00" selected="selected">Paperback</option>
    <option value="40.00">eBook</option>
  </select>

  Format:
  <select id="format4" class="selectpicker" name="for" >
    <option value="48.00" selected="selected">Paperback</option>
    <option value="40.00">eBook</option>
  </select>

$(document).ready(function() {
  var format_div = $(".format-block select").attr("id");
  $(".format-block span.price").html("£" + $("#" + format_div).val());

  $('.format-block').on("change", "select", function() {
    $(".format-block span.price").html("£" + $("#" + format_div).val());
  });
});

pls let me know what im doing wrong here..

Body:
You need use event.target, the DOM element that initiated the event. You need to perform operation in its context.

$('.format-block').on("change", "select", function(event) {
  $(event.target).closest(".format-block").find("span.price").html("£" + $(event.target).val());
});

//Tigger event handler, to set the price
$('.format-block select').trigger('change');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format3" class="selectpicker" name="for">
    <option value="48.00" selected>Paperback</option>
    <option value="40.00">eBook</option>
  </select>
  <span id="price-div3">
    <span class="price"></span>
  </span>
</div>

<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format4" class="selectpicker" name="for">
    <option value="48.00">Paperback</option>
    <option value="40.00" selected>eBook</option>
  </select>
  <span id="price-div4">
    <span class="price"></span>
  </span>
</div>

References

.closest()

.find()

.trigger()


问:
php, mysql search for the website
I need a search engine for a website I am building. I decided to try my own using php and mysql. Currently it looks like the viable options is to create three tables.

One for words, one for pages, and one reference table. Then when I am inserting a new article I would scan the text and put the separate words in the words table and refernce those words on the third table.

In the end when a search is made. The script should return the pages with the most indexed words for a given word.

However it looks like this approach can only return results depending on the number of keywords. The more a keyword is used in an article the more higher it will appear on the result page. So an article with less keywords maybe more related to the search but will be placed lower on the results.

The question would be is there a better way to create a custom search engine using php/mysql? Also if you do not have access to server to install search engines like Sphinx what is the best way to tackle this problem?

答: I  Second El Yobo, if you are going for a full blown search engine you will have better luck with lucene clients but if you are looking for a quick solution google cse is the best.</p>

Title: php, mysql search for the website


问:
PARTIAL_WAKE_LOCK when recording sensor data
I am recording sensor data such as Accelerometer, Orientation, Gyroscope. This data writes to a file onSensorChanged update every so often.

My problem is when I put the phone into standby that the sensor data stops writing to file. So I done some research and decided to set it up using PowerManager and using the wake lock

PARTIAL_WAKE_LOCK: I just can't get it working.

SCREEN_DIM_WAKE_LOCK: My code will work grand.
From what I read up on there seems to be a problem with using PARTIAL_WAKE_LOCK.

I can't seem to find a definite answer on whether or not there is a problem with it still or there isn't. I even tried some of the hack approaches people have suggested such as using an itent to capture when screen is off and then unregistering the sensors and registering them again. But this solution didn't work. From what I can gather it seems inconsistant if it will work or not and seems phone dependant. I have tried my code on both a HTC Wildfire running Android2.2 and Nexus S running Android2.3.

My application is an app that is basically ran in the background with a long running service. So having PARTIAL_WAKE_LOCK is important with battery life.

答:
This is a pretty old question, I'll still answer it as pretty much all the devices today are beyond 2.3

Create a background service and use the Partial Lock Wake in the following manner:

First take care of the permissions (in the manifest file):

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

Then, most preferably use this in the Application file, or wherever:

```<code>PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
if(/*condition*/) {
    wakeLock.acquire(); //keep CPU awake
} else {
    wakeLock.release(); //disable keep CPU awake
}
</code>```

Although it is a pretty cool feature, it drains your battery life, hence use it responsibly.

Body:
This is a pretty old question, I'll still answer it as pretty much all the devices today are beyond 2.3

Create a background service and use the Partial Lock Wake in the following manner:

First take care of the permissions (in the manifest file):

<uses-permission android:name="android.permission.WAKE_LOCK" />

Then, most preferably use this in the Application file, or wherever:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
if(/*condition*/) {
    wakeLock.acquire(); //keep CPU awake
} else {
    wakeLock.release(); //disable keep CPU awake
}

Although it is a pretty cool feature, it drains your battery life, hence use it responsibly.


问:
angular 2 observable timeout second parameter type
I am currently trying to make timeout() method of Angular 2 Observable work properly, but in all tutorials there is similair code, where the second argument of timeout() method is a simple Error:

```<code>return this.http.get('http://...')
                .timeout(2000, new Error('Timeout exceeded'));
</code>```

But when I copy this code, TypeScript says that the second argument has invalid type and expects to see smth which implements interface IScheduler.

One of the ways to solve the problem is to make new class which implements IScheduler interface, but it has functionality I am not familiar with (now() method and Tasks).

Does anyone know, should I do it in this way or are there another ways to make things work? And what if instead of error I want to place some callback function?

答:
timeout does not take an Error as a parameter. If a timeout occurs it will throw a TimeoutError.

If you want to throw a particular type of error, you could use the timeoutWith operator to do something like this:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/timeoutWith';

return this.http
  .get('http://...')
  .timeoutWith(2000, Observable.throw(new Error('Boom!')));
```

Body:
I am currently trying to make timeout() method of Angular 2 Observable work properly, but in all tutorials there is similair code, where the second argument of timeout() method is a simple Error:

return this.http.get('http://...')
                .timeout(2000, new Error('Timeout exceeded'));

But when I copy this code, TypeScript says that the second argument has invalid type and expects to see smth which implements interface IScheduler.

One of the ways to solve the problem is to make new class which implements IScheduler interface, but it has functionality I am not familiar with (now() method and Tasks).

Does anyone know, should I do it in this way or are there another ways to make things work? And what if instead of error I want to place some callback function?


答:
You are just missing array push function of javasciprt

```<code>var array = [], finarr = [];
Object.keys(data).forEach(function (key) {
    //console.log(data[key]);
    array = $.map(data[key], function(value, index) {
    return [value];
    });
    finarr.push(array);
});
</code>```

it will give the right result i hope

Title: How to convert objects in to array of Array

Body:
I have tried like this but it's not like what i need

Object.keys(data).forEach(function (key) {
    console.log(data[key]);
    array = $.map(data[key], function(value, index) {
       return [value];
    });
});

output i found -

0:{1: 2, 2: 2, 3: 7, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}
1:{1: 3, 2: 1, 3: 2, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}
2:{1: 0, 2: 2, 3: 2, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}

please help me to get the result below :

0:[1: 2, 2: 2, 3: 7, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0]
1:[1: 3, 2: 1, 3: 2, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0]
2:[1: 0, 2: 2, 3: 2, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0]

Thanks in advance !

Body:
You are just missing array push function of javasciprt

var array = [], finarr = [];
Object.keys(data).forEach(function (key) {
    //console.log(data[key]);
    array = $.map(data[key], function(value, index) {
    return [value];
    });
    finarr.push(array);
});

it will give the right result i hope


问:
Create new entry if not empty and no duplicates exist
I want to create a note with a title and a text if

the title is not empty

the title does not already exist

When I check for duplicates in my array, it always returns true, even if there are duplicates.

My code:

```<code>CreateNote(title, text){
    if (title.length > 0 && // title is empty?
 $.inArray(title, this.store.notes) < 0) // check the array for duplicates, returns always true, even with duplicates in the store
      this.store.AddNote(new Note(title, text));
  }
</code>```

So what is wrong with the second check =?

Thanks

答:
You're not comparing the title to the other note titles, but instead to the note objects.

Assuming that the title is exposed as a title property on the note objects, you'd have to rewrite your condition like this:

```<code>$.inArray(title, this.store.notes.map(n => n.title)) < 0
</code>```

Or with standard JavsScript:

```<code>!this.store.notes.some(n => n.title === title)
</code>```

Body:
I want to create a note with a title and a text if

the title is not empty

the title does not already exist

When I check for duplicates in my array, it always returns true, even if there are duplicates.

My code:

CreateNote(title, text){
    if (title.length > 0 && // title is empty?
 $.inArray(title, this.store.notes) < 0) // check the array for duplicates, returns always true, even with duplicates in the store
      this.store.AddNote(new Note(title, text));
  }

So what is wrong with the second check =?

Thanks

Body:
You're not comparing the title to the other note titles, but instead to the note objects.

Assuming that the title is exposed as a title property on the note objects, you'd have to rewrite your condition like this:

$.inArray(title, this.store.notes.map(n => n.title)) < 0

Or with standard JavsScript:

!this.store.notes.some(n => n.title === title)


问:
(Ruby) First x Recursive Nums
I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

```<code>def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end
</code>```

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

答:
A variation of Ilya's answer:</p>

```<code>def each_factorial
  return enum_for(__method__) unless block_given?
  m = 1
  1.step do |i|
    yield m
    m *= i
  end
end

each_factorial.take(6)
#=> [1, 1, 2, 6, 24, 120]
</code>```

Title: (Ruby) First x Recursive Nums

Body:
I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

Body:
A variation of Ilya's answer:

def each_factorial
  return enum_for(__method__) unless block_given?
  m = 1
  1.step do |i|
    yield m
    m *= i
  end
end

each_factorial.take(6)
#=> [1, 1, 2, 6, 24, 120]


问:
Faces missing when drawing icosahedron in OpenGL following code in redBook
I am attempting to draw an icosahedron following this popular OpenGl tutorial in the redBook.

I am using GLUT to handle windowing.

Here is my complete code. It is mostly the code from the tutorial plus some clerical work using GLUT

#include <stdio.h>
#include <GL/glut.h>
#define X .525731112119133606
#define Z .850650808352039932

void mouseEventHandler(int button, int state, int x, int y){
}

void display() {
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    static GLfloat vdata[12][3] = {
        {-X,0.0,Z}, {X,0.0,Z}, {-X,0.0,-Z}, {X,0.0,-Z},
        {0.0,Z,X}, {0.0,Z,-X}, {0.0,-Z,X}, {0.0,-Z,-X},
        {Z,X,0.0}, {-Z,X,0.0}, {Z,-X,0.0}, {-Z,-X,0.0},
    };

    static GLuint tindices[20][3] = {
        {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
        {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
        {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
        {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} };

    int i;

    glBegin(GL_TRIANGLES);
    for (i = 0; i < 20; i++){
        glNormal3fv(&vdata[tindices[i][0]][0]);
        glVertex3fv(&vdata[tindices[i][0]][0]);
        glNormal3fv(&vdata[tindices[i][1]][0]);
        glVertex3fv(&vdata[tindices[i][1]][0]);
        glNormal3fv(&vdata[tindices[i][2]][0]);
        glVertex3fv(&vdata[tindices[i][2]][0]);
    }
    glEnd();
    glFlush ( );
}

void windowSetup(){
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

    glutInitWindowPosition(80, 80);
    glutInitWindowSize(1000,1000);

    glutCreateWindow("OpenGL Ico");

    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode( GL_MODELVIEW);
    glLoadIdentity();
    gluOrtho2D( -2.0, 2.0, -2.0, 2.0 );
}

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

    glutInit(&argc, argv);
    windowSetup();

    glutDisplayFunc(display);
    glutMouseFunc(&mouseEventHandler);
    glutMainLoop();
}
```

This is my output:

This is very different from the expected output:

Does someone know why these differ so much?

The differences seem to be:

My icosahedron is missing faces

My icosahedron is being viewed from a different angle

My icosahedron is lit differently

The first one is the most pressing. I have noticed when I change glMatrixMode( GL_MODELVIEW); to glMatrixMode( GL_PROJECTION); the faces that aren't showing up appear and those that are currenty appearing disappear. Does anybody know why this could be?

答:
missing faces

most likely you just have wrong order of indices. In such case Reversing them will solve the issue. To check this you can try:

```<code>glDisable(GL_CULL_FACE);
</code>```

if problem disappears I am right. If not it is different thing (like too close to camera cutting by Z_NEAR but that would look a bit different).

To identify the correct face you can use glColor based on i for exaple

```<code>if (i==5) glColor3f(1.0,0.0,0.0); else glColor3f(1.0,1.0,1.0);
</code>```

the red face would be the 6th in this case {8,3,10}

lighting

You are using vertex coordinates as normals so do not expect FLAT shading. Also I do not see you are setting any lights here (but that can be hidden in GLUT somewhere I do not use it). To remedy this use just single normal per triangle. so average the 3 normals you got and make an unit vector from that and use that (before first glVertex call of each triangle).

orientation

just rotate your GL_MODELVIEW to desired orientation. Standard perspective GL_PROJECTION has z axis as viewing direction and x,y axises matches the screen (while GL_MODELVIEW is unit)

[Edit1] I tried your code

So the problem is you got reverse order of indices then default polygon winding in OpenGL (at least in my environment) and wrong normals here fixed code:

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
const GLfloat vdata[12][3] =
    {
    {-X,0.0,Z}, {X,0.0,Z}, {-X,0.0,-Z}, {X,0.0,-Z},
    {0.0,Z,X}, {0.0,Z,-X}, {0.0,-Z,X}, {0.0,-Z,-X},
    {Z,X,0.0}, {-Z,X,0.0}, {Z,-X,0.0}, {-Z,-X,0.0},
    };

const GLuint tindices[20][3] =
    {
    {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
    {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
    {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
    {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11}
    };

int i;
GLfloat nx,ny,nz;

glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
glBegin(GL_TRIANGLES);
for (i = 0; i < 20; i++)
    {
    nx =vdata[tindices[i][0]][0];
    ny =vdata[tindices[i][0]][1];
    nz =vdata[tindices[i][0]][2];
    nx+=vdata[tindices[i][1]][0];
    ny+=vdata[tindices[i][1]][1];
    nz+=vdata[tindices[i][1]][2];
    nx+=vdata[tindices[i][2]][0]; nx/=3.0;
    ny+=vdata[tindices[i][2]][1]; ny/=3.0;
    nz+=vdata[tindices[i][2]][2]; nz/=3.0;
    glNormal3f(nx,ny,nz);
    glVertex3fv(vdata[tindices[i][0]]);
    glVertex3fv(vdata[tindices[i][1]]);
    glVertex3fv(vdata[tindices[i][2]]);
    }
glEnd();
```

And preview:

it is a screenshot and my object is rotating so do not expect correct orientation you expect.

Body:
I am attempting to draw an icosahedron following this popular OpenGl tutorial in the redBook.

I am using GLUT to handle windowing.

Here is my complete code. It is mostly the code from the tutorial plus some clerical work using GLUT

#include <stdio.h>
#include <GL/glut.h>
#define X .525731112119133606
#define Z .850650808352039932

void mouseEventHandler(int button, int state, int x, int y){
}

void display() {
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    static GLfloat vdata[12][3] = {
        {-X,0.0,Z}, {X,0.0,Z}, {-X,0.0,-Z}, {X,0.0,-Z},
        {0.0,Z,X}, {0.0,Z,-X}, {0.0,-Z,X}, {0.0,-Z,-X},
        {Z,X,0.0}, {-Z,X,0.0}, {Z,-X,0.0}, {-Z,-X,0.0},
    };

    static GLuint tindices[20][3] = {
        {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
        {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
        {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
        {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} };

    int i;

    glBegin(GL_TRIANGLES);
    for (i = 0; i < 20; i++){
        glNormal3fv(&vdata[tindices[i][0]][0]);
        glVertex3fv(&vdata[tindices[i][0]][0]);
        glNormal3fv(&vdata[tindices[i][1]][0]);
        glVertex3fv(&vdata[tindices[i][1]][0]);
        glNormal3fv(&vdata[tindices[i][2]][0]);
        glVertex3fv(&vdata[tindices[i][2]][0]);
    }
    glEnd();
    glFlush ( );
}

void windowSetup(){
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

    glutInitWindowPosition(80, 80);
    glutInitWindowSize(1000,1000);

    glutCreateWindow("OpenGL Ico");

    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode( GL_MODELVIEW);
    glLoadIdentity();
    gluOrtho2D( -2.0, 2.0, -2.0, 2.0 );
}

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

    glutInit(&argc, argv);
    windowSetup();

    glutDisplayFunc(display);
    glutMouseFunc(&mouseEventHandler);
    glutMainLoop();
}

This is my output:

This is very different from the expected output:

Does someone know why these differ so much?

The differences seem to be:

My icosahedron is missing faces

My icosahedron is being viewed from a different angle

My icosahedron is lit differently

The first one is the most pressing. I have noticed when I change glMatrixMode( GL_MODELVIEW); to glMatrixMode( GL_PROJECTION); the faces that aren't showing up appear and those that are currenty appearing disappear. Does anybody know why this could be?

Body:
missing faces

most likely you just have wrong order of indices. In such case Reversing them will solve the issue. To check this you can try:

glDisable(GL_CULL_FACE);

if problem disappears I am right. If not it is different thing (like too close to camera cutting by Z_NEAR but that would look a bit different).

To identify the correct face you can use glColor based on i for exaple

if (i==5) glColor3f(1.0,0.0,0.0); else glColor3f(1.0,1.0,1.0);

the red face would be the 6th in this case {8,3,10}

lighting

You are using vertex coordinates as normals so do not expect FLAT shading. Also I do not see you are setting any lights here (but that can be hidden in GLUT somewhere I do not use it). To remedy this use just single normal per triangle. so average the 3 normals you got and make an unit vector from that and use that (before first glVertex call of each triangle).

orientation

just rotate your GL_MODELVIEW to desired orientation. Standard perspective GL_PROJECTION has z axis as viewing direction and x,y axises matches the screen (while GL_MODELVIEW is unit)

[Edit1] I tried your code

So the problem is you got reverse order of indices then default polygon winding in OpenGL (at least in my environment) and wrong normals here fixed code:

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
const GLfloat vdata[12][3] =
    {
    {-X,0.0,Z}, {X,0.0,Z}, {-X,0.0,-Z}, {X,0.0,-Z},
    {0.0,Z,X}, {0.0,Z,-X}, {0.0,-Z,X}, {0.0,-Z,-X},
    {Z,X,0.0}, {-Z,X,0.0}, {Z,-X,0.0}, {-Z,-X,0.0},
    };

const GLuint tindices[20][3] =
    {
    {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
    {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
    {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
    {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11}
    };

int i;
GLfloat nx,ny,nz;

glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
glBegin(GL_TRIANGLES);
for (i = 0; i < 20; i++)
    {
    nx =vdata[tindices[i][0]][0];
    ny =vdata[tindices[i][0]][1];
    nz =vdata[tindices[i][0]][2];
    nx+=vdata[tindices[i][1]][0];
    ny+=vdata[tindices[i][1]][1];
    nz+=vdata[tindices[i][1]][2];
    nx+=vdata[tindices[i][2]][0]; nx/=3.0;
    ny+=vdata[tindices[i][2]][1]; ny/=3.0;
    nz+=vdata[tindices[i][2]][2]; nz/=3.0;
    glNormal3f(nx,ny,nz);
    glVertex3fv(vdata[tindices[i][0]]);
    glVertex3fv(vdata[tindices[i][1]]);
    glVertex3fv(vdata[tindices[i][2]]);
    }
glEnd();

And preview:

it is a screenshot and my object is rotating so do not expect correct orientation you expect.


问:
Simple Math with JS
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

答:
Here, this one is pure javascript, try not to overcomplicate things

1500$

```

Title: Simple Math with JS

Body:
Here, this one is pure javascript, try not to overcomplicate things

<html>
<body>

    <div id="num">1500$</div>
    <div id="num2"></div>

    <script>
        var number = document.getElementById("num").innerHTML.replace("$", "");
        number = number / (2 * 6);
        document.getElementById("num2").innerHTML = "Pay as low as " + number + " here";
    </script>

</body>
</html>


问:
create a rest api in django-rest-framework with relation
create a rest api in django-rest-framework

I have 2 tables

Fist table: User

```<code>id   | PK
Name | varchar(255)
</code>```

Second table: address

```<code>id      | PK
address | varchar(255)
city_id | int
user_id | FK
</code>```

Now when i hit query on User I also want user address in Json format

Like this

```<code>[
  {
    "id": 98,
    "name": "rijoj@selectsourceintl.com",

    "address": [
      {
        "id": 51,
        "city_id": 5,
        "addrss": "New York",
      },
      {
        "id": 61,
        "city_id": 5,
        "addrss": "California",
      },
    ]
  }
]
</code>```

答:
models.py-

```<code>class User(models.Model):
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

class Address (models.Model):
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='addresses')
</code>```

Note - id field is autoincrementing and in-built in django, you don't need to specify it directly.
Following is a demonstration how should you link your user obj and address obj.

```<code>>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()
</code>```

Later you can access the address from the user object as -

```<code>>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.addresses.all() (will give the data)
</code>```

Now install django-restframework

views.py -

```<code>from rest_framework.generics import RetrieveAPIView
from .serializers import UserDetailSerializer

class UserAPIView(RetrieveAPIView):
      serializer_class = UserDetailSerializer
      lookup_field = 'id'
      queryset = User.objects.all()
</code>```

serializers.py -

```<code>from .models import User,Address
from rest_framework import serializers

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('id', 'city_id', 'address')

class UserDetailSerializer(serializers.ModelSerializer):
    address = AddressSerializer(many=True)
    class Meta:
           model = User
           fields = (
              'id',
              'name',
              'address'
           )
</code>```

urls.py

```<code>from django.conf.urls import url

from reports.views import UserAPIView

urlpatterns = [
    url(r'^users/(?P<id>[0-9]+)/$',UserAPIView.as_view(), name= 'users'),
]
</code>```

Body:
create a rest api in django-rest-framework

I have 2 tables

Fist table: User

id   | PK
Name | varchar(255)

Second table: address

id      | PK
address | varchar(255)
city_id | int
user_id | FK

Now when i hit query on User I also want user address in Json format

Like this

[
  {
    "id": 98,
    "name": "rijoj@selectsourceintl.com",

    "address": [
      {
        "id": 51,
        "city_id": 5,
        "addrss": "New York",
      },
      {
        "id": 61,
        "city_id": 5,
        "addrss": "California",
      },
    ]
  }
]

Body:
models.py-

class User(models.Model):
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

class Address (models.Model):
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='addresses')

Note - id field is autoincrementing and in-built in django, you don't need to specify it directly.
Following is a demonstration how should you link your user obj and address obj.

>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()

Later you can access the address from the user object as -

>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.addresses.all() (will give the data)

Now install django-restframework

views.py -

from rest_framework.generics import RetrieveAPIView
from .serializers import UserDetailSerializer

class UserAPIView(RetrieveAPIView):
      serializer_class = UserDetailSerializer
      lookup_field = 'id'
      queryset = User.objects.all()

serializers.py -

from .models import User,Address
from rest_framework import serializers

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('id', 'city_id', 'address')

class UserDetailSerializer(serializers.ModelSerializer):
    address = AddressSerializer(many=True)
    class Meta:
           model = User
           fields = (
              'id',
              'name',
              'address'
           )

urls.py

from django.conf.urls import url

from reports.views import UserAPIView

urlpatterns = [
    url(r'^users/(?P<id>[0-9]+)/$',UserAPIView.as_view(), name= 'users'),
]


问:
Sending an array over a socket with Java
I have an 2-dimensional array to send over the socket
The client is implemented so that it has 2 threads, one for rendering the swing gui and one for RECEIVING the data from server.

The server is implemented so that it has 2 threads, one for listening to incoming request and then put the request to another thread for processing the request (communicating with client)

Once the client interact with the swing gui, data will be constructed and sent to the server (actually, send to the thread which is in charge of processing the particular client), the server then processes the data and send back to client with a new data in an 2-dimensional array with updated information. The client can use the array to render the view.

However, when the first time the client send data, it ok, everything is fine. But the next time, client send new data, but it still receive the old one (server data is still updating)

I dont know if the problem is with the socket itself or the thread.

答: If you are using Serialization, see the Javadoc for ObjectOutputStream.reset() and ObjectOutputStream.writeUnshared().</p>


问:
I need my applescript to run ONLY if Chrome is in focus
I am triggering an AppleScript with a keyboard shortcut. Works great. But I need the script to run ONLY if Google Chrome is currently in focus. All of the possibly relevant examples I've found are very complex (at least for me) and don't really do what I need.  Is there a simple "if" syntax I can use? If not, what's the simplest solution? Here's what I have:  </p>

```<code>tell application "Google Chrome"
    delete tab (active tab index of window 1) of window 1
end tell

tell application "Mail"
    activate
end tell
</code>```

答:
Every application has a frontmost property

```<code>if application "Google Chrome" is frontmost then
    tell application "Google Chrome" to delete tab (active tab index of window 1) of window 1
    activate application "Mail"
end if
</code>```

Body:
I am triggering an AppleScript with a keyboard shortcut. Works great. But I need the script to run ONLY if Google Chrome is currently in focus. All of the possibly relevant examples I've found are very complex (at least for me) and don't really do what I need.  Is there a simple "if" syntax I can use? If not, what's the simplest solution? Here's what I have:

tell application "Google Chrome"
    delete tab (active tab index of window 1) of window 1
end tell

tell application "Mail"
    activate
end tell

Body:
Every application has a frontmost property

if application "Google Chrome" is frontmost then
    tell application "Google Chrome" to delete tab (active tab index of window 1) of window 1
    activate application "Mail"
end if


问:
ionic button on list item without ui-sref list item navigation
I've created an ionic list with a ui-sref so that when an item is clicked on, it navigates to a specific page.  I have also placed a button in the upper right corner of each list item that toggles on and off (sort of like a bookmark).  However, when I click the button to toggle the bookmark, the ui-sref is also triggered, causing an unwanted page navigation.  Is there any way to isolate the button in an ionic list item so when clicked, the list item navigation is not triggered?

Here is my list item code with the button:

```<code><ion-item ng-class="{'save': item.save}" collection-repeat="item in items" ui-sref="tab.page({id:item.$id})">
  <button class="icon button top-right" ng-click="item.save = !item.save" ng-class="{'ion-ios-heart button-clear button-assertive':item.save, 'ion-ios-heart-outline  button-clear button-stable':!item.save}"></button>
</ion-item>
</code>```

答:
You used ui-sref directive in your ion-item, that make it as a link ( like  tag ) and then you add your button in between, so of-course when you click on the button, it will do the page navigation.

You need to define your button outside.

```<code><ion-item ng-class="{'save': item.save}" collection-repeat="item in items" ui-sref="tab.page({id:item.$id})">
</ion-item>

<button class="icon button top-right" ng-click="item.save = !item.save" ng-class="{'ion-ios-heart button-clear button-assertive':item.save, 'ion-ios-heart-outline  button-clear button-stable':!item.save}"></button>
</code>```

Update :
basically, when you have button inside a link tag, button called first and right after the link triggered. so what you need to do is somehow return false for your ui-sref eveent if button clicked.

Since you are using angularjs, you can do this ( I didn't test it, but it should work, let me know if this worked ) :

1 - add ng-click on your ion-item

```<code><ion-item ng-click="isNavigation()" ng-class="{'save': item.save}" collection-repeat="item in items" ui-sref="tab.page({id:item.$id})">
</code>```

2 - change your button ng-click to use a function

```<code><button class="icon button top-right" ng-click="myFunctionName(item.save)" ng-class="{'ion-ios-heart button-clear button-assertive':item.save, 'ion-ios-heart-outline  button-clear button-stable':!item.save}"></button>
</code>```

3 - in your controller :

```<code>$rootScope.isNavigation=true;
$scope.isNavigation=function(){
    if($rootScope.isNavigation)
         return true;
    else
        return false;
}
$scope.myFunctionName(item){
  $rootScope.isNavigation=false;
  return item.save = !item.save;
}
</code>```

Body:
I've created an ionic list with a ui-sref so that when an item is clicked on, it navigates to a specific page.  I have also placed a button in the upper right corner of each list item that toggles on and off (sort of like a bookmark).  However, when I click the button to toggle the bookmark, the ui-sref is also triggered, causing an unwanted page navigation.  Is there any way to isolate the button in an ionic list item so when clicked, the list item navigation is not triggered?

Here is my list item code with the button:

<ion-item ng-class="{'save': item.save}" collection-repeat="item in items" ui-sref="tab.page({id:item.$id})">
  <button class="icon button top-right" ng-click="item.save = !item.save" ng-class="{'ion-ios-heart button-clear button-assertive':item.save, 'ion-ios-heart-outline  button-clear button-stable':!item.save}"></button>
</ion-item>

Body:
You used ui-sref directive in your ion-item, that make it as a link ( like <a> tag ) and then you add your button in between, so of-course when you click on the button, it will do the page navigation.

You need to define your button outside.

<ion-item ng-class="{'save': item.save}" collection-repeat="item in items" ui-sref="tab.page({id:item.$id})">
</ion-item>

<button class="icon button top-right" ng-click="item.save = !item.save" ng-class="{'ion-ios-heart button-clear button-assertive':item.save, 'ion-ios-heart-outline  button-clear button-stable':!item.save}"></button>

Update :
basically, when you have button inside a link tag, button called first and right after the link triggered. so what you need to do is somehow return false for your ui-sref eveent if button clicked.

Since you are using angularjs, you can do this ( I didn't test it, but it should work, let me know if this worked ) :

1 - add ng-click on your ion-item

<ion-item ng-click="isNavigation()" ng-class="{'save': item.save}" collection-repeat="item in items" ui-sref="tab.page({id:item.$id})">

2 - change your button ng-click to use a function

<button class="icon button top-right" ng-click="myFunctionName(item.save)" ng-class="{'ion-ios-heart button-clear button-assertive':item.save, 'ion-ios-heart-outline  button-clear button-stable':!item.save}"></button>

3 - in your controller :

$rootScope.isNavigation=true;
$scope.isNavigation=function(){
    if($rootScope.isNavigation)
         return true;
    else
        return false;
}
$scope.myFunctionName(item){
  $rootScope.isNavigation=false;
  return item.save = !item.save;
}


问:
Flink assurance of ordered streams
From my little experience with Flink I have noticed that even If we have events arriving at the order they should be arriving after partitioning the order is lost. This is discussed here:
Ordering of Records in Stream

So I have 3 questions that extend the question mentioned above:

The reason the order is lost after the keyBy function is still unclear to me. Why does that happen?

Is there a way to ensure the order of the events even after the partitioning?

If we do not create KeyedStreams, is the order of the events guaranteed per parallel operator?

答:
I think there might have been some misunderstanding here. I'll try to reclarify some things here:

The ordering of elements will be retained for elements emitted from the same operator with the same key. However, on the receiving side after the partitioning, there isn't any strict ordering if you account for all the records with the same key that it receives, simply because ordering is guaranteed for per-parallel operator.

Title: Flink assurance of ordered streams