问:
Sending emails through SMTP with PHPMailer
I'm trying to send SMTP e-mails using PHPMailer, but I keep getting this error message, any ideas how to get rid of it?

I'm trying to connect via SSL on port 465.

```<code>SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:

Notice: fputs() [function.fputs]: send of 18 bytes failed with errno=32 Roura přerušena (SIGPIPE) in /home/www/amazonek.cz/subdomains/library/PHPMailer_v5.1/class.smtp.php on line 494
SMTP -> FROM SERVER:
SMTP -> ERROR: HELO not accepted from server:

Notice: fputs() [function.fputs]: send of 12 bytes failed with errno=32 Roura přerušena (SIGPIPE) in /home/www/amazonek.cz/subdomains/library/PHPMailer_v5.1/class.smtp.php on line 212
SMTP -> ERROR: AUTH not accepted from server:
SMTP Error: Could not authenticate.
</code>```

My code:

```<code>  require_once('../library/PHPMailer_v5.1/class.phpmailer.php');

        try{
            $mail = new PHPMailer(true);
            $mail->IsSMTP();
            $mail->SMTPAuth = true;
            $mail->Host = SMTP_SERVER;
            $mail->Port = SMTP_PORT;
            $mail->Username = SMTP_USERNAME;
            $mail->Password = SMTP_PASSWORD;
            $mail->SMTPDebug = 2;
            $mail->SetFrom(MAIL_ORDERS_ADDRESS, MAIL_ORDERS_NAME);
            $mail->Subject = 'AMAZONEK.cz - objednávka číslo '.$_SESSION['orderId'];
            $mail->MsgHTML('<b>Ahoj</b>');
            $mail->AddAddress($_SESSION['user']['email'], $_SESSION['user']['name'].' '.$_SESSION['user']['surname']);
            $mail->AddBCC(MAIL_ORDERS_ADDRESS, MAIL_ORDERS_NAME);

            if(!$mail->Send()) throw new Exception($mail->ErrorInfo);
        }
        catch(Exception $e){
            echo $e->getMessage();
        }
</code>```

Constants definition:

```<code>define('SMTP_SERVER', 'smtp.ebola.cz');
define('SMTP_PORT', 465);
define('SMTP_USERNAME', 'myEmail@myDomain.tld');
define('SMTP_PASSWORD', '***CENSORED***');

define('MAIL_ORDERS_ADDRESS', 'myEmail@myDomain.tld');
define('MAIL_ORDERS_NAME', 'My Name');
</code>```

Any ideas?

答: Yes, you need OpenSSL to work correctly.  My backup testing site worked, my live server didn't.  Difference?  Live server didn't have OpenSSL within PHP configuration.</p>

Body:
I'm trying to send SMTP e-mails using PHPMailer, but I keep getting this error message, any ideas how to get rid of it?

I'm trying to connect via SSL on port 465.

SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:

Notice: fputs() [function.fputs]: send of 18 bytes failed with errno=32 Roura přerušena (SIGPIPE) in /home/www/amazonek.cz/subdomains/library/PHPMailer_v5.1/class.smtp.php on line 494
SMTP -> FROM SERVER:
SMTP -> ERROR: HELO not accepted from server:

Notice: fputs() [function.fputs]: send of 12 bytes failed with errno=32 Roura přerušena (SIGPIPE) in /home/www/amazonek.cz/subdomains/library/PHPMailer_v5.1/class.smtp.php on line 212
SMTP -> ERROR: AUTH not accepted from server:
SMTP Error: Could not authenticate.

My code:

  require_once('../library/PHPMailer_v5.1/class.phpmailer.php');

        try{
            $mail = new PHPMailer(true);
            $mail->IsSMTP();
            $mail->SMTPAuth = true;
            $mail->Host = SMTP_SERVER;
            $mail->Port = SMTP_PORT;
            $mail->Username = SMTP_USERNAME;
            $mail->Password = SMTP_PASSWORD;
            $mail->SMTPDebug = 2;
            $mail->SetFrom(MAIL_ORDERS_ADDRESS, MAIL_ORDERS_NAME);
            $mail->Subject = 'AMAZONEK.cz - objednávka číslo '.$_SESSION['orderId'];
            $mail->MsgHTML('Ahoj');
            $mail->AddAddress($_SESSION['user']['email'], $_SESSION['user']['name'].' '.$_SESSION['user']['surname']);
            $mail->AddBCC(MAIL_ORDERS_ADDRESS, MAIL_ORDERS_NAME);

            if(!$mail->Send()) throw new Exception($mail->ErrorInfo);
        }
        catch(Exception $e){
            echo $e->getMessage();
        }

Constants definition:

define('SMTP_SERVER', 'smtp.ebola.cz');
define('SMTP_PORT', 465);
define('SMTP_USERNAME', 'myEmail@myDomain.tld');
define('SMTP_PASSWORD', '***CENSORED***');

define('MAIL_ORDERS_ADDRESS', 'myEmail@myDomain.tld');
define('MAIL_ORDERS_NAME', 'My Name');

Any ideas?


来源: stackexchange

问:
Python Json. Getting only the last element in the json array
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

```<code>[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]
</code>```

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

```<code>rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
</code>```

when i return the value, i get

```<code>{
  "Ingreient ID": 19682
}
</code>```

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

答:
What you're doing right now is that you're redefining value again every loop. You will need to define value before the loop and assign it to an empty list that you can add to.

```<code>value = {'Ingredient ID':[]}
for records in rec:
    value['Ingredient ID'].append(records['IngredientID'])
</code>```

You can also define value as a list like this:

```<code>value = []
for records in rec:
    value.append(records['IngredientID'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }

when i return the value, i get

{
  "Ingreient ID": 19682
}

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

Body:
What you're doing right now is that you're redefining value again every loop. You will need to define value before the loop and assign it to an empty list that you can add to.

value = {'Ingredient ID':[]}
for records in rec:
    value['Ingredient ID'].append(records['IngredientID'])

You can also define value as a list like this:

value = []
for records in rec:
    value.append(records['IngredientID'])


问:
What are the different build-in filters available in Angular.js?
What are the different build-in filters available in Angular.js can anyone explain me with example.

答:
You can check them on angular js documentation....any way here are some links with some examples....Hope these will help you to understand how they works in angular js
https://www.w3schools.com/angular/angular_filters.asp

https://docs.angularjs.org/api/ng/filter/filter

http://www.programming-free.com/2013/10/exploring-angularjs-built-in-filters.html


答:
You're overwriting the value inside the loop. So, the final result would be the last ingredient_id in the json. Try instead try adding the value to a list:

```<code>myList = []

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
            myList.append(value)
</code>```

myList will have all the ingredients

You can even have a one liner to do this:

[r['IngredientID'] for r in rec]

This will give a list as ['1142',1523,..]

Title: Python Json. Getting only the last element in the json array

Body:
You're overwriting the value inside the loop. So, the final result would be the last ingredient_id in the json. Try instead try adding the value to a list:

myList = []

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
            myList.append(value)

myList will have all the ingredients

You can even have a one liner to do this:

[r['IngredientID'] for r in rec]

This will give a list as ['1142',1523,..]


答:
You are re-assigning variable value everytime. Hence you are getting the last element. Instead you should try

```<code># Your code
value = []
for records in rec:
    value.append(records['IngredientID']);

# print value     # this will have all required IngredientID
</code>```

Body:
You are re-assigning variable value everytime. Hence you are getting the last element. Instead you should try

# Your code
value = []
for records in rec:
    value.append(records['IngredientID']);

# print value     # this will have all required IngredientID


问:
How to work with Vue.js and Semantic UI?
I love Vue.js and would like to incorporate that into Semantic UI. I'm very new to all of this so this may not come out correctly. I've looked in many places to see how to put the two together, like here, and it gets very overwhelming.

Then I thought why can't I just install Semantic UI and link to the vuejs CDN so I can use that. Is that a legitimate way to integrate the two? Could I also do the reverse and install vue-cli and link to the Semantic CDN?

I feel like I'm missing something here but using these two inside of webpack and making sure dependencies are setup and working properly is way too big for me.

I like the idea of Vuetify.js and Element, but I don't like the possibility of these integrations going to the wayside soon and being "stuck" with it and having to learn something else in the near future.

答:
At the end of the day these are just javascript and css files. Include them into your html and start coding. These complicated build processes you mentioned are suited for large applications that require the overhead of webpack.

I've never used Semantic but it looks to be just a widget library, while Vue is a view framework. There is no special set up required to get these 2 to work with each other, just start adding Semantic elements into your Vue templates.


问:
Removing code for mobile screen menu
I have the following code which adds/removes a .show-nav and .hide-nav class to my navigation. This is applied to the  .mobile-nav div with the .toggle-nav button.

functions.php

```<code>$(function() {

// Bind a click event to anything with the class "toggle-nav"
$('.toggle-nav').click(function() {
    if ($('.mobile-nav').hasClass('show-nav')) {
        $('.mobile-nav').removeClass('show-nav').addClass('hide-nav');

        setTimeout(function() {
            $('.mobile-nav').removeClass('hide-nav');
        }, 500);

    } else {
        $('.mobile-nav').removeClass('hide-nav').addClass('show-nav');
    }

    return false;
});

});
</code>```

.mobile-nav is a full screen overlay menu which I only want to use on mobile devices so I remove the .toggle-nav button on screen size ( >768px). .mobile-nav remains invisible until .toggle-nav is clicked.

css

```<code>.toggle-nav { display: none; }

@media screen and (max-width: 768px) {

.toggle-nav { display: inline-block; }
}
</code>```

Problem is if the mobile-nav is 'opened' and the user makes the screen large, the toggle-nav button is hidden but the menu remains open.

Basically, I want the class .hide-nav applied (or .show-nav is removed) if the screen goes larger than 768px.

答:
I have created a short example of  things need to be done. Added some jquery codes to make it work the way you want .

Step 1 - Add class hide-nav on window width

```<code> /* logic For window width */
  if ($(window).width() > 768) {
    $('.mobile-nav').addClass('hide-nav');
  } else {
    $('.mobile-nav').removeClass('hide-nav');
  }
</code>```

Step 2 - Add class hide-nav on window resize

```<code>  /* logic For Window Resize */
  function resize() {
    if ($(window).width() > 768) {
      $('.mobile-nav').addClass('hide-nav');
    }

    $('.mobile-nav').addClass('hide-nav');
  }

  $(window).resize(resize)
    .trigger('resize');
</code>```

$(function() {

  // Bind a click event to anything with the class "toggle-nav"
  $('.toggle-nav').click(function() {
    if ($('.mobile-nav').hasClass('show-nav')) {
      $('.mobile-nav').removeClass('show-nav').addClass('hide-nav');

      setTimeout(function() {
        $('.mobile-nav').removeClass('hide-nav');
      }, 500);

    } else {
      $('.mobile-nav').removeClass('hide-nav').addClass('show-nav');
    }

    return false;
  });

  /* logic For window width */
  if ($(window).width() > 768) {
    $('.mobile-nav').addClass('hide-nav');
    $('.mobile-nav').removeClass('show-nav');
  } else {
    $('.mobile-nav').removeClass('hide-nav');
  }

  /* logic For Window Resize */
  function resize() {
    if ($(window).width() > 768) {
      $('.mobile-nav').addClass('hide-nav');
      $('.mobile-nav').removeClass('show-nav');
    }

    $('.mobile-nav').addClass('hide-nav');
  }

  $(window).resize(resize)
    .trigger('resize');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mobile-nav {
  width: 100px;
  height: 100px;
  background: red;
}

.show-nav {
  display: block;
}

.hide-nav {
  display: none
}

.toggle-nav {
  display: none;
}

@media screen and (max-width: 768px) {
  .toggle-nav {
    display: inline-block;
  }
}</code>```

Toggle Nav

```

Title: Removing code for mobile screen menu

Body:
I have the following code which adds/removes a .show-nav and .hide-nav class to my navigation. This is applied to the  .mobile-nav div with the .toggle-nav button.

functions.php

$(function() {

// Bind a click event to anything with the class "toggle-nav"
$('.toggle-nav').click(function() {
    if ($('.mobile-nav').hasClass('show-nav')) {
        $('.mobile-nav').removeClass('show-nav').addClass('hide-nav');

        setTimeout(function() {
            $('.mobile-nav').removeClass('hide-nav');
        }, 500);

    } else {
        $('.mobile-nav').removeClass('hide-nav').addClass('show-nav');
    }

    return false;
});

});

.mobile-nav is a full screen overlay menu which I only want to use on mobile devices so I remove the .toggle-nav button on screen size ( >768px). .mobile-nav remains invisible until .toggle-nav is clicked.

css

.toggle-nav { display: none; }

@media screen and (max-width: 768px) {

.toggle-nav { display: inline-block; }
}

Problem is if the mobile-nav is 'opened' and the user makes the screen large, the toggle-nav button is hidden but the menu remains open.

Basically, I want the class .hide-nav applied (or .show-nav is removed) if the screen goes larger than 768px.

Body:
I have created a short example of  things need to be done. Added some jquery codes to make it work the way you want .

Step 1 - Add class hide-nav on window width

 /* logic For window width */
  if ($(window).width() > 768) {
    $('.mobile-nav').addClass('hide-nav');
  } else {
    $('.mobile-nav').removeClass('hide-nav');
  }

Step 2 - Add class hide-nav on window resize

  /* logic For Window Resize */
  function resize() {
    if ($(window).width() > 768) {
      $('.mobile-nav').addClass('hide-nav');
    }

    $('.mobile-nav').addClass('hide-nav');
  }

  $(window).resize(resize)
    .trigger('resize');

$(function() {

  // Bind a click event to anything with the class "toggle-nav"
  $('.toggle-nav').click(function() {
    if ($('.mobile-nav').hasClass('show-nav')) {
      $('.mobile-nav').removeClass('show-nav').addClass('hide-nav');

      setTimeout(function() {
        $('.mobile-nav').removeClass('hide-nav');
      }, 500);

    } else {
      $('.mobile-nav').removeClass('hide-nav').addClass('show-nav');
    }

    return false;
  });

  /* logic For window width */
  if ($(window).width() > 768) {
    $('.mobile-nav').addClass('hide-nav');
    $('.mobile-nav').removeClass('show-nav');
  } else {
    $('.mobile-nav').removeClass('hide-nav');
  }

  /* logic For Window Resize */
  function resize() {
    if ($(window).width() > 768) {
      $('.mobile-nav').addClass('hide-nav');
      $('.mobile-nav').removeClass('show-nav');
    }

    $('.mobile-nav').addClass('hide-nav');
  }

  $(window).resize(resize)
    .trigger('resize');

});

.mobile-nav {
  width: 100px;
  height: 100px;
  background: red;
}

.show-nav {
  display: block;
}

.hide-nav {
  display: none
}

.toggle-nav {
  display: none;
}

@media screen and (max-width: 768px) {
  .toggle-nav {
    display: inline-block;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggle-nav">Toggle Nav</div>

<div class="mobile-nav"></div>


答:
You are replacing the value every time through that loop.  You should be adding to the value, instead.

So first create the value as an empty list (before the loop), then on each iteration of the loop, append to that list:

```<code>value = []
rec = recipes['Recipes'][0]['Ingredients']
for records in rec:
    value.append({'Ingredient ID': records['IngredientID']})
</code>```

However, having a list of dictionaries, where each dictionary has one single value with the same known key, seems a bit pointless.  Depending on your requirements, you probably may want to do either this:

```<code>    value.append(rec)
</code>```

or

```<code>    value.append(records['IngredientID'])
</code>```

Body:
You are replacing the value every time through that loop.  You should be adding to the value, instead.

So first create the value as an empty list (before the loop), then on each iteration of the loop, append to that list:

value = []
rec = recipes['Recipes'][0]['Ingredients']
for records in rec:
    value.append({'Ingredient ID': records['IngredientID']})

However, having a list of dictionaries, where each dictionary has one single value with the same known key, seems a bit pointless.  Depending on your requirements, you probably may want to do either this:

    value.append(rec)

or

    value.append(records['IngredientID'])


问:
Print in python 3.4.2
I have typed print ("Hello World!") into python 3.4.2 and instead of printing Hello World!  It prints Syntax error: invalid character in identifier. I am a complete beginner and am using a raspberry pi 3</p>

答:
For python, there are two ways to print something. You can either print a variable as a integer, string, float, and boolean

```<code>x=5 #int
y="Hello world" #str
z=3.14 #float
a=True #boolean
print(x)
print(y)
print(z)
print(a)

'''
output:
5
Hello World
3.14
True
'''
</code>```

or you can directly print an integer, string, boolean, and/or float by putting it in the parenthesis like you did.

```<code>print(5) #int
print("Hello world!") #str
print(True) #bool
print(3.14) #float

'''
output:
5
Hello world!
True
3.14
'''
</code>```

your code seems to be correct, there's nothing wrong with it. Make sure you put quotes around the string.

Title: Print in python 3.4.2

Body:
For python, there are two ways to print something. You can either print a variable as a integer, string, float, and boolean

x=5 #int
y="Hello world" #str
z=3.14 #float
a=True #boolean
print(x)
print(y)
print(z)
print(a)

'''
output:
5
Hello World
3.14
True
'''

or you can directly print an integer, string, boolean, and/or float by putting it in the parenthesis like you did.

print(5) #int
print("Hello world!") #str
print(True) #bool
print(3.14) #float

'''
output:
5
Hello world!
True
3.14
'''

your code seems to be correct, there's nothing wrong with it. Make sure you put quotes around the string.


问:
Enable wifi from application
I am trying to enable wifi from application.
I have tried the following:

```<code>Runtime.getRuntime().exec(new String[] {"su", "-c", "svc wifi enable"});
</code>```

And I see that wifi is enabled but I can't find any wifi stations.
The strange thing is that I do find wifi station if I just will do the same from shell just before starting application:

```<code> $ svc enable wifi
</code>```

I don't understand what's the difference between these two scenarios, and how to make it work from application.

I also tried to call script from application which only calls the same command, But I got the same results.

答:
Try this way...</p>

```<code>Runtime.getRuntime().exec(new String[]{"/system/bin/su","-c","svc wifi enable"});
</code>```

Title: Enable wifi from application

Body:
I am trying to enable wifi from application.
I have tried the following:

Runtime.getRuntime().exec(new String[] {"su", "-c", "svc wifi enable"});

And I see that wifi is enabled but I can't find any wifi stations.
The strange thing is that I do find wifi station if I just will do the same from shell just before starting application:

 $ svc enable wifi

I don't understand what's the difference between these two scenarios, and how to make it work from application.

I also tried to call script from application which only calls the same command, But I got the same results.

Body:
Try this way...

Runtime.getRuntime().exec(new String[]{"/system/bin/su","-c","svc wifi enable"});


问:
Java/Android MainActivity Syntax Confusing - Need some Clarification
I'm new to Java and Android development as a whole so I'm sure this question pertains to a gap in knowledge in my part on how Java actually works so I'm hoping someone can help me fill this gap. I've been coding in Python, Javascript, and other OOP languages for a couple years but I'm finding Java/Android Dev to break some of the conventions I've come to know and understand.

Below is a very basic class definition for a MainActivity, I believe it's a part of the standard Android tutorials

```<code>public class MainActivity extends AppCompatActivity {
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    textView = (TextView) findViewById(R.id.textView);

}
</code>```

Overall this code makes perfect sense to me. A class is defined called MainActivity that inherits the AppCompatActivity class and overrides the onCreate method. The instance state is saved, a layout is initialized and then a textView is initialized.

The area of my confusion comes from the textView initialization.

```<code>textView = (TextView) findViewById(R.id.textView);
</code>```

The space between (TextView) and the findViewById method baffles me. Why is this allowed? Shouldn't it be something more like,

```<code>textView = (TextView).findViewById(R.id.textView);
</code>```

Again I'm completely new to Java and still learning the syntax and language constructs but this seems a little strange to me. How can a method be called like this? Thanks again in advance. I've been having a little trouble wording this question for a google search.

答:
Defining this programmatically sentence is standard android java coding

```<code>textView = (TextView) findViewById(R.id.textView);
</code>```

either you can go for

```<code>textView = (TextView) this.findViewById(R.id.textView);
</code>```

For more information please refer link

Body:
I'm new to Java and Android development as a whole so I'm sure this question pertains to a gap in knowledge in my part on how Java actually works so I'm hoping someone can help me fill this gap. I've been coding in Python, Javascript, and other OOP languages for a couple years but I'm finding Java/Android Dev to break some of the conventions I've come to know and understand.

Below is a very basic class definition for a MainActivity, I believe it's a part of the standard Android tutorials

public class MainActivity extends AppCompatActivity {
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    textView = (TextView) findViewById(R.id.textView);

}

Overall this code makes perfect sense to me. A class is defined called MainActivity that inherits the AppCompatActivity class and overrides the onCreate method. The instance state is saved, a layout is initialized and then a textView is initialized.

The area of my confusion comes from the textView initialization.

textView = (TextView) findViewById(R.id.textView);

The space between (TextView) and the findViewById method baffles me. Why is this allowed? Shouldn't it be something more like,

textView = (TextView).findViewById(R.id.textView);

Again I'm completely new to Java and still learning the syntax and language constructs but this seems a little strange to me. How can a method be called like this? Thanks again in advance. I've been having a little trouble wording this question for a google search.

Body:
Defining this programmatically sentence is standard android java coding

textView = (TextView) findViewById(R.id.textView);

either you can go for

textView = (TextView) this.findViewById(R.id.textView);

For more information please refer link


问:
What is the maximum (practical) number of nodes in an Erlang system
I wish to create a platform as a service in the financial markets using Erlang/Elixir. I will provide AWS lambda-style functions in financial markets, but rather than being accessible via web/rest/http, I plan to distribute my own ARM-based hardware terminals to clients (Nvidia Jetson TX2-based or similar, so decent hardware). They will access the functions from these terminals. I want said terminals to be full nodes in the system. So they will use the actor model to message pass to my central servers, and indeed, the terminals might message pass amongst each other if terminal users decide to put their own functions online.

Is this a viable model? Could I run 1000 terminals like this? 100 000? What kinds of limitations might I start bumping into? Is Erlang message routing scalable enough to imagine such a network still being performant if we had soft-real time financial markets streaming data flowing around? (mostly from central servers to terminals, but a good proportion possible moving directly around from terminal to terminal). We could have a system where up to 100k or more different "subscription" data channel processes were available, many of them taking input and producing output every second.

Basically I'd like a canonical guide to the scalability capabilities of an Erlang system something like the above. Ideally I'd also like some guide to the security implications of such a system ie. would global routing tables or any other part of the system be compromisable by a rogue terminal user, or can edge nodes be partly "sealed off" from sensitive parts of the rest of the Erlang network?

Note that I'd want to make heavy use of ports/NIFs for high-compute processes.

答:
I recommend read this carefully and i recommend divide your service to little Micro-Services too.

Another benchmark is Investigating the Scalability Limits of
Distributed Erlang.

In the Joe Armstorng's book programming Erlang, he said:

"A few years ago, when I had my research hat on, I was working with PlanetLab. I had access to the PlanetLab a network, so I installed empty Erlang servers on all the PlanetLab machines (about 450 of them).

I didn’t really know what I would do with the machines, so I just set up the server infrastructure to do something later."

Do not use External ports, use internal drivers which are written in C or C++ instead.


问:
Why does this html table definition not validate?
I'm getting this W3C HTML validation error:

```<code>end tag for "table" which is not finished
</code>```

for this code:

```<code><table id="myTable">
</table>
</code>```

This is my DOCTYPE:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</code>```

I thought that table definition was perfectly fine!?

答:
If you look at the XHTML 1.0 Strict DTD, it specifies that a table requires at least one of TR OR TBODY:

```<code><!ELEMENT table
     (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))>
<!ELEMENT caption  %Inline;>
<!ELEMENT thead    (tr)+>
<!ELEMENT tfoot    (tr)+>
<!ELEMENT tbody    (tr)+>
<!ELEMENT colgroup (col)*>
<!ELEMENT col      EMPTY>
<!ELEMENT tr       (th|td)+>
<!ELEMENT th       %Flow;>
<!ELEMENT td       %Flow;>
</code>```

The TR, in its turn, requires at least one of TH or TD.

The + sign after an element name means it should appear at least once.

ContentLicense: CC BY-SA 2.5

Body:
I'm getting this W3C HTML validation error:

end tag for "table" which is not finished

for this code:

This is my DOCTYPE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

I thought that table definition was perfectly fine!?

Body:
If you look at the XHTML 1.0 Strict DTD, it specifies that a table requires at least one of TR OR TBODY:

<!ELEMENT table
     (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))>
<!ELEMENT caption  %Inline;>
<!ELEMENT thead    (tr)+>
<!ELEMENT tfoot    (tr)+>
<!ELEMENT tbody    (tr)+>
<!ELEMENT colgroup (col)*>
<!ELEMENT col      EMPTY>
<!ELEMENT tr       (th|td)+>
<!ELEMENT th       %Flow;>
<!ELEMENT td       %Flow;>

The TR, in its turn, requires at least one of TH or TD.

The + sign after an element name means it should appear at least once.


答:
One issue with your current implementation is that the value of value will be over-written each time you find a new ingredient ID.  If you need to get a list of values, then you have to make sure that you keep all of the old values even when adding a new one.

If you make values a list and then use append, you'll get all of the values you are looking for:

```<code>values = []
for records in rec:
    ingredient_id = records.get('IngredientID', None)
    if ingredient_id:
        values.append(ingredient_id)
</code>```

It is a good idea to use the dict.get() method to retrieve a value and then check if it exists; otherwise you may end up with an exception.

Body:
One issue with your current implementation is that the value of value will be over-written each time you find a new ingredient ID.  If you need to get a list of values, then you have to make sure that you keep all of the old values even when adding a new one.

If you make values a list and then use append, you'll get all of the values you are looking for:

values = []
for records in rec:
    ingredient_id = records.get('IngredientID', None)
    if ingredient_id:
        values.append(ingredient_id)

It is a good idea to use the dict.get() method to retrieve a value and then check if it exists; otherwise you may end up with an exception.


问:
How to debug on remote AEM server?
While reading online AEM documents, I came across how to run the AEM on debug mode. But How to debug on remote AEM server ?

答: Just as you would debug any Java application. Open the AEM in debug mode (i.e. add -debug <your port> to the startup parameters) and connect to it using your favorite IDE. I don't remember how you do it in Eclipse, but in IntelliJ you just create a new "Remote" run configuration specifying the debugging port.

Title: How to debug on remote AEM server?


问:
Align a child class vertically to parent class
I am developing a webpage in which a user can show the larger image or preview of every thumbnails by hovering it.

I am using this Jquery code to show and center the larger image on the screen responsively.

```<code>var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

      $(self).children('.popup-preview').css("position", "fixed");
      $(self).children('.popup-preview').css("top", ($(window).height() / 2) - ($(self).children('.popup-preview').outerHeight() / 2));
      $(self).children('.popup-preview').css("left", ($(window).width() / 2) - ($(self).children('.popup-preview').outerWidth() / 2));

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);
</code>```

How can I align the larger image vertically the same with the parent class?

Here is my working sample code.

Update: Example is when the thumbnail is on the top or bottom of the screen and was hovered. The larger image should display vertically center of the screen.

答:
Just try changing the postion to absolute

```<code>        var timer;
        $(".theme-preview").hover(function() {
                var self = $(this);

                timer = setTimeout(function(){
                    timer = false;

                    $(self).children('.popup-preview').fadeIn("slow");

                    $(self).children('.popup-preview').css("position","absolute");
                    $(self).children('.popup-preview').css("top", '0');
                    $(self).children('.popup-preview').css("left", 'auto');

                }, 800);

                //return false;
            },
            function () {
                if(timer){
                    clearTimeout(timer);
                    timer = false;
                }else{
                        $(this).children('.popup-preview').fadeOut("fast");
                }

                //return false;
            }
        );
</code>```

Here's the fiddle

Body:
I am developing a webpage in which a user can show the larger image or preview of every thumbnails by hovering it.

I am using this Jquery code to show and center the larger image on the screen responsively.

var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

      $(self).children('.popup-preview').css("position", "fixed");
      $(self).children('.popup-preview').css("top", ($(window).height() / 2) - ($(self).children('.popup-preview').outerHeight() / 2));
      $(self).children('.popup-preview').css("left", ($(window).width() / 2) - ($(self).children('.popup-preview').outerWidth() / 2));

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);

How can I align the larger image vertically the same with the parent class?

Here is my working sample code.

Update: Example is when the thumbnail is on the top or bottom of the screen and was hovered. The larger image should display vertically center of the screen.

Body:
Just try changing the postion to absolute

        var timer;
        $(".theme-preview").hover(function() {
                var self = $(this);

                timer = setTimeout(function(){
                    timer = false;

                    $(self).children('.popup-preview').fadeIn("slow");

                    $(self).children('.popup-preview').css("position","absolute");
                    $(self).children('.popup-preview').css("top", '0');
                    $(self).children('.popup-preview').css("left", 'auto');

                }, 800);

                //return false;
            },
            function () {
                if(timer){
                    clearTimeout(timer);
                    timer = false;
                }else{
                        $(this).children('.popup-preview').fadeOut("fast");
                }

                //return false;
            }
        );

Here's the fiddle


问:
PHP exception not being caught, laravel, lumen
When attempting to catch/handle an exception thrown from PDFParser, I cannot catch it. I use a simple try catch statement, outlined below.

```<code>try{
  $pdf  = $parser->parseFile($filepath);
  $text = $pdf->getText();
} catch( \Exception $e){
  $text = $paper->abstract;
}
</code>```

The exception is thrown as follows.

```<code>if (empty($data)) {
        throw new \Exception('Object list not found. Possible secured file.');
}
</code>```

The output is here.

lumen.ERROR: Exception: Object list not found. Possible secured file.
  in

/Users/pietrosette/Documents/CS_310/AcademicWordCloud-Backend/vendor/smalot/pdfparser/src/Smalot/PdfParser/Parser.php:98
  Stack trace:

#0 /Users/pietrosette/Documents/CS_310/AcademicWordCloud-Backend/vendor/smalot/pdfparser/src/Smalot/PdfParser/Parser.php(74):
  Smalot\PdfParser\Parser->parseContent('%PDF-1.5\r%\xE2\xE3\xCF\xD3\r...')

#1 /Users/pietrosette/Documents/CS_310/AcademicWordCloud-Backend/app/Http/Controllers/ACMServer.php(198):
  Smalot\PdfParser\Parser->parseFile('/Users/pietrose...')

答:
You have a typo in your catch:

```<code>try{
  $pdf  = $parser->parseFile($filepath);
  $text = $pdf->getText();
} catch( \Execption $e){
  $text = $paper->abstract;
}
</code>```

"Exception" is spelled incorrectly.

Body:
When attempting to catch/handle an exception thrown from PDFParser, I cannot catch it. I use a simple try catch statement, outlined below.

try{
  $pdf  = $parser->parseFile($filepath);
  $text = $pdf->getText();
} catch( \Exception $e){
  $text = $paper->abstract;
}

The exception is thrown as follows.

if (empty($data)) {
        throw new \Exception('Object list not found. Possible secured file.');
}

The output is here.

lumen.ERROR: Exception: Object list not found. Possible secured file.
  in

/Users/pietrosette/Documents/CS_310/AcademicWordCloud-Backend/vendor/smalot/pdfparser/src/Smalot/PdfParser/Parser.php:98
  Stack trace:

#0 /Users/pietrosette/Documents/CS_310/AcademicWordCloud-Backend/vendor/smalot/pdfparser/src/Smalot/PdfParser/Parser.php(74):
  Smalot\PdfParser\Parser->parseContent('%PDF-1.5\r%\xE2\xE3\xCF\xD3\r...')

#1 /Users/pietrosette/Documents/CS_310/AcademicWordCloud-Backend/app/Http/Controllers/ACMServer.php(198):
  Smalot\PdfParser\Parser->parseFile('/Users/pietrose...')

Body:
You have a typo in your catch:

try{
  $pdf  = $parser->parseFile($filepath);
  $text = $pdf->getText();
} catch( \Execption $e){
  $text = $paper->abstract;
}

"Exception" is spelled incorrectly.


答:
(TextView) only casts the object found by findViewbyId.
R.layout.test should contain a TextView with id textView.

Title: Java/Android MainActivity Syntax Confusing - Need some Clarification


问:
What is the recommended way to filter Objects with Unique property in the array in JS?
How to filter objects in array based on unique property
here i have an array where KEY is the key value in the objects.
How to filter the objects where key value is unique. Key value is repeated in the objects but should only the first one should be filtered out.

```<code>var array = [];
array = [
  {
    "KEY": "00001",
    "ID": "1234",
    "ID_DESC": "1234",
    "NOT_UNIQUE_VALUE": "119.0",
    "NOT_UNIQUE_TYPE": "this is not unique"
  },
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"11019.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  }]
</code>```

Result:

```<code>uniquearray = [
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"119.0",
    "NO T_UNIQUE_TYPE":"this is not unique"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  }]
</code>```

答:
You can iterate over the members and look at the KEY property. If it's not been seen before, add it to a list of seen keys and return true. If it has been seen before, return false. E.g.

var array = [{
  "KEY": "00001",
  "ID": "1234",
  "ID_DESC": "1234",
  "NOT_UNIQUE_VALUE": "119.0",
  "NOT_UNIQUE_TYPE": "this is not unique"
}, {
  "KEY": "00001",
  "ID": "1234",
  "ID_DESC": "1234",
  "NOT_UNIQUE_VALUE": "11019.0",
  "NOT_UNIQUE_TYPE": "not unique type"
}, {
  "KEY": "00002",
  "ID": "2468",
  "ID_DESC": "2468",
  "NOT_UNIQUE_VALUE": "195.0",
  "NOT_UNIQUE_TYPE": "not unique type",
}, {
  "KEY": "00002",
  "ID": "2468",
  "ID_DESC": "2468",
  "NOT_UNIQUE_VALUE": "195.0",
  "NOT_UNIQUE_TYPE": "not unique type",
}]

var seenKeys = Object.create(null);
var result = array.filter(function(obj) {
  return seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true;
});

console.log(result)```
</div>
</div>
</p>

<p>As an arrow function:</p>

```var seenKeys = Object.create(null);
var result = array.filter(obj => seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true);
```

Body:
How to filter objects in array based on unique property
here i have an array where KEY is the key value in the objects.
How to filter the objects where key value is unique. Key value is repeated in the objects but should only the first one should be filtered out.

var array = [];
array = [
  {
    "KEY": "00001",
    "ID": "1234",
    "ID_DESC": "1234",
    "NOT_UNIQUE_VALUE": "119.0",
    "NOT_UNIQUE_TYPE": "this is not unique"
  },
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"11019.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  }]

Result:

uniquearray = [
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"119.0",
    "NO T_UNIQUE_TYPE":"this is not unique"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  }]

Body:
You can iterate over the members and look at the KEY property. If it's not been seen before, add it to a list of seen keys and return true. If it has been seen before, return false. E.g.

var array = [{
  "KEY": "00001",
  "ID": "1234",
  "ID_DESC": "1234",
  "NOT_UNIQUE_VALUE": "119.0",
  "NOT_UNIQUE_TYPE": "this is not unique"
}, {
  "KEY": "00001",
  "ID": "1234",
  "ID_DESC": "1234",
  "NOT_UNIQUE_VALUE": "11019.0",
  "NOT_UNIQUE_TYPE": "not unique type"
}, {
  "KEY": "00002",
  "ID": "2468",
  "ID_DESC": "2468",
  "NOT_UNIQUE_VALUE": "195.0",
  "NOT_UNIQUE_TYPE": "not unique type",
}, {
  "KEY": "00002",
  "ID": "2468",
  "ID_DESC": "2468",
  "NOT_UNIQUE_VALUE": "195.0",
  "NOT_UNIQUE_TYPE": "not unique type",
}]

var seenKeys = Object.create(null);
var result = array.filter(function(obj) {
  return seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true;
});

console.log(result)

As an arrow function:

var seenKeys = Object.create(null);
var result = array.filter(obj => seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true);


问:
A Typescript variable that is available both statically and dynamically
I have a readonly value that I want to access either statically or dynamically. I could write it this way:

```<code>class Example {
   static readonly FOO = 1;
   readonly FOO = 1;
}
</code>```

The result would be:

```<code>const example = Example();
example.FOO === Example.FOO;
</code>```

This approach seems very clumsy. Is there a way I can write this in one line?

答:
In Angular, templates cannot access objects that are not exposed by a component. see https://github.com/angular/angular/issues/2885.

Something like this is required:

```<code>class Controller {
    public example = Example;
    ...
}
</code>```

Body:
I have a readonly value that I want to access either statically or dynamically. I could write it this way:

class Example {
   static readonly FOO = 1;
   readonly FOO = 1;
}

The result would be:

const example = Example();
example.FOO === Example.FOO;

This approach seems very clumsy. Is there a way I can write this in one line?

Body:
In Angular, templates cannot access objects that are not exposed by a component. see https://github.com/angular/angular/issues/2885.

Something like this is required:

class Controller {
    public example = Example;
    ...
}


问:
How to apply WHERE clause to multiple SELECT statements in SQL Server
I am creating an query that selects data from multiple tables. I have completed all the query but now I have to apply the WHERE clause to the whole query.
I have 9 select statements, and these are working fine. Data is being selected from different tables. Now I want to declare date session and I want all data to be filtered according to the date provided. I am using the below query:

```<code>SELECT
    (SELECT COUNT(DISTINCT OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsDistinct',
    (SELECT COUNT(OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsInDistinct',
    (SELECT COUNT(Orders.OrderID)
     FROM Orders) AS 'TotalOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @CompleteOStatusID) AS 'CompleteOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @PendingOStatusID) AS 'PendingOrders',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID != @WalkingCustID) AS 'namedcustomers',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID = @WalkingCustID) AS 'WalkingCustomers',
   (SELECT SUM(OrderItems.PurchasePrice)
    FROM OrderItems) AS 'TotalPurchasePrice',
   (SELECT SUM(OrderItems.SalePrice)
    FROM OrderItems) AS 'TotalSalePrice'
</code>```

I am selecting data from 2 tables named 'Orders' and 'OrderItems', I have column TransactionDate in 'Orders' table and column OrderDate in OrderItems table on that I want to use where filter. Can anybody please suggest how to apply filter to whole query?

答:
You could try this</p>

```<code>;with tempOrderItems AS
   (
      SELECT
         COUNT(DISTINCT OrderItems.ProductID) AS 'TotalSoldItemsDistinct',
         COUNT(OrderItems.ProductID) AS 'TotalSoldItemsInDistinct',
         SUM(OrderItems.PurchasePrice) AS 'TotalPurchasePrice',
         SUM(OrderItems.SalePrice)  AS 'TotalSalePrice'
      FROM OrderItems ori
      WHERE OrderDate  BETWEEN xxx AND yyy
   )
, tempOrders AS
   (
      SELECT
         COUNT(o.OrderID) AS 'TotalOrders',
         SUM(CASE WHEN o.OrderStatusID = @CompleteOStatusID THEN 1 ELSE 0 END) AS 'CompleteOrders',
         SUM(CASE WHEN o.OrderStatusID = @PendingOStatusID THEN 1 ELSE 0 END) AS 'PendingOrders',
         SUM(CASE WHEN o.ClientID != @WalkingCustID THEN 1 ELSE 0 END) AS 'namedcustomers',
         SUM(CASE WHEN o.ClientID = @WalkingCustID THEN 1 ELSE 0 END) AS 'WalkingCustomers'
      FROM Orders o
      WHERE TransactionDate BETWEEN xxx AND yyy

   )
SELECT * FROM tempOrderItems
CROSS JOIN tempOrders
</code>```

Body:
I am creating an query that selects data from multiple tables. I have completed all the query but now I have to apply the WHERE clause to the whole query.
I have 9 select statements, and these are working fine. Data is being selected from different tables. Now I want to declare date session and I want all data to be filtered according to the date provided. I am using the below query:

SELECT
    (SELECT COUNT(DISTINCT OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsDistinct',
    (SELECT COUNT(OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsInDistinct',
    (SELECT COUNT(Orders.OrderID)
     FROM Orders) AS 'TotalOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @CompleteOStatusID) AS 'CompleteOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @PendingOStatusID) AS 'PendingOrders',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID != @WalkingCustID) AS 'namedcustomers',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID = @WalkingCustID) AS 'WalkingCustomers',
   (SELECT SUM(OrderItems.PurchasePrice)
    FROM OrderItems) AS 'TotalPurchasePrice',
   (SELECT SUM(OrderItems.SalePrice)
    FROM OrderItems) AS 'TotalSalePrice'

I am selecting data from 2 tables named 'Orders' and 'OrderItems', I have column TransactionDate in 'Orders' table and column OrderDate in OrderItems table on that I want to use where filter. Can anybody please suggest how to apply filter to whole query?

Body:
You could try this

;with tempOrderItems AS
   (
      SELECT
         COUNT(DISTINCT OrderItems.ProductID) AS 'TotalSoldItemsDistinct',
         COUNT(OrderItems.ProductID) AS 'TotalSoldItemsInDistinct',
         SUM(OrderItems.PurchasePrice) AS 'TotalPurchasePrice',
         SUM(OrderItems.SalePrice)  AS 'TotalSalePrice'
      FROM OrderItems ori
      WHERE OrderDate  BETWEEN xxx AND yyy
   )
, tempOrders AS
   (
      SELECT
         COUNT(o.OrderID) AS 'TotalOrders',
         SUM(CASE WHEN o.OrderStatusID = @CompleteOStatusID THEN 1 ELSE 0 END) AS 'CompleteOrders',
         SUM(CASE WHEN o.OrderStatusID = @PendingOStatusID THEN 1 ELSE 0 END) AS 'PendingOrders',
         SUM(CASE WHEN o.ClientID != @WalkingCustID THEN 1 ELSE 0 END) AS 'namedcustomers',
         SUM(CASE WHEN o.ClientID = @WalkingCustID THEN 1 ELSE 0 END) AS 'WalkingCustomers'
      FROM Orders o
      WHERE TransactionDate BETWEEN xxx AND yyy

   )
SELECT * FROM tempOrderItems
CROSS JOIN tempOrders


问:
How can I control the speed that bootstrap carousel slides in items?
I see you can set the interval but I want to control how fast the items slide?</p>

```<code>   // Sets interval...what is transition slide speed?
    $('#mainCarousel').carousel({
    interval: 3000
});
</code>```

答:
All  carousel </p>

```<code>  <script type="text/javascript">
              $(document).ready(function () {
            $('.carousel').carousel({
                interval: 15000
            })
        });

    </script>
</code>```

Body:
I see you can set the interval but I want to control how fast the items slide?

   // Sets interval...what is transition slide speed?
    $('#mainCarousel').carousel({
    interval: 3000
});

Body:
All  carousel

  <script type="text/javascript">
              $(document).ready(function () {
            $('.carousel').carousel({
                interval: 15000
            })
        });

    </script>


答:
Take a look at http://validator.w3.org/docs/errors.html

73: end tag for X which is not finished

Most likely, you nested tags and closed them in the wrong order. For example
.

 is not acceptable, as  must be closed before
. Acceptable nesting is:

```<code><p><em>...</em></p>
</code>```

Another possibility is that you used an element which requires a child element that you did not include. Hence the parent element is "not finished", not complete. For instance, in HTML the  element must contain a  child element, lists require appropriate list items (
 and
 require
;
 requires
 and
), and so on.

You need at least one
 inside your table.

Title: Why does this html table definition not validate?

Body:
Take a look at http://validator.w3.org/docs/errors.html

73: end tag for X which is not finished

Most likely, you nested tags and closed them in the wrong order. For example <p><em>.
</p> is not acceptable, as <em> must be closed before <p>. Acceptable nesting is:

<p><em>...</em></p>

Another possibility is that you used an element which requires a child element that you did not include. Hence the parent element is "not finished", not complete. For instance, in HTML the  element must contain a  child element, lists require appropriate list items (<ul> and <ol> require <li>; <dl> requires <dt> and <dd>), and so on.

You need at least one <tr> inside your table.


问:
UTF8 character decoding in Objective C
I am trying to parse a feed from a json webservice on my iPhone however the utf8 conversion is not working the way it should or am I doing something wrong
Here is apart of the feed

est un r\u00c3\u00aave en noir

Here is the code I have written to convert the above:

```<code>NSString* str1 = @"est un r \u00c3\u00aa ve en noir";

NSString* str = [NSString stringWithUTF8String:[str1 cStringUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"Converted UTF   %@",str);
</code>```

This is the output that I am getting:

Converted UTF   est un r Ãª ve en noir

The expected output should be
 Converted UTF   est un rêve en noir

When I checked the UTF table and used a utf converter online the output is correctly got with the same code and using the string @"est un r\u00EAve en noir" but I think that the UTF16 Representation if I am not mistaken. Now am really in a fix how to parse this feed.

答:
While sending to server

```<code>NSString* str1 = @"est un r \u00c3\u00aa ve en noir";
    NSData *str1Data = [str1 dataUsingEncoding:NSNonLossyASCIIStringEncoding];
    NSString  *str2 = [[NSString alloc] initWithData:str1Data encoding:NSUTF8StringEncoding];
</code>```

After receiving you can decode like this

```<code>NSData *recivedStrData = [recivedStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *strResult = [[NSString alloc] initWithData:recivedStrData encoding:NSNonLossyASCIIStringEncoding];
</code>```

This works for me!

Title: UTF8 character decoding in Objective C

Body:
I am trying to parse a feed from a json webservice on my iPhone however the utf8 conversion is not working the way it should or am I doing something wrong
Here is apart of the feed

est un r\u00c3\u00aave en noir

Here is the code I have written to convert the above:

NSString* str1 = @"est un r \u00c3\u00aa ve en noir";

NSString* str = [NSString stringWithUTF8String:[str1 cStringUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"Converted UTF   %@",str);

This is the output that I am getting:

Converted UTF   est un r Ãª ve en noir

The expected output should be
 Converted UTF   est un rêve en noir

When I checked the UTF table and used a utf converter online the output is correctly got with the same code and using the string @"est un r\u00EAve en noir" but I think that the UTF16 Representation if I am not mistaken. Now am really in a fix how to parse this feed.

Body:
While sending to server

NSString* str1 = @"est un r \u00c3\u00aa ve en noir";
    NSData *str1Data = [str1 dataUsingEncoding:NSNonLossyASCIIStringEncoding];
    NSString  *str2 = [[NSString alloc] initWithData:str1Data encoding:NSUTF8StringEncoding];

After receiving you can decode like this

NSData *recivedStrData = [recivedStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *strResult = [[NSString alloc] initWithData:recivedStrData encoding:NSNonLossyASCIIStringEncoding];

This works for me!


问:
variable null, even without being called
I'm attempting to use JavaScript to add rows to a table. I created an anonymous function iterate that iterates id names, and that works fine. The problem is somewhere in my class.

```<code>class CreateTable{
      constructor(text) {
    this.text = text
  }

  makeTableRow(){
    let self = this;
    let row = document.createElement('tr');
    for (let i = 0; i < 1; i++) {
      let el = document.createElement('td');
      el.setAttribute('id', iterate(i));
      row.appendChild(el);
    }
    let en = document.getElementById('id1');
    console.log(en);
    en.innerHTML = self.text;
    return row;
  }
}
</code>```

I adapted this class from something that already works, with some tweaks. The en variable is returning a typeError:en is null, and I can't figure it out. What I want to do is create two empty td elements with callable ids, and then add text to the first element immediately. What is the actual problem that is going on here?

答:
Is null because doesn't is identifying the "id", that meaning that you are writing your script before the id="id1".

You need to write your script at the end, just before of "body"

```<code>  .......
  <div id="id1">
  </div>
  .....
  <script>
  ....
  </script>
</body>
</code>```

Body:
I'm attempting to use JavaScript to add rows to a table. I created an anonymous function iterate that iterates id names, and that works fine. The problem is somewhere in my class.

class CreateTable{
      constructor(text) {
    this.text = text
  }

  makeTableRow(){
    let self = this;
    let row = document.createElement('tr');
    for (let i = 0; i < 1; i++) {
      let el = document.createElement('td');
      el.setAttribute('id', iterate(i));
      row.appendChild(el);
    }
    let en = document.getElementById('id1');
    console.log(en);
    en.innerHTML = self.text;
    return row;
  }
}

I adapted this class from something that already works, with some tweaks. The en variable is returning a typeError:en is null, and I can't figure it out. What I want to do is create two empty td elements with callable ids, and then add text to the first element immediately. What is the actual problem that is going on here?

Body:
Is null because doesn't is identifying the "id", that meaning that you are writing your script before the id="id1".

You need to write your script at the end, just before of "body"

  .......
  <div id="id1">
  </div>
  .....
  <script>
  ....
  </script>
</body>


问:
wso2esb LDAP connector retrive thumbnailphoto
How can I retrieve thumbnailphoto from Active Directory using LDAP Connector in WSO2ESB?

Thanks in advance

答:
I think we can use search[1] operation to retrieve the thumbnailphoto and we have to specify the attributes[2] (jpegPhoto or thumbnailPhoto).

[1] https://docs.wso2.com/display/ESBCONNECTORS/Working+with+CRUD+operations+in+LDAP#WorkingwithCRUDoperationsinLDAP-searchEntry

[2] https://kanboard.net/documentation/ldap-profile-picture


问:
Simple validation for  element.
I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.

```<code>        function saveToDatabase(editableObj,column,id) {
        $(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
        $("#tabs-1").load(location.href + " #tabs-1");
            $.ajax({
                url: "saveedit.php",
                type: "POST",
                data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
                success: function(data){
                    $(editableObj).css("background","#FDFDFD");
                }
           });
    }
</code>```

After the function above, saveedit.php will deal with updating the database and it's functional.

Then, this is my table in html and these table elements are editable.

```<code>        <?php
            $result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
            foreach($result as $k=>$v){
        ?>
        <tr>
            <td><?php echo $k+1; ?></td>
            <td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?></td>
        </tr>
        <?php
            }
        ?>
</code>```

This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this  element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.

答:
Check the passing parameter and only process ajax when your condition is satisfied.

```<code>function saveToDatabase(editableObj,column,id) {
//If(editableObj.length > 6) // Case of string Check your other condition.
if(editableObj.toString().length > 6) // in case it is not string.
{
alert(Condition fail);
}
else
{
 // Your ajax call -------
}

}
</code>```

Or :

Check your passing data before calling saveToDatabase function.

Title: Simple validation for <td contenteditable="true"> element.

Body:
I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.

        function saveToDatabase(editableObj,column,id) {
        $(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
        $("#tabs-1").load(location.href + " #tabs-1");
            $.ajax({
                url: "saveedit.php",
                type: "POST",
                data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
                success: function(data){
                    $(editableObj).css("background","#FDFDFD");
                }
           });
    }

After the function above, saveedit.php will deal with updating the database and it's functional.

Then, this is my table in html and these table elements are editable.

        <?php
            $result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
            foreach($result as $k=>$v){
        ?>

            <?php echo $k+1; ?>
            <td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?>

        <?php
            }
        ?>

This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this  element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.

Body:
Check the passing parameter and only process ajax when your condition is satisfied.

function saveToDatabase(editableObj,column,id) {
//If(editableObj.length > 6) // Case of string Check your other condition.
if(editableObj.toString().length > 6) // in case it is not string.
{
alert(Condition fail);
}
else
{
 // Your ajax call -------
}

}

Or :

Check your passing data before calling saveToDatabase function.


问:
Flash Message Laravel 5.2 using toast materialize
can you help me solve this problem ? so in this case i want to show flash message in the next page after button click & action (save, update, delete) success perform...

i've read this https://www.tutorialspoint.com/materialize/materialize_dialogs.htm and also http://materializecss.com/dialogs.html but idk how to use it in my controller

```<code>public function hapuskeluhan($id){

    $keluh = keluhan::findOrFail($id);
    $keluh->delete();
    return redirect('lihatkeluhan');
}
</code>```

For Example is function delete, how could my toast appear before it redirect ? or maybe after ? please kindly help me brother

答:
I think you need to pass the message along with the redirection to be displayed on the view.

```<code>public function hapuskeluhan($id)
{
    $keluh = keluhan::findOrFail($id);
    $keluh->delete();
    return redirect('lihatkeluhan')->with(['message', 'Record Deleted!']);
}
</code>```

and in your view you could access the session variable message as

```<code>Materialize.toast({{ session('message') }}, duration, 'rounded');
</code>```

and initiate a click so that the toast is displayed

```<code>$(document).ready(function () {

    $("your element containing materialize handle").click();

});
</code>```

Body:
can you help me solve this problem ? so in this case i want to show flash message in the next page after button click & action (save, update, delete) success perform...

i've read this https://www.tutorialspoint.com/materialize/materialize_dialogs.htm and also http://materializecss.com/dialogs.html but idk how to use it in my controller

public function hapuskeluhan($id){

    $keluh = keluhan::findOrFail($id);
    $keluh->delete();
    return redirect('lihatkeluhan');
}

For Example is function delete, how could my toast appear before it redirect ? or maybe after ? please kindly help me brother

Body:
I think you need to pass the message along with the redirection to be displayed on the view.

public function hapuskeluhan($id)
{
    $keluh = keluhan::findOrFail($id);
    $keluh->delete();
    return redirect('lihatkeluhan')->with(['message', 'Record Deleted!']);
}

and in your view you could access the session variable message as

Materialize.toast({{ session('message') }}, duration, 'rounded');

and initiate a click so that the toast is displayed

$(document).ready(function () {

    $("your element containing materialize handle").click();

});


问:
How api calls are done with headers in swift
I want to securely provide my data from the API using JWT token.So Currently I have implemented security in the backend and each ajax call eith the header

```<code>url:"https://dataurl,
        contentType : "application/json; charset=utf-8",
        headers : TokenHeader(),
</code>```

But now I want to send the same data to be consumed by an IOS App which is developed in swift.I am not a IOS mobile developer and when I look into how they make the rest calls I found that something like this can be done:

```<code>let todosEndpoint: String = "https://dataurl"
guard let todosURL = URL(string: todosEndpoint) else {
  print("Error: cannot create URL")
  return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "GET"
let newTodo: [String: Any] = ["title": "My First todo", "completed": false, "userId": 1]
let jsonTodo: Data
do {
  jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
  todosUrlRequest.httpBody = jsonTodo
} catch {
  print("Error: cannot create JSON from todo")
  return
}

let session = URLSession.shared

let task = session.dataTask(with: todosUrlRequest) {
  (data, response, error) in
  guard error == nil else {
    print("error calling POST on /todos/1")
    print(error)
    return
  }
  guard let responseData = data else {
    print("Error: did not receive data")
    return
  }
</code>```

So now my question is like ajax call in my web app how to consume rest service from the mobile app side.Any help is appreciated?

答:
I suggest you to use headers like this</p>

```<code>let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL)
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.cachePolicy = .reloadIgnoringLocalCacheData
</code>```

Body:
I want to securely provide my data from the API using JWT token.So Currently I have implemented security in the backend and each ajax call eith the header

url:"https://dataurl,
        contentType : "application/json; charset=utf-8",
        headers : TokenHeader(),

But now I want to send the same data to be consumed by an IOS App which is developed in swift.I am not a IOS mobile developer and when I look into how they make the rest calls I found that something like this can be done:

let todosEndpoint: String = "https://dataurl"
guard let todosURL = URL(string: todosEndpoint) else {
  print("Error: cannot create URL")
  return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "GET"
let newTodo: [String: Any] = ["title": "My First todo", "completed": false, "userId": 1]
let jsonTodo: Data
do {
  jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
  todosUrlRequest.httpBody = jsonTodo
} catch {
  print("Error: cannot create JSON from todo")
  return
}

let session = URLSession.shared

let task = session.dataTask(with: todosUrlRequest) {
  (data, response, error) in
  guard error == nil else {
    print("error calling POST on /todos/1")
    print(error)
    return
  }
  guard let responseData = data else {
    print("Error: did not receive data")
    return
  }

So now my question is like ajax call in my web app how to consume rest service from the mobile app side.Any help is appreciated?

Body:
I suggest you to use headers like this

let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL)
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.cachePolicy = .reloadIgnoringLocalCacheData


问:
How to configure IBM MobileFirst Platform 8.0 analytics console REST API maximum search result?
Why is the Elasticsearch REST API for search and view data via port 9500* returning only 10 records? Is there a maximum number that controls this?

http://localhost:9500/*/_search?q=module:"login"

*https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/analyt
ics/elasticsearch/

答:
Since analytics is based on the elasticsearch, to the query you need to add the additional parameter &size=100000 to the url.

Example:
http://localhost:9500/_search?size=100000


问:
Sorted/searchable StackedInline options
I have three classes:

Person

Publication

AuthorOrder

Publication has a m2m field to Person through AuthorOrder. This is done to enable making it possible to set the order of authors, which matters for academic publications.

However, the list of Persons is getting long, and it would therefore be nice if it was searchable or at least sorted. However, if I use the obvious method of setting a Meta class to Person, this causes the Persons to be sorted everywhere, including where I don't want them to be.

Is there a way to make it searchable (best) or at least sorted without ruining the order elsewhere (ok)?

Looks like this:

答: There you go. This works well for us on several projects. https://github.com/and3rson/django-searchable-select</p>

Title: Sorted/searchable StackedInline options


问:
Python csv.reader: How do I return to the top of the file?
When I'm moving through a file with a csv.reader, how do I return to the top of the file.   If I were doing it with a normal file I could just do something like "file.seek(0)".  Is there anything like that for the csv module?

Thanks ahead of time ;)

答:
You can still use file.seek(0). For instance, look at the following:

```<code>import csv
file_handle = open("somefile.csv", "r")
reader = csv.reader(file_handle)
# Do stuff with reader
file_handle.seek(0)
# Do more stuff with reader as it is back at the beginning now
</code>```

This should work since csv.reader is working with the same.

OwnerDisplayName: Casey

Body:
You can still use file.seek(0). For instance, look at the following:

import csv
file_handle = open("somefile.csv", "r")
reader = csv.reader(file_handle)
# Do stuff with reader
file_handle.seek(0)
# Do more stuff with reader as it is back at the beginning now

This should work since csv.reader is working with the same.

OwnerDisplayName: Evan Fosmark


问:
angularjs push function not working
Hi I am trying to make a single page angular js application but while adding to the list "schedulelist" only the latest record are getting pushed into the list and all the previous records are getting replaced by the latest record

This is my Html:

```<code> <table class="table1" cellspacing=2 cellpadding=5 border=0>
  <div ng-repeat="scheduleDTO in schedules">
<tr>
<td>
       <SELECT id="days" name="days" class="form-right" style="width:90%" ng-model="scheduleDTO.day_of_the_week" required>

                    <OPTION selected value="Monday">Monday</OPTION>
                    <OPTION value="Tuesday">Tuesday</OPTION>
                    <OPTION value="Wednesday">Wednesday</OPTION>
                    <OPTION value="Thursday">Thursday</OPTION>
                    <OPTION value="Friday">Friday</OPTION>
                    <OPTION value="Saturday">Saturday</OPTION>
                    <OPTION value="Sunday">Sunday</OPTION>
        </SELECT>

</td>
<td>
       <SELECT id="start_time" name="Start" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION selected value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

</td>
<td>
<SELECT id="start" name="am" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time_meridiem"required>
                    <OPTION selected value="AM">AM</OPTION>
                    <OPTION value="PM">PM</OPTION>
</SELECT>

<td><SELECT  id="end_time"class="form-right" name="end" style="width:90%" ng-model="scheduleDTO.end_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION selected value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

        </td>
<td>

<SELECT id="end" name="pm" class="form-right" style="width:90%" ng-model="scheduleDTO.end_time_meridiem" required>
                    <OPTION value="AM">AM</OPTION>
                    <OPTION selected value="PM">PM</OPTION>
</SELECT>

</td>
<td><input type="button" class="addSch" ng-click="add(scheduleDTO)" value="Add Schedule" style="width:90%"> <!-- add_schedule(); -->

</td>
</tr>
</div>
</table>
<table align='center' class="table1" cellspacing=2 cellpadding=5 id="table" border=0>

<tr ng-repeat="ScheduleDTO in schedulelist">

<td>{{scheduleDTO.day_of_the_week}}</td>
<td>{{scheduleDTO.start_time}}</td>
<td>{{scheduleDTO.start_time_meridiem}}</td><td>To</td>
<td>{{scheduleDTO.end_time}}</td>
<td>{{scheduleDTO.end_time_meridiem}}</td>
<td><input type='button' value='Delete' class='delete' ng-click="remove(scheduleDTO)"></td>

</table>
</code>```

This is rthe controller:

```<code>$scope.schedulelist = [

    ];

    $scope.add = function (schedule)
            {                   schedule.volunteer_id="";
                                schedule.sid="";
                   $scope.schedulelist.push({"ScheduleDTO":schedule});
                    alert(angular.toJson($scope.schedulelist));
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };
</code>```

答:
Use Angular#copy to avoid reference copy in the modal,

which is the same one getting used again and data is overwritten.

```<code>$scope.schedulelist.push({"ScheduleDTO":angular.copy(schedule)});
</code>```

Title: angularjs push function not working

Body:
Hi I am trying to make a single page angular js application but while adding to the list "schedulelist" only the latest record are getting pushed into the list and all the previous records are getting replaced by the latest record

This is my Html:

       <SELECT id="days" name="days" class="form-right" style="width:90%" ng-model="scheduleDTO.day_of_the_week" required>

                    <OPTION selected value="Monday">Monday</OPTION>
                    <OPTION value="Tuesday">Tuesday</OPTION>
                    <OPTION value="Wednesday">Wednesday</OPTION>
                    <OPTION value="Thursday">Thursday</OPTION>
                    <OPTION value="Friday">Friday</OPTION>
                    <OPTION value="Saturday">Saturday</OPTION>
                    <OPTION value="Sunday">Sunday</OPTION>
        </SELECT>

       <SELECT id="start_time" name="Start" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION selected value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

<SELECT id="start" name="am" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time_meridiem"required>
                    <OPTION selected value="AM">AM</OPTION>
                    <OPTION value="PM">PM</OPTION>
</SELECT>

<SELECT  id="end_time"class="form-right" name="end" style="width:90%" ng-model="scheduleDTO.end_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION selected value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

<SELECT id="end" name="pm" class="form-right" style="width:90%" ng-model="scheduleDTO.end_time_meridiem" required>
                    <OPTION value="AM">AM</OPTION>
                    <OPTION selected value="PM">PM</OPTION>
</SELECT>

<input type="button" class="addSch" ng-click="add(scheduleDTO)" value="Add Schedule" style="width:90%">

{{scheduleDTO.day_of_the_week}}
{{scheduleDTO.start_time}}
{{scheduleDTO.start_time_meridiem}}	To
{{scheduleDTO.end_time}}
{{scheduleDTO.end_time_meridiem}}
<input type='button' value='Delete' class='delete' ng-click="remove(scheduleDTO)">

This is rthe controller:

$scope.schedulelist = [

    ];

    $scope.add = function (schedule)
            {                   schedule.volunteer_id="";
                                schedule.sid="";
                   $scope.schedulelist.push({"ScheduleDTO":schedule});
                    alert(angular.toJson($scope.schedulelist));
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };

Body:
Use Angular#copy to avoid reference copy in the modal,

which is the same one getting used again and data is overwritten.

$scope.schedulelist.push({"ScheduleDTO":angular.copy(schedule)});


问:
Python Json. Getting only the last element in the json array
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

```<code>[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]
</code>```

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

```<code>rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
</code>```

when i return the value, i get

```<code>{
  "Ingreient ID": 19682
}
</code>```

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

答:
If you just wanted the ids, you could use a list comprehension, something like this:</p>

```<code>ids = [records['IngredientID'] for records in recipes['Recipes'][0]['Ingredients']]
</code>```

Body:
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }

when i return the value, i get

{
  "Ingreient ID": 19682
}

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

Body:
If you just wanted the ids, you could use a list comprehension, something like this:

ids = [records['IngredientID'] for records in recipes['Recipes'][0]['Ingredients']]


问:
Added wrong default value in new field and now can't migrate
I added a user foreign field in one of my models and made a migration. I was prompted to add a default value. The default value for user is suppose to be Int, representing the user_id. Instead of adding an Int, I added a string "username".

Now I'm stuck with:

```<code>return int(value)
ValueError: invalid literal for int() with base 10: 'testuser'
</code>```

I deleted all the objects associated with the model, and tried migrating, that didn't work, getting same error. (Model.objects.all().delete())

I reverted to a previous migration, that didn't solve the problem, when I migrated, it got the same ValueError. (./manage.py migrate app 0037_auto_20170330_0326)

Lastly, I deleted my new foreign field, but that didn't solve the issue either.

What other options do I have in such a scenario?

My model is very simple:

```<code>class Chat(models.Model):
    user = models.ForeignKey(User) #new field that was added
    message = models.CharField(max_length=50)
</code>```

答:
If you are already at migration 0036, try following steps:

Delete the migration 0037_auto_20170330_0326. It will be present at the following location:

```<code>appfolder -> migrations -> 0037_auto_20170330_0326.py
</code>```

Set null=True in user field in Chat model:

```<code>user = models.ForeignKey(User, null=True)
</code>```

Migrate again!

Body:
I added a user foreign field in one of my models and made a migration. I was prompted to add a default value. The default value for user is suppose to be Int, representing the user_id. Instead of adding an Int, I added a string "username".

Now I'm stuck with:

return int(value)
ValueError: invalid literal for int() with base 10: 'testuser'

I deleted all the objects associated with the model, and tried migrating, that didn't work, getting same error. (Model.objects.all().delete())

I reverted to a previous migration, that didn't solve the problem, when I migrated, it got the same ValueError. (./manage.py migrate app 0037_auto_20170330_0326)

Lastly, I deleted my new foreign field, but that didn't solve the issue either.

What other options do I have in such a scenario?

My model is very simple:

class Chat(models.Model):
    user = models.ForeignKey(User) #new field that was added
    message = models.CharField(max_length=50)

Body:
If you are already at migration 0036, try following steps:

Delete the migration 0037_auto_20170330_0326. It will be present at the following location:

appfolder -> migrations -> 0037_auto_20170330_0326.py

Set null=True in user field in Chat model:

user = models.ForeignKey(User, null=True)

Migrate again!


问:
Do statically linked libraries require linking with their dependencies?
I'm building an executable that depends on a static library A which in turn depends on a static library B. When I build my application, do I need to also link against B in my build script?

To be more specific, do I need to do -la -lb, or, just linking with A via -la is enough?

答:
A static library is completely included in the using program during compile time, so that it won't need any additional file to run the program.

If library A was already build with the static library B, A has B already and won't need it again.


问:
add tabindex attribute to a class mark dynamically
I am new to angularjs. I am using a textangular to show a html document. I want to highlight some words from that html and also want to focus that word.So, I am using tabindex and class = mark to highlight and focus. So, Here At first I am adding

```<code><span class="mark">ABC</span>
</code>```

so that It will get highlighted, after that I want to add a tabindex=1 attribute to this .So that It become like

```<code><span class="mark" tabindex="1">ABC</span>
</code>```

Here I want to add this tabindex dynamically. That means , I want to find that text and then add a tabindex to that text only.How can I achieve this ?At a time tabindex can be applied to only one word.

答:
.focus() or keyboard navigating / tabindexing 's is not reliable.

You need to use empty hyperlink tags, like so:

ABC

$("button").click(function() {
  $("a.mark:contains('ABC')").focus();
});```
<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>
ABC
ABC1
<button>Next</button></code>```

Body:
I am new to angularjs. I am using a textangular to show a html document. I want to highlight some words from that html and also want to focus that word.So, I am using tabindex and class = mark to highlight and focus. So, Here At first I am adding

ABC

so that It will get highlighted, after that I want to add a tabindex=1 attribute to this .So that It become like

ABC

Here I want to add this tabindex dynamically. That means , I want to find that text and then add a tabindex to that text only.How can I achieve this ?At a time tabindex can be applied to only one word.

Body:
.focus() or keyboard navigating / tabindexing <span>'s is not reliable.

You need to use empty hyperlink tags, like so:

<a href="#" onCLick="return false" class="mark">ABC</a>

$("button").click(function() {
  $("a.mark:contains('ABC')").focus();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onCLick="return false" class="mark">ABC</a>
<a href="#" onCLick="return false" class="mark1">ABC1</a>
<button>Next</button>


问:
Print in python 3.4.2
I have typed print ("Hello World!") into python 3.4.2 and instead of printing Hello World!  It prints Syntax error: invalid character in identifier. I am a complete beginner and am using a raspberry pi 3</p>

答:
You used the wrong quotes. You must use ASCII quotes, not extended quotes.</p>

```<code>>>> print ("Hello World")
Hello World
>>> print (“Hello World”)
  File "<stdin>", line 1
    print (“Hello World”)
                ^
SyntaxError: invalid character in identifier
</code>```

Title: Print in python 3.4.2

Body:
You used the wrong quotes. You must use ASCII quotes, not extended quotes.

>>> print ("Hello World")
Hello World
>>> print (“Hello World”)
  File "<stdin>", line 1
    print (“Hello World”)
                ^
SyntaxError: invalid character in identifier