问:
Date is not defined error in angularjs

I am trying to print a date and time in my page with values coming from an Sql Server. The format of the date that is returned is like so:

```<code>/Date(1510563600000)/
</code>```

angular

```<code>$filter('date')(date, format, timezone)

$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
    var obj = { "userId": userId, "projectId": projectId }
    $http.post('/Admin/GetTimelineByUserIdAndProjectId', obj)
    .then(function (response) {
        $scope.userTimeline = response.data;
    })
}
</code>```

html

```<code><ul class="timeline timeline-inverse" ng-repeat="u in userTimeline">
<li class="time-label">
    <span class="bg-red">
        {{u.StartDateTime | date:'medium'}}
    </span>
</li>
<li>
    <i class="fa fa-clock-o bg-gray"></i>
</li>
</code>```

I want the date format to be day/month/year hour:minutes.

When I run this program, I got the $filter is not defined so I place it in my controller like this:

```<code>var app = angular.module('adminApp', []);
app.controller('adminController', function ($scope, $http, $filter) {
</code>```

but it then gives me an error of angular.js:14642 ReferenceError: date is not defined

答:
here I have used multiple filters it could be helpful to you.

In your case, you have created a filter which is not linked to your app so that it causes error

var app = angular.module('adminApp', []);
//$filter('')(date, format, timezone)
app.filter('date_filter',function(){
   return function(val){
    var n= val.replace('/Date(','').replace(')/','')
    return n;
   }
})
app.controller('adminController', function ($scope, $http) {
$scope.StartDateTime="/Date(1510563600000)/";
$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
    var obj = { "userId": userId, "projectId": projectId }
    //$http.post('/Admin/GetTimelineByUserIdAndProjectId', obj)
    //.then(function (response) {
        //$scope.userTimeline = response.data;

    //})
}
});```
<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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="adminApp" ng-controller="adminController">
{{StartDateTime|date_filter |date:'medium'}}
<br/>
{{StartDateTime|date_filter |date:'dd/MM/yyyy'}}
<ul class="timeline timeline-inverse" ng-repeat="u in userTimeline">
<li class="time-label">
    <span class="bg-red">
        {{u.StartDateTime |date_filter| date:'medium'}}
    </span>
</li>
<li>
    <i class="fa fa-clock-o bg-gray"></i>
</li>
</div></code>```

Title: Date is not defined error in angularjs

Body:
I am trying to print a date and time in my page with values coming from an Sql Server. The format of the date that is returned is like so:

/Date(1510563600000)/

angular

$filter('date')(date, format, timezone)

$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
    var obj = { "userId": userId, "projectId": projectId }
    $http.post('/Admin/GetTimelineByUserIdAndProjectId', obj)
    .then(function (response) {
        $scope.userTimeline = response.data;
    })
}

html

        {{u.StartDateTime | date:'medium'}}

I want the date format to be day/month/year hour:minutes.

When I run this program, I got the $filter is not defined so I place it in my controller like this:

var app = angular.module('adminApp', []);
app.controller('adminController', function ($scope, $http, $filter) {

but it then gives me an error of angular.js:14642 ReferenceError: date is not defined

Body:
here I have used multiple filters it could be helpful to you.

In your case, you have created a filter which is not linked to your app so that it causes error

var app = angular.module('adminApp', []);
//$filter('')(date, format, timezone)
app.filter('date_filter',function(){
   return function(val){
    var n= val.replace('/Date(','').replace(')/','')
    return n;
   }
})
app.controller('adminController', function ($scope, $http) {
$scope.StartDateTime="/Date(1510563600000)/";
$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
    var obj = { "userId": userId, "projectId": projectId }
    //$http.post('/Admin/GetTimelineByUserIdAndProjectId', obj)
    //.then(function (response) {
        //$scope.userTimeline = response.data;

    //})
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="adminApp" ng-controller="adminController">
{{StartDateTime|date_filter |date:'medium'}}
<br/>
{{StartDateTime|date_filter |date:'dd/MM/yyyy'}}
<ul class="timeline timeline-inverse" ng-repeat="u in userTimeline">
<li class="time-label">
    <span class="bg-red">
        {{u.StartDateTime |date_filter| date:'medium'}}
    </span>
</li>
<li>
    <i class="fa fa-clock-o bg-gray"></i>
</li>
</div>


来源: stackexchange

问:
How to send asynchronous state fetch to component?
I am currently working on a little app for fun. I ran into an issue with using axios and returning the response to my App component as updated state.

I then try to allow another component to use that piece of state, but I am not able to actually access the data. I can console.log(props) from within the List component, but I am not sure how to output the actual data as I am only able to output the promise results. I want to be able to output props.currentUser and have it be the googleId (using google Oauth2.0)..I am sure the solution is simple but, here is my code:

App.js ->

```<code>import React from 'react';
import helpers from '../helpers';
import List from './List';

class App extends React.Component{

  state = {
    currentUser: null
  }

  componentDidMount() {
    this.setState(prevState => ({
      currentUser: helpers.fetchUser()
    }));
  }

  render() {
    return (
      <div>
        <List currentUser={this.state.currentUser}/>
      </div>
    );
  }
};

export default App;
</code>```

helpers.js ->

```<code>import axios from 'axios';

var helpers = {
  fetchUser: async () => {
      const user = await axios.get('/api/current_user');

      return user.data;
  }
};

export default helpers;
</code>```

List Component ->

```<code>import React from 'react';

const List = (props) => {

  const renderContent = () => {
      console.log(props);
      return <li>{props.currentUser}</li>
  }

  renderContent();

  return (
    <div>
      <h1>Grocery List</h1>
      <ul>

      </ul>
    </div>
  );
}

export default List;
</code>```

Output ->

```<code>{currentUser: null}
{currentUser: Promise}
    currentUser: Promise__proto__: Promise[[PromiseStatus]]: "resolved"
</code>```

答:
Because fetchUser is an async function, it returns a promise. Thus, in the App component, you have to call setState inside the .then of that promise, like so:

```<code>componentDidMount() {
    helpers.fetchUser()
      .then(data => {
          this.setState(prevState => ({
              currentUser: data
          }));
      });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently working on a little app for fun. I ran into an issue with using axios and returning the response to my App component as updated state.

I then try to allow another component to use that piece of state, but I am not able to actually access the data. I can console.log(props) from within the List component, but I am not sure how to output the actual data as I am only able to output the promise results. I want to be able to output props.currentUser and have it be the googleId (using google Oauth2.0)..I am sure the solution is simple but, here is my code:

App.js ->

import React from 'react';
import helpers from '../helpers';
import List from './List';

class App extends React.Component{

  state = {
    currentUser: null
  }

  componentDidMount() {
    this.setState(prevState => ({
      currentUser: helpers.fetchUser()
    }));
  }

  render() {
    return (

        <List currentUser={this.state.currentUser}/>

    );
  }
};

export default App;

helpers.js ->

import axios from 'axios';

var helpers = {
  fetchUser: async () => {
      const user = await axios.get('/api/current_user');

      return user.data;
  }
};

export default helpers;

List Component ->

import React from 'react';

const List = (props) => {

  const renderContent = () => {
      console.log(props);
      return
{props.currentUser}

  }

  renderContent();

  return (

Grocery List

  );
}

export default List;

Output ->

{currentUser: null}
{currentUser: Promise}
    currentUser: Promise__proto__: Promise[[PromiseStatus]]: "resolved"

Body:
Because fetchUser is an async function, it returns a promise. Thus, in the App component, you have to call setState inside the .then of that promise, like so:

componentDidMount() {
    helpers.fetchUser()
      .then(data => {
          this.setState(prevState => ({
              currentUser: data
          }));
      });
}


问:
Displaying data from SQLite database incrementally
I want to be able to display values from my SQL database five at a time and then on button click be able to display the next five until I have display all of the courses. Right now this is how I am trying to display them: </p>

```<code> <%= form_for(Stc.new, action:'stcs#create') do |form| %>

 <%= collection_check_boxes(:course_id, Course.all, :id, :title,{}) do
 |form| %>

 form.label { form.check_box }

 <% end %>
 <%= form.collection_select(:course_id, Course.all,:id, :title, {}, {
 :multiple => false}) %>

 <%= form.select(:semester, options_for_select([['Fall', 'Fall'],
 ['Spring', 'Spring'],['Summer', 'Summer']]), :id => 'sel1') %>

 <%= form.select(:year, options_for_select([['2012', '2012'], ['2013',
'2013'], ['2014', '2014'], ['2015', '2015'], ['2016', '2016'], ['2017',
'2017']]), :id => 'sel2') %>

<%= form.select(:user_id, options_for_select([[1,@user.id]])) %>
<div class="actions">

 <form id="my_sample_form">

</form>

  <input type="submit" value="Submit" form="my_sample_form">

   <% end %>

 </div>
</code>```

答:
I think you want to do pagination here you can use a gem for that,
one gem is 'will_paginate' gem.

read about that https://github.com/mislav/will_paginate

Body:
I want to be able to display values from my SQL database five at a time and then on button click be able to display the next five until I have display all of the courses. Right now this is how I am trying to display them:

 <%= form_for(Stc.new, action:'stcs#create') do |form| %>

 <%= collection_check_boxes(:course_id, Course.all, :id, :title,{}) do
 |form| %>

 form.label { form.check_box }

 <% end %>
 <%= form.collection_select(:course_id, Course.all,:id, :title, {}, {
 :multiple => false}) %>

 <%= form.select(:semester, options_for_select([['Fall', 'Fall'],
 ['Spring', 'Spring'],['Summer', 'Summer']]), :id => 'sel1') %>

 <%= form.select(:year, options_for_select([['2012', '2012'], ['2013',
'2013'], ['2014', '2014'], ['2015', '2015'], ['2016', '2016'], ['2017',
'2017']]), :id => 'sel2') %>

<%= form.select(:user_id, options_for_select([[1,@user.id]])) %>

 <form id="my_sample_form">

</form>

  <input type="submit" value="Submit" form="my_sample_form">

   <% end %>


问:
Correctly doing redirect_to :back in Ruby on Rails when referrer is not available
I'm having a problem with redirect_to :back. Yes, it's referrers.

I often get the exception

(ActionController::RedirectBackError) "No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env[\"HTTP_REFERER\"]."

I realize that this is a result of a referrer not being available. Is there a way that, for example, one can set a session variable on each access with the last page visited, and, when HTTP_REFERER is not available, utilize this session variable to redirect to?

答:
Here's my little redirect_to_back method:

```<code>  def redirect_to_back(default = root_url)
    if request.env["HTTP_REFERER"].present? and request.env["HTTP_REFERER"] != request.env["REQUEST_URI"]
      redirect_to :back
    else
      redirect_to default
    end
  end
</code>```

You can pass an optional url to go somewhere else if http_refferrer is blank.

Body:
Here's my little redirect_to_back method:

  def redirect_to_back(default = root_url)
    if request.env["HTTP_REFERER"].present? and request.env["HTTP_REFERER"] != request.env["REQUEST_URI"]
      redirect_to :back
    else
      redirect_to default
    end
  end

You can pass an optional url to go somewhere else if http_refferrer is blank.


问:
Instant App, What's the actual minimum sdk
As per the android developers site, minimum sdk for Instant app is 21, ie 5.0.
link

The site clearly  states : Android Instant Apps are available on the majority of devices running Android 5.0 (API level 21) and higher.

But when we create a new project as per the guideline given in this link
which states that we need to have minimum sdk of 23, to get instant app support.

And does not allow me to create a support for 5.0.

as shown in below image which I tried :

答:
For instance app minimum API 23: Android 6.0 (Marshmallow).

Please follow this link https://developer.android.com/topic/instant-apps/getting-started/first-instant-app.html


问:
When to use Hadoop, HBase, Hive and Pig?
What are the benefits of using either Hadoop or HBase or Hive ?

From my understanding, HBase avoids using map-reduce and has a column oriented storage on top of HDFS. Hive is a sql-like interface for Hadoop and HBase.

I would also like to know how Hive compares with Pig.

答:
1.We are using Hadoop for storing Large data (i.e.structure,Unstructure and Semistructure data ) in the form file format like txt,csv.

2.If We want columnar Updations in our data then we are using Hbase tool

3.In case of Hive , we are storing Big data which is in structured format
and in addition to that we are providing Analysis on that data.

4.Pig is tool which is using Pig latin language to analyze data which is in any format(structure,semistructure and unstructure).


问:
Pass a List of integers to a C# controller action
I am trying to pass in a list of integers to a C# controller action. I have the following code:

```<code>    HttpRequestMessage request;
    String myUrl = 'http://path/to/getData';
    List<int> data = new List<int>() { 4, 6, 1 };

    request = new HttpRequestMessage(HttpMethod.post, myUrl);
    request.Content = new StringContent(JsonConvert.SerializeObject(data, Formatting.Indented));

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    String responseString = response.Content.ReadAsStringAsync().Result;
    var data = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(responseString);
</code>```

The controller action:

```<code>    [HttpPost]
    [ActionName("getData")]
    public Response getData(List<int> myInts) {

        // ...

    }
</code>```

However the resulting responseString is:

```<code> {"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'.","ExceptionType":"System.InvalidOperationException}
</code>```

答:
It is easy if you utilize Microsoft.AspNet.WebApi.Client package in client application

Action method

```<code>// POST api/values
        public void Post(List<int> value)
        {
        }
</code>```

client application

```<code>class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                var result = client.PostAsJsonAsync("http://localhost:24932/api/values",
                    new List<int>() {123, 123, 123}).Result;

                Console.ReadLine();
            }
        }
    }
</code>```

Body:
I am trying to pass in a list of integers to a C# controller action. I have the following code:

    HttpRequestMessage request;
    String myUrl = 'http://path/to/getData';
    List<int> data = new List<int>() { 4, 6, 1 };

    request = new HttpRequestMessage(HttpMethod.post, myUrl);
    request.Content = new StringContent(JsonConvert.SerializeObject(data, Formatting.Indented));

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    String responseString = response.Content.ReadAsStringAsync().Result;
    var data = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(responseString);

The controller action:

    [HttpPost]
    [ActionName("getData")]
    public Response getData(List<int> myInts) {

        // ...

    }

However the resulting responseString is:

 {"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'.","ExceptionType":"System.InvalidOperationException}

Body:
It is easy if you utilize Microsoft.AspNet.WebApi.Client package in client application

Action method

// POST api/values
        public void Post(List<int> value)
        {
        }

client application

class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                var result = client.PostAsJsonAsync("http://localhost:24932/api/values",
                    new List<int>() {123, 123, 123}).Result;

                Console.ReadLine();
            }
        }
    }


问:
How do I use Python Tkinter with sending mail?
I am trying to use Tkinter to make a program to send mail but I can't get the window to pop up before it try to send the mail. How would i do this?

Code:

```<code>import smtplib
from Tkinter import *

root=Tk()

v=StringVar()
entry=Entry(root, textvariable=v)

sender = "email@email.com.au"
receiver = [v]
message = """From: <email@email.com.au>
To: email@email.com
Subject: I made a code to send this!
Hello i made a code to send this!"""

try:
    session = smtplib.SMTP('mail.optusnet.com.au',25)
    session.ehlo()
    session.starttls()
    session.ehlo()
    session.login(sender,'passwrd')
    session.sendmail(sender,receiver,message)
    session.quit()

except smtplib.SMTPException as e:
    print(e)
</code>```

答:
```<code>import smtplib

from smtplib import SMTPException

#this app sends email  via gmail
def gmail( ):
    usermail = user_email.get()
    receivermail=receiver_email.get()
    server=smtplib.SMTP('smtp.gmail.com:587')
    pass_word=password.get()
    subject=subj.get()
    #This allow you to include a subject by adding from, to and subject
    line
    main_message=body.get('1.0', 'end-1c')
    Body="""From: Name here <usermail>
    To: <receivermail>
    Subject:%s

    %s
    """ %(subject,main_message )

        try:
            server=smtplib.SMTP('smtp.gmail.com:587')
            server.ehlo()
            server.starttls()
            server.login(usermail, pass_word  )
            server.sendmail(usermail,receivermail, Body )

            text.insert(1.0, 'message sent')
         #error handling
         except  (smtplib.SMTPException,ConnectionRefusedError,OSError):
            text.insert(1.0, 'message not sent')
         finally:
            server.quit()

#Gui interface
from tkinter import*

root= Tk(className=" Gmail app " )
root.config(bg="brown", )

#user mail
user_email = Label(root, text="Enter your Gmail address:  ")
user_email.pack()
user_email.config(bg="black", fg="white")

user_email = Entry(root, bd =8)
user_email.pack(fill=X)

#receiver email
receiver_email = Label(root, text="Enter the recipient's email address:
   ")
receiver_email.pack( )
receiver_email.config(bg="black", fg="white")

receiver_email = Entry(root, bd =8)
receiver_email.pack(fill=X)

#subject line
subj= Label(root, text="Enter your subject here: ")
subj.pack( )
subj.config(bg="black", fg="white")

subj = Entry(root, bd =8)
subj.pack(fill=X)

#Body of the message
body = Text(root, font="Tahoma",  relief=SUNKEN , bd=8)
body.config(bg="pink", height=15)
body.pack(fill=BOTH, expand=True)

#password widget
password = Label(root, text="Enter your Gmail password:  ")
password.pack()
password.config(bg="black", fg="white")

password= Entry(root, show='*', bd =8)
password.pack(fill=X)

#submit button
submit_mail = Button(root, bd =8, text="Click here to submit the mail",
command=gmail)
submit_mail.pack(fill=X)

#feed back
text = Text(root, font="Tahoma",  relief=SUNKEN , bd=8)
text.config(bg="pink",  height=2)
text.pack(fill=BOTH, expand=True)

root.mainloop()
</code>```

the problem with my code above is that it can not send subject , only

body can be sent. I am also amateur with two months self learning. i will
recommend that you learn tkinter from this forum, yputube and a book
called 'an  introduction to tkinter by David Beazely'. hope this helps

Body:
I am trying to use Tkinter to make a program to send mail but I can't get the window to pop up before it try to send the mail. How would i do this?

Code:

import smtplib
from Tkinter import *

root=Tk()

v=StringVar()
entry=Entry(root, textvariable=v)

sender = "email@email.com.au"
receiver = [v]
message = """From: <email@email.com.au>
To: email@email.com
Subject: I made a code to send this!
Hello i made a code to send this!"""

try:
    session = smtplib.SMTP('mail.optusnet.com.au',25)
    session.ehlo()
    session.starttls()
    session.ehlo()
    session.login(sender,'passwrd')
    session.sendmail(sender,receiver,message)
    session.quit()

except smtplib.SMTPException as e:
    print(e)

Body:
import smtplib

from smtplib import SMTPException

#this app sends email  via gmail
def gmail( ):
    usermail = user_email.get()
    receivermail=receiver_email.get()
    server=smtplib.SMTP('smtp.gmail.com:587')
    pass_word=password.get()
    subject=subj.get()
    #This allow you to include a subject by adding from, to and subject
    line
    main_message=body.get('1.0', 'end-1c')
    Body="""From: Name here <usermail>
    To: <receivermail>
    Subject:%s

    %s
    """ %(subject,main_message )

        try:
            server=smtplib.SMTP('smtp.gmail.com:587')
            server.ehlo()
            server.starttls()
            server.login(usermail, pass_word  )
            server.sendmail(usermail,receivermail, Body )

            text.insert(1.0, 'message sent')
         #error handling
         except  (smtplib.SMTPException,ConnectionRefusedError,OSError):
            text.insert(1.0, 'message not sent')
         finally:
            server.quit()

#Gui interface
from tkinter import*

root= Tk(className=" Gmail app " )
root.config(bg="brown", )

#user mail
user_email = Label(root, text="Enter your Gmail address:  ")
user_email.pack()
user_email.config(bg="black", fg="white")

user_email = Entry(root, bd =8)
user_email.pack(fill=X)

#receiver email
receiver_email = Label(root, text="Enter the recipient's email address:
   ")
receiver_email.pack( )
receiver_email.config(bg="black", fg="white")

receiver_email = Entry(root, bd =8)
receiver_email.pack(fill=X)

#subject line
subj= Label(root, text="Enter your subject here: ")
subj.pack( )
subj.config(bg="black", fg="white")

subj = Entry(root, bd =8)
subj.pack(fill=X)

#Body of the message
body = Text(root, font="Tahoma",  relief=SUNKEN , bd=8)
body.config(bg="pink", height=15)
body.pack(fill=BOTH, expand=True)

#password widget
password = Label(root, text="Enter your Gmail password:  ")
password.pack()
password.config(bg="black", fg="white")

password= Entry(root, show='*', bd =8)
password.pack(fill=X)

#submit button
submit_mail = Button(root, bd =8, text="Click here to submit the mail",
command=gmail)
submit_mail.pack(fill=X)

#feed back
text = Text(root, font="Tahoma",  relief=SUNKEN , bd=8)
text.config(bg="pink",  height=2)
text.pack(fill=BOTH, expand=True)

root.mainloop()

the problem with my code above is that it can not send subject , only

body can be sent. I am also amateur with two months self learning. i will
recommend that you learn tkinter from this forum, yputube and a book
called 'an  introduction to tkinter by David Beazely'. hope this helps


问:
Python - Remove quotes and double minus using replace
Given a string such as

```<code>--"I like salami. "-I want to walk to the shops"
</code>```

How can I return the string such as

```<code>I like salami. I want to walk to the shops.
</code>```

I can alter each individually but when I use '-"' it fails.

Quotes

```<code>b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops
</code>```

Minus

```<code>b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"
</code>```

Together

```<code>MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"
</code>```

答:
Here is little different approach using beautiful lambda function:

```<code>word='--"I like salami. "-I want to walk to the shops"'
print("".join(list(map(lambda x:x if x!='-' and x!='"' else '',word))))
</code>```

output:

```<code>I like salami. I want to walk to the shops
</code>```

Body:
Given a string such as

--"I like salami. "-I want to walk to the shops"

How can I return the string such as

I like salami. I want to walk to the shops.

I can alter each individually but when I use '-"' it fails.

Quotes

b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops

Minus

b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"

Together

MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"

Body:
Here is little different approach using beautiful lambda function:

word='--"I like salami. "-I want to walk to the shops"'
print("".join(list(map(lambda x:x if x!='-' and x!='"' else '',word))))

output:

I like salami. I want to walk to the shops


问:
laravel undefined variable: itinerary
I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?

Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)

AgentsController update function

```<code>public function update(Request $request, $p_id){
    $this->validate($request, [
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);

    $packages = Packages::find($p_id);
    $packages->packageName = $request->input('packageName');
    $packages->adultPrice = $request->input('adultPrice');
    $packages->childPrice = $request->input('childPrice');
    $packages->infantPrice = $request->input('infantPrice');
    $packages->excessPrice = $request->input('excessPrice');
    $packages->type = $request->input('type');
    $packages->inclusions = $request->input('inclusions');
    $packages->additionalInfo = $request->input('additionalInfo');
    $packages->reminders = $request->input('reminders');
    $packages->photo = $request->input('photo');
    $packages->tags = $request->input('tags');
    $packages->save();

    $itinerary = Itinerary::find($p_id);
    if($itinerary->p_id == $packages->p_id){
    $itinerary->noOfDays = $request->input('noOfDays');
    $itinerary->day = $request->input('day');
    $itinerary->time = $request->input('time');
    $itinerary->destination = $request->input('destination');
    $itinerary->save();

    return redirect('Agent/Packages')->with('success', 'Updated');
    }
}
</code>```

edit.blade.php where the error is located

```<code>{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController@update', $packages->p_id, $itinerary->p_id)))!!}}
</code>```

Itinerary.php Model

```<code><?php
   namespace App;

   use Illuminate\Database\Eloquent\Model;

   class Itinerary extends Model{
      public $fillable = [
        'p_id',
        'noOfDays',
        'day',
        'time',
        'destination'
   ];

   protected $primaryKey = 'i_id';
   }
?>
</code>```

Edit function

```<code>public function edit($p_id){
   $packages = Packages::find($p_id);
   $itinerary = Itinerary::find($p_id);

   return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}
</code>```

答: In your edit.blade.php, try remplacing your $itinerary variable by $itineraries (plural).</p>

Title: laravel undefined variable: itinerary

Body:
I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?

Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)

AgentsController update function

public function update(Request $request, $p_id){
    $this->validate($request, [
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);

    $packages = Packages::find($p_id);
    $packages->packageName = $request->input('packageName');
    $packages->adultPrice = $request->input('adultPrice');
    $packages->childPrice = $request->input('childPrice');
    $packages->infantPrice = $request->input('infantPrice');
    $packages->excessPrice = $request->input('excessPrice');
    $packages->type = $request->input('type');
    $packages->inclusions = $request->input('inclusions');
    $packages->additionalInfo = $request->input('additionalInfo');
    $packages->reminders = $request->input('reminders');
    $packages->photo = $request->input('photo');
    $packages->tags = $request->input('tags');
    $packages->save();

    $itinerary = Itinerary::find($p_id);
    if($itinerary->p_id == $packages->p_id){
    $itinerary->noOfDays = $request->input('noOfDays');
    $itinerary->day = $request->input('day');
    $itinerary->time = $request->input('time');
    $itinerary->destination = $request->input('destination');
    $itinerary->save();

    return redirect('Agent/Packages')->with('success', 'Updated');
    }
}

edit.blade.php where the error is located

{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController@update', $packages->p_id, $itinerary->p_id)))!!}}

Itinerary.php Model

<?php
   namespace App;

   use Illuminate\Database\Eloquent\Model;

   class Itinerary extends Model{
      public $fillable = [
        'p_id',
        'noOfDays',
        'day',
        'time',
        'destination'
   ];

   protected $primaryKey = 'i_id';
   }
?>

Edit function

public function edit($p_id){
   $packages = Packages::find($p_id);
   $itinerary = Itinerary::find($p_id);

   return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}


问:
Use pyaudio to play files immediately after the other
I'm trying to modify my first Python program. I'm trying to use this repository to do some rudimentary text-to-speech. It does fine, but I want to improve it.

From the looks of it, there is a 0.145 second delay between samples played. Not all the samples of my voice will be 0.145 seconds, however, and I want to have each sample play one after the other with no delays or skips.

```<code>import re
import wave
import pyaudio
import _thread
import time

class TextToSpeech:

    CHUNK = 1024

    def __init__(self, words_pron_dict:str = 'cmudict-0.7b.txt'):
        self._l = {}
        self._load_words(words_pron_dict)

    def _load_words(self, words_pron_dict:str):
        with open(words_pron_dict, 'r') as file:
            for line in file:
                if not line.startswith(';;;'):
                    key, val = line.split('  ',2)
                    self._l[key] = re.findall(r"[A-Z]+",val)

    def get_pronunciation(self, str_input):
        list_pron = []
        for word in re.findall(r"[\w']+",str_input.upper()):
            if word in self._l:
                list_pron += self._l[word]
        print(list_pron)
        delay = 0.0
        for pron in list_pron:
            _thread.start_new_thread( TextToSpeech._play_audio, (pron,delay,))
            delay += 0.145

    def _play_audio(sound, delay):
        try:
            time.sleep(delay)
            wf = wave.open("sounds/"+sound+".wav", 'rb')
            p = pyaudio.PyAudio()
            stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

            data = wf.readframes(TextToSpeech.CHUNK)

            while data:
                stream.write(data)
                data = wf.readframes(TextToSpeech.CHUNK)

            stream.stop_stream()
            stream.close()

            p.terminate()
        except:
            pass

if __name__ == '__main__':
    tts = TextToSpeech()
    while True:
        tts.get_pronunciation(input('Enter a word or phrase: '))
</code>```

I've tried getting rid of the threading and delay, but there is some delay still between samples. I'm thinking that I should, instead of incrementing delay by 0.145, increment it by the length of the sample in seconds, but I've looked at the pyaudio documentation, and I have no idea how to do that.

Can someone help?

答:
Here is a modified code that plays wav files continuously.</p>

```<code>import re
import wave
import pyaudio

class TextToSpeech:

    CHUNK = 1024

    def __init__(self, words_pron_dict='cmudict-0.7b.txt'):
        self._l = {}
        self._load_words(words_pron_dict)

    def _load_words(self, words_pron_dict: str):
        with open(words_pron_dict, 'r') as file:
            for line in file:
                if not line.startswith(';;;'):
                    key, val = line.split('  ', 2)
                    self._l[key] = re.findall(r"[A-Z]+", val)

    def get_pronunciation(self, str_input):
        list_pron = []
        for word in re.findall(r"[\w']+", str_input.upper()):
            if word in self._l:
                list_pron += self._l[word]
        print(list_pron)

        # pyaudio set up.
        # This open method assume all wave files have the same format.
        p = pyaudio.PyAudio()
        stream = p.open(format=p.get_format_from_width(2),
                        channels=2,
                        rate=44100,
                        output=True,
                        frames_per_buffer=self.CHUNK)

        # play each wav file contineuously
        for pron in list_pron:
            with wave.open("sounds/"+pron+".wav", 'rb') as wf:
                data = wf.readframes(TextToSpeech.CHUNK)
                while data:
                    stream.write(data)
                    data = wf.readframes(TextToSpeech.CHUNK)

        stream.stop_stream()
        stream.close()
        p.terminate()

if __name__ == '__main__':
    tts = TextToSpeech()
    while True:
        tts.get_pronunciation(input('Enter a word or phrase: '))
</code>```

Body:
I'm trying to modify my first Python program. I'm trying to use this repository to do some rudimentary text-to-speech. It does fine, but I want to improve it.

From the looks of it, there is a 0.145 second delay between samples played. Not all the samples of my voice will be 0.145 seconds, however, and I want to have each sample play one after the other with no delays or skips.

import re
import wave
import pyaudio
import _thread
import time

class TextToSpeech:

    CHUNK = 1024

    def __init__(self, words_pron_dict:str = 'cmudict-0.7b.txt'):
        self._l = {}
        self._load_words(words_pron_dict)

    def _load_words(self, words_pron_dict:str):
        with open(words_pron_dict, 'r') as file:
            for line in file:
                if not line.startswith(';;;'):
                    key, val = line.split('  ',2)
                    self._l[key] = re.findall(r"[A-Z]+",val)

    def get_pronunciation(self, str_input):
        list_pron = []
        for word in re.findall(r"[\w']+",str_input.upper()):
            if word in self._l:
                list_pron += self._l[word]
        print(list_pron)
        delay = 0.0
        for pron in list_pron:
            _thread.start_new_thread( TextToSpeech._play_audio, (pron,delay,))
            delay += 0.145

    def _play_audio(sound, delay):
        try:
            time.sleep(delay)
            wf = wave.open("sounds/"+sound+".wav", 'rb')
            p = pyaudio.PyAudio()
            stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

            data = wf.readframes(TextToSpeech.CHUNK)

            while data:
                stream.write(data)
                data = wf.readframes(TextToSpeech.CHUNK)

            stream.stop_stream()
            stream.close()

            p.terminate()
        except:
            pass

if __name__ == '__main__':
    tts = TextToSpeech()
    while True:
        tts.get_pronunciation(input('Enter a word or phrase: '))

I've tried getting rid of the threading and delay, but there is some delay still between samples. I'm thinking that I should, instead of incrementing delay by 0.145, increment it by the length of the sample in seconds, but I've looked at the pyaudio documentation, and I have no idea how to do that.

Can someone help?

Body:
Here is a modified code that plays wav files continuously.

import re
import wave
import pyaudio

class TextToSpeech:

    CHUNK = 1024

    def __init__(self, words_pron_dict='cmudict-0.7b.txt'):
        self._l = {}
        self._load_words(words_pron_dict)

    def _load_words(self, words_pron_dict: str):
        with open(words_pron_dict, 'r') as file:
            for line in file:
                if not line.startswith(';;;'):
                    key, val = line.split('  ', 2)
                    self._l[key] = re.findall(r"[A-Z]+", val)

    def get_pronunciation(self, str_input):
        list_pron = []
        for word in re.findall(r"[\w']+", str_input.upper()):
            if word in self._l:
                list_pron += self._l[word]
        print(list_pron)

        # pyaudio set up.
        # This open method assume all wave files have the same format.
        p = pyaudio.PyAudio()
        stream = p.open(format=p.get_format_from_width(2),
                        channels=2,
                        rate=44100,
                        output=True,
                        frames_per_buffer=self.CHUNK)

        # play each wav file contineuously
        for pron in list_pron:
            with wave.open("sounds/"+pron+".wav", 'rb') as wf:
                data = wf.readframes(TextToSpeech.CHUNK)
                while data:
                    stream.write(data)
                    data = wf.readframes(TextToSpeech.CHUNK)

        stream.stop_stream()
        stream.close()
        p.terminate()

if __name__ == '__main__':
    tts = TextToSpeech()
    while True:
        tts.get_pronunciation(input('Enter a word or phrase: '))


问:
500 Internal server error CakePHP
I uploaded a cakePHP project to the Godaddy server.

I have also seen this link. But not solve the error:-

500 internal server error occured in CakePHP 3?

How to solve cakephp 500 Internal Server Error?

CakePHP 500 Internal Server Error

CakePHP shows 500 Internal Server Error

My .htaccess code in /root/.htaccess

```<code><IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>
</code>```

In /root/app/.htaccess

```<code><IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>
</code>```

In /root/app/webroot/.htaccess

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

This error is still coming after a lot of effort.

Please Help?

答: It may not be a problem everytime. Your .htaccess code may be alright. Please check permission of your root folder on godaddy server. It dependent on which type of server you use. Please enable to your folder permission on server. Then it may be working for you.</p>

Title: 500 Internal server error CakePHP

Body:
I uploaded a cakePHP project to the Godaddy server.

I have also seen this link. But not solve the error:-

500 internal server error occured in CakePHP 3?

How to solve cakephp 500 Internal Server Error?

CakePHP 500 Internal Server Error

CakePHP shows 500 Internal Server Error

My .htaccess code in /root/.htaccess

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

In /root/app/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

In /root/app/webroot/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

This error is still coming after a lot of effort.

Please Help?


问:
Sorting an incrementing list in C
I am trying to create a list of employees and sort the list based on age each time I add a new employee. The problem I am having is that only a list of 1 employee is "sorted". If I add another employee suddenly all of the ages become 0. Here is my code:

```<code>#include <stdio.h>
#include <string.h>
#include "employee.h"

int i = 0;
unsigned int employee_get_num (struct employee* list)
{
    unsigned int i;

    for (i=0; list[i].name[0]; i++);

    return i;
}

void employee_sort (struct employee* list)
{
    int n = i;
    int I, j;
    int tmp;

    printf("There are %d employees\n", n);
    for(I=0; I<n; I++)
        printf("Age: %d\n", list[i-1].age);

    for(I=0; I<(n-1); I++)
        for(j=0; j<n-I-1; j++)
            if(list[j].age > list[j+1].age){
                tmp = list[j].age;
                list[j].age = list[j+1].age;
                list[j+1].age = tmp;
            }
    printf("Sorted list:\n");
    for(I=0; I<n; I++)
        printf("%d\n", list[i-1].age);  // only printing zeros for some reason
}

void employee_add (struct employee* list)
{
    i = i+1;    // i is global, keeps track of employees
    char first[128];
    char last[128];
    char space[] = " ";

    printf ("First Name: ");
    scanf ("%s", first);
    printf("Last Name: ");
    scanf ("%s", last);
    // Concatenate first and last name into one string
    strcpy(list[i-1].name, first);
    strcat(list[i-1].name, space);
    strcat(list[i-1].name, last);

    printf (" Age: ");
    scanf("%u", &(list->age));
    printf ("Wage: ");
    scanf("%u", &(list->wage));

    employee_sort(&list[i-1]);
}
</code>```

I think that I might not be increasing correctly.

Header file:

```<code>#ifndef _employee_h_
#define _employee_h_

struct employee {
    char name[128];
    unsigned int age;
    unsigned int wage;
};

unsigned int employee_get_num (struct employee* list);
void employee_print (struct employee* e);
void employee_print_all (struct employee* list);
void employee_sort (struct employee* array);
void employee_add (struct employee* list);
void employee_delete (struct employee* list);

#endif
</code>```

main() (in menu.c)

```<code>int main (unsigned int argc, char** argv)
{
    struct employee list[MAX];

    unsigned int running = 1;

    /* Set all bits in the employee array to zero */
    memset (list, 0, MAX*sizeof(struct employee));

    while (running) {
        switch (print_menu()) {
            case OPTION_ADD:
                employee_add(list);
                break;
            case OPTION_DEL:
                employee_delete(list);
                break;
            case OPTION_LIST:
                employee_print_all(list);
                break;
            case OPTION_QUIT:
                running = 0;
                break;
        };

    }

    return 0;
}
</code>```

I left out the rest of menu.c because it only prints the menu which you'll see below.

The output should look like:

```<code>[1] Add New Employee
[2] Delete an Employee
[3] List All by Age (Acending)
[4] Quit
------------------------
Selection: 1
First Name: Bob
Last Name: Smith
 Age: 40
Wage: 60000
There are 1 employees
 Age: 40
Sorted list:
40

[1] Add New Employee
[2] Delete an Employee
[3] List All by Age (Acending)
[4] Quit
------------------------
Selection: 1
First Name: John
Last Name: Connor
 Age: 35
Wage: 62000
There are 2 employees
 Age: 40
 Age: 35
Sorted list:
35
40
</code>```

I added some extra print statements just to show what it is supposed to be doing.

I'm also worried that it is only going to sort the age and not the rest of the information

答:
Firstly in employee_add when calling employee_sort you are passing the last struct element. Pass the first employee. Change last line in employee_add to

employee_sort(list);

Next problem

If I add another employee suddenly all of the ages become 0

No it doesn't. In employee_sort in the for loop before sorting, change it to

```<code>printf("There are %d employees\n", n);
    for(I=0; I<n; I++)
        printf("Age: %d\n", list[I].age);
</code>```

Next

While taking age and wage input change it to

```<code>scanf("%u", &(list[i-1].age));
scanf("%u", &(list[i-1].wage));
</code>```

I'm also worried that it is only going to sort the age and not the rest of the information

Yes you are only sorting age, you should sort whole struct based on age.

```<code>for(I=0; I<(n-1); I++)
        for(j=0; j<n-I-1; j++)
            if(list[j].age > list[j+1].age){
                tmp = list[j];
                list[j] = list[j+1];
                list[j+1] = tmp;
            }
</code>```

And the final problem of printing sorted list

```<code> printf("Sorted list:\n");
    for(I=0; I<n; I++)
        printf("%d\n", list[I].age);
</code>```

PS Note the list[I] in every printf and not list[i+1]

Edit

Instead of sorting it yourself, you can use qsort biult in function in stdlib.h header file.

Implementation: You will need to define a comparator function as you dont have a traditional array to sort

Just define a function

```<code>int comparator(const struct employee *p, const struct employee *q)
{
    int l = p->age;
    int r = q->age;
    return (l - r);
}
</code>```

And then where you sort the list call qsort like this

```<code>qsort(list,i,sizeof(list[0]),comparator);
</code>```

Title: Sorting an incrementing list in C

Body:
I am trying to create a list of employees and sort the list based on age each time I add a new employee. The problem I am having is that only a list of 1 employee is "sorted". If I add another employee suddenly all of the ages become 0. Here is my code:

#include <stdio.h>
#include <string.h>
#include "employee.h"

int i = 0;
unsigned int employee_get_num (struct employee* list)
{
    unsigned int i;

    for (i=0; list[i].name[0]; i++);

    return i;
}

void employee_sort (struct employee* list)
{
    int n = i;
    int I, j;
    int tmp;

    printf("There are %d employees\n", n);
    for(I=0; I<n; I++)
        printf("Age: %d\n", list[i-1].age);

    for(I=0; I<(n-1); I++)
        for(j=0; j<n-I-1; j++)
            if(list[j].age > list[j+1].age){
                tmp = list[j].age;
                list[j].age = list[j+1].age;
                list[j+1].age = tmp;
            }
    printf("Sorted list:\n");
    for(I=0; I<n; I++)
        printf("%d\n", list[i-1].age);  // only printing zeros for some reason
}

void employee_add (struct employee* list)
{
    i = i+1;    // i is global, keeps track of employees
    char first[128];
    char last[128];
    char space[] = " ";

    printf ("First Name: ");
    scanf ("%s", first);
    printf("Last Name: ");
    scanf ("%s", last);
    // Concatenate first and last name into one string
    strcpy(list[i-1].name, first);
    strcat(list[i-1].name, space);
    strcat(list[i-1].name, last);

    printf (" Age: ");
    scanf("%u", &(list->age));
    printf ("Wage: ");
    scanf("%u", &(list->wage));

    employee_sort(&list[i-1]);
}

I think that I might not be increasing correctly.

Header file:

#ifndef _employee_h_
#define _employee_h_

struct employee {
    char name[128];
    unsigned int age;
    unsigned int wage;
};

unsigned int employee_get_num (struct employee* list);
void employee_print (struct employee* e);
void employee_print_all (struct employee* list);
void employee_sort (struct employee* array);
void employee_add (struct employee* list);
void employee_delete (struct employee* list);

#endif

main() (in menu.c)

int main (unsigned int argc, char** argv)
{
    struct employee list[MAX];

    unsigned int running = 1;

    /* Set all bits in the employee array to zero */
    memset (list, 0, MAX*sizeof(struct employee));

    while (running) {
        switch (print_menu()) {
            case OPTION_ADD:
                employee_add(list);
                break;
            case OPTION_DEL:
                employee_delete(list);
                break;
            case OPTION_LIST:
                employee_print_all(list);
                break;
            case OPTION_QUIT:
                running = 0;
                break;
        };

    }

    return 0;
}

I left out the rest of menu.c because it only prints the menu which you'll see below.

The output should look like:

[1] Add New Employee
[2] Delete an Employee
[3] List All by Age (Acending)
[4] Quit
------------------------
Selection: 1
First Name: Bob
Last Name: Smith
 Age: 40
Wage: 60000
There are 1 employees
 Age: 40
Sorted list:
40

[1] Add New Employee
[2] Delete an Employee
[3] List All by Age (Acending)
[4] Quit
------------------------
Selection: 1
First Name: John
Last Name: Connor
 Age: 35
Wage: 62000
There are 2 employees
 Age: 40
 Age: 35
Sorted list:
35
40

I added some extra print statements just to show what it is supposed to be doing.

I'm also worried that it is only going to sort the age and not the rest of the information

Body:
Firstly in employee_add when calling employee_sort you are passing the last struct element. Pass the first employee. Change last line in employee_add to

employee_sort(list);

Next problem

If I add another employee suddenly all of the ages become 0

No it doesn't. In employee_sort in the for loop before sorting, change it to

printf("There are %d employees\n", n);
    for(I=0; I<n; I++)
        printf("Age: %d\n", list[I].age);

Next

While taking age and wage input change it to

scanf("%u", &(list[i-1].age));
scanf("%u", &(list[i-1].wage));

I'm also worried that it is only going to sort the age and not the rest of the information

Yes you are only sorting age, you should sort whole struct based on age.

for(I=0; I<(n-1); I++)
        for(j=0; j<n-I-1; j++)
            if(list[j].age > list[j+1].age){
                tmp = list[j];
                list[j] = list[j+1];
                list[j+1] = tmp;
            }

And the final problem of printing sorted list

 printf("Sorted list:\n");
    for(I=0; I<n; I++)
        printf("%d\n", list[I].age);

PS Note the list[I] in every printf and not list[i+1]

Edit

Instead of sorting it yourself, you can use qsort biult in function in stdlib.h header file.

Implementation: You will need to define a comparator function as you dont have a traditional array to sort

Just define a function

int comparator(const struct employee *p, const struct employee *q)
{
    int l = p->age;
    int r = q->age;
    return (l - r);
}

And then where you sort the list call qsort like this

qsort(list,i,sizeof(list[0]),comparator);


问:
How to get a specific json key value from post request response in Android?
I have following response from post request using HttpURLConnection:

Post Request Response:

```<code>{
    "LatestData": [{
        "ExtraData": null,
        "ID": 0,
        "season": false,
        "latest": 0,
        "url": "http://www.awebsite.com/images/12.jpg"
    }]
}
</code>```

How to get value of URL? I tried following but Android Studio keeps giving me error:

```<code>String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
</code>```

Android Studio Error:

```<code>error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
</code>```

could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks

android code:

```<code> if (myURLConnection.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    line = br.readLine();
                    if (line != null) {
                        sb.append(line + "\n");

                        //String newURL = sb.getJSONObject("LatestData").getString("url");
                        String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
                        mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
                    } else {
                        br.close();
                        return sb.toString();
                    }
                }
            }
</code>```

答:
Can you try this :

```<code>StringBuilder sb = new StringBuilder();
line = br.readLine();
while(line != null){
    sb.append(line);
}
// if it's fail here then this means there is an issue in parsing JSONObject
JSONObject jsonObj = new JSONObject(sb.toString());
JSONArray latestData = jsonObj.getJSONArray("LatestData");
JSONObject jsonObject = latestData.getJSONObject(0);
String url = jsonObject.getString("url");
</code>```

Also I'm highly recommending to use Retrofit with GSON .. you can follow this article : http://www.vogella.com/tutorials/Retrofit/article.html

Body:
I have following response from post request using HttpURLConnection:

Post Request Response:

{
    "LatestData": [{
        "ExtraData": null,
        "ID": 0,
        "season": false,
        "latest": 0,
        "url": "http://www.awebsite.com/images/12.jpg"
    }]
}

How to get value of URL? I tried following but Android Studio keeps giving me error:

String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");

Android Studio Error:

error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)

could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks

android code:

 if (myURLConnection.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    line = br.readLine();
                    if (line != null) {
                        sb.append(line + "\n");

                        //String newURL = sb.getJSONObject("LatestData").getString("url");
                        String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
                        mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
                    } else {
                        br.close();
                        return sb.toString();
                    }
                }
            }

Body:
Can you try this :

StringBuilder sb = new StringBuilder();
line = br.readLine();
while(line != null){
    sb.append(line);
}
// if it's fail here then this means there is an issue in parsing JSONObject
JSONObject jsonObj = new JSONObject(sb.toString());
JSONArray latestData = jsonObj.getJSONArray("LatestData");
JSONObject jsonObject = latestData.getJSONObject(0);
String url = jsonObject.getString("url");

Also I'm highly recommending to use Retrofit with GSON .. you can follow this article : http://www.vogella.com/tutorials/Retrofit/article.html


问:
SQL - Can this relation have a primary key?
The relationship between bands and members, 'MemberOf', includes a member id (Mid), band id (Bid), 'StartYear', 'EndYear' and 'Instrument' played. Mid and Bid are both foreign keys to Member and Band relations respectively but I am struggling to identify the primary key in this situation for the 'MemberOf' relation.

Note: start year can be null if a member was in a band from the start and end year can also be null if a member is still in the band.

In this situation, start and end year cannot be used as PK's as they may contain null values, but the member id and band id is not enough information to be unique - e.g. the same member returns to the same band at a later date.

Does this mean no primary key exists? Thanks.

答:
This is a common problem.  To see what's going on, we need to disentangle the relational concept 'primary key' from the SQL construct PRIMARY KEY.

The relational concept 'primary key' is a unique identifier for the rows in a table.  In the context of your table, the band and the member are clearly part of the primary key, and so too is the period during which the member played for the band.  A single member could play for a specific band in, say, 2003-2005, go off on a solo career for 2006-2007, and rejoin his original band for 2008-2011.  You'd need two entries for the member in the table, one for each of the two periods.

Ideally, you'd be able to say 'startYear' and 'endYear' form a single 'memberFor' period column and the primary key is (bid, mid, memberFor) and for a single combination of bid+mid, the memberFor values represent disjoint ranges: that is, for two rows R1, R2, the value R1.memberFor does not overlap or touch R2.memberFor.  Example overlap: R1.memberFor = (2003-2005), R2.Memberfor = (2004-2006).  Example touch: R1.memberFor = (2003-2005), R2.MemberFor = (2005-2007).

So much for the theory.

In practice, SQL does not support time periods, where a time period in this context has a start and a duration. The INTERVAL types do not qualify because they represent duration without the start, and the DATE, TIME, TIMESTAMP types do not qualify because they lack the duration (ignoring issues of quantization which are not germane to the matter at hand).  Clearly, you can also represent a period by (duration, end) and also by (start, end), and in the latter case, you can have open, closed, open-closed or closed-open ranges for the start and end.

Because SQL does not support the requisite type, much less the necessary checking options, you have to do the checking yourself, and it is complex to do it.  The SQL primary key only looks for equality of values.  Unconstrained, it means that if you create the primary key on (bid, mid, start) or (bid, mid, end) or (bid, mid, start, end), you can end up with unwanted data in the table which satisfies the SQL primary key but not the conceptual primary key.

```<code>Bid     Mid     Start   End
  1       1      2003   2005   - α
  1       1      2004   2006   - β
  1       1      2004   2007   - γ
  1       1      2008   2011   - δ
</code>```

Consider the row tagged α as correct.  If your SQL primary key is on (bid, mid, start), then the row tagged β should not be allowed because it overlaps with α; similarly for γ.  However, SQL only prevents β and γ both appearing; the one entered first will be OK and the one entered second will be rejected.  If γ were allowed, then ∂ should not be allowed because it touches γ. Similarly, if the SQL primary key were on (bid, mid, start, end), all four rows would be allowed into the table, but clearly they should not be.  And if the SQL primary key was on (bid, mid, end), all the rows above would be allowed in.

So, you would have to augment the criteria for the SQL primary key with a complex query that filters out unwanted rows.  This would like be stored procedure used in an insert trigger for the table and in an update trigger.

…details left as exercise for reader…

In your table, you have a year-based granularity.  You could probably, therefore, get away with a revised table that stored just (mid, bid, memberInYear), and have one row for each band member for each year when they were a member of the given band.  This reduces to a large quantum time period where the SQL primary key on the three columns enforces the constraint.  However, if you change the granularity of the table to record the start and end dates (down to the day), then clearly the revised design does not work well.

So, you should probably go with an SQL primary key on (bid, mid, start) backed up by a stored procedure invoked from insert and update triggers that enforces the non-overlap and non-touching criteria.

ContentLicense: CC BY-SA 2.5

Body:
This is a common problem.  To see what's going on, we need to disentangle the relational concept 'primary key' from the SQL construct PRIMARY KEY.

The relational concept 'primary key' is a unique identifier for the rows in a table.  In the context of your table, the band and the member are clearly part of the primary key, and so too is the period during which the member played for the band.  A single member could play for a specific band in, say, 2003-2005, go off on a solo career for 2006-2007, and rejoin his original band for 2008-2011.  You'd need two entries for the member in the table, one for each of the two periods.

Ideally, you'd be able to say 'startYear' and 'endYear' form a single 'memberFor' period column and the primary key is (bid, mid, memberFor) and for a single combination of bid+mid, the memberFor values represent disjoint ranges: that is, for two rows R1, R2, the value R1.memberFor does not overlap or touch R2.memberFor.  Example overlap: R1.memberFor = (2003-2005), R2.Memberfor = (2004-2006).  Example touch: R1.memberFor = (2003-2005), R2.MemberFor = (2005-2007).

So much for the theory.

In practice, SQL does not support time periods, where a time period in this context has a start and a duration. The INTERVAL types do not qualify because they represent duration without the start, and the DATE, TIME, TIMESTAMP types do not qualify because they lack the duration (ignoring issues of quantization which are not germane to the matter at hand).  Clearly, you can also represent a period by (duration, end) and also by (start, end), and in the latter case, you can have open, closed, open-closed or closed-open ranges for the start and end.

Because SQL does not support the requisite type, much less the necessary checking options, you have to do the checking yourself, and it is complex to do it.  The SQL primary key only looks for equality of values.  Unconstrained, it means that if you create the primary key on (bid, mid, start) or (bid, mid, end) or (bid, mid, start, end), you can end up with unwanted data in the table which satisfies the SQL primary key but not the conceptual primary key.

Bid     Mid     Start   End
  1       1      2003   2005   - α
  1       1      2004   2006   - β
  1       1      2004   2007   - γ
  1       1      2008   2011   - δ

Consider the row tagged α as correct.  If your SQL primary key is on (bid, mid, start), then the row tagged β should not be allowed because it overlaps with α; similarly for γ.  However, SQL only prevents β and γ both appearing; the one entered first will be OK and the one entered second will be rejected.  If γ were allowed, then ∂ should not be allowed because it touches γ. Similarly, if the SQL primary key were on (bid, mid, start, end), all four rows would be allowed into the table, but clearly they should not be.  And if the SQL primary key was on (bid, mid, end), all the rows above would be allowed in.

So, you would have to augment the criteria for the SQL primary key with a complex query that filters out unwanted rows.  This would like be stored procedure used in an insert trigger for the table and in an update trigger.

…details left as exercise for reader…

In your table, you have a year-based granularity.  You could probably, therefore, get away with a revised table that stored just (mid, bid, memberInYear), and have one row for each band member for each year when they were a member of the given band.  This reduces to a large quantum time period where the SQL primary key on the three columns enforces the constraint.  However, if you change the granularity of the table to record the start and end dates (down to the day), then clearly the revised design does not work well.

So, you should probably go with an SQL primary key on (bid, mid, start) backed up by a stored procedure invoked from insert and update triggers that enforces the non-overlap and non-touching criteria.


问:
R boxcox not working
```<code>data1 <- read.csv("~/Desktop/Group_22.csv")

View(data1)

E_var <- regmatches(names(data1), regexpr("(E[0-9])+", names(data1)))
G_var <- regmatches(names(data1), regexpr("(G[0-9]*)+", names(data1)))

(E_vs_G  <- paste0(c(gsub(" ", "*", outer(E_var, G_var, paste))), collapse = "+"))
(G_eff_1 <- paste("I(", G_var, ")", collapse="+"))
(G_eff_2 <- paste("I(", apply( combn(G_var, 2), 2, paste, collapse="*"), ")", collapse="+"))
(G_eff_3 <- paste("I(", apply( combn(G_var, 3), 2, paste, collapse="*"), ")", collapse="+"))
(E_eff  <- paste0("I(", E_var,"^2", ")", collapse = "+"))

(formula <- paste( "I(log(Y)) ~" , paste(c(E_eff, G_eff_1, G_eff_2, G_eff_3, E_vs_G), collapse = "+")))

M <- lm(formula, data=data1)
summary(M)

anova(M)

install.packages('MASS')

library(MASS)

boxcox(M)

Error: object of type 'closure' is not subsettable
</code>```

the code runs properly except when it gets to boxcox(M) it gives me that error. what am i doing wrong?

答:
That is a particularly vague and non-helpful error, but if you understand what a "closure" is then it might provide insight on where to look. Unfortunately, here it is a little difficult to find it ...

TL;DR

Rename your variable from formula to anything else that is not a function name. Your code works fine if you use frm <- paste(...), for instance.

NB: this is a classic example of why you should avoid naming variables the same as a function. Often you'll see variables named just data. In this case, formula is a function that, due to package search paths, is not found in the order you would expect.

Explanation

To find out why, first we need to debug the specific function being called. We can use debug(boxcox) and step our way into it, or we can do debug(MASS:::boxcox.lm) to make sure we debug the correct one. Regardless ...

```<code>boxcox(M)
# debugging in: boxcox.lm(M)
# debug: {
#     m <- length(lambda)
#     if (is.null(object$y) || is.null(object$qr))
#         object <- update(object, y = TRUE, qr = TRUE, ...)
#     result <- NextMethod()
#     if (plotit)
#         invisible(result)
#     else result
# }
</code>```

Stepping through this, it fails with the call to update. Not very informative, we'll need to step within that. We can use s to step into the function. (By the way, it's using MASS:::update.loglm, not an export function.)

```<code># Browse[2]>
s
# debugging in: update(object, y = TRUE, qr = TRUE, ...)
# debug: UseMethod("update")
# Browse[3]>
s
# debugging in: update.default(object, y = TRUE, qr = TRUE, ...)
# debug: {
#     if (is.null(call <- getCall(object)))
#         stop("need an object with call component")
#     extras <- match.call(expand.dots = FALSE)$...
#     if (!missing(formula.))
#         call$formula <- update.formula(formula(object), formula.)
#     if (length(extras)) {
#         existing <- !is.na(match(names(extras), names(call)))
#         for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
#         if (any(!existing)) {
#             call <- c(as.list(call), extras[!existing])
#             call <- as.call(call)
#         }
#     }
#     if (evaluate)
#         eval(call, parent.frame())
#     else call
# }
</code>```

Stepping through this, it fails on the last command, eval(call, parent.frame()). Not very helpful still, but it's useful while troubleshooting to look at the variables R thinks it is using. For instance, earlier:

```<code># Browse[2]>
object
# Call:
# lm(formula = formula, data = data1)
# Coefficients:
#  (Intercept)      I(cyl^2)     I(disp^2)         I(hp)       I(drat)  I(hp * drat)           cyl
#    3.274e+00    -2.006e-02     9.589e-06    -1.250e-02     2.388e-01     5.869e-04     4.034e-01
#           hp          disp          drat        cyl:hp       hp:disp      cyl:drat     disp:drat
#           NA    -9.728e-03            NA     2.122e-03    -2.418e-05    -1.155e-01     2.064e-03
</code>```

Okay, that looks correct. Next, realize that the eval call is trying to recall the previous model with an update to it.

```<code># Browse[4]>
call
# lm(formula = formula, data = data1)
</code>```

That looks similar to how we called it the first time. However, looking at the actual variables, data1 looks correct but ...

```<code># Browse[4]>
formula
# function (x, ...)
# UseMethod("formula")
# <bytecode: 0x000000001a5c20a0>
# <environment: namespace:stats>
</code>```

Oh. So the formula being referenced in the recent call to lm is not reaching back to the original calling environment, even with eval(...,parent.frame()).

If you instead use:

```<code>(frm <- paste( "I(log(Y)) ~" , paste(c(E_eff, G_eff_1, G_eff_2, G_eff_3, E_vs_G), collapse = "+")))
M <- lm(frm, data=data1)
</code>```

then things work fine.

Title: R boxcox not working

Body:
data1 <- read.csv("~/Desktop/Group_22.csv")

View(data1)

E_var <- regmatches(names(data1), regexpr("(E[0-9])+", names(data1)))
G_var <- regmatches(names(data1), regexpr("(G[0-9]*)+", names(data1)))

(E_vs_G  <- paste0(c(gsub(" ", "*", outer(E_var, G_var, paste))), collapse = "+"))
(G_eff_1 <- paste("I(", G_var, ")", collapse="+"))
(G_eff_2 <- paste("I(", apply( combn(G_var, 2), 2, paste, collapse="*"), ")", collapse="+"))
(G_eff_3 <- paste("I(", apply( combn(G_var, 3), 2, paste, collapse="*"), ")", collapse="+"))
(E_eff  <- paste0("I(", E_var,"^2", ")", collapse = "+"))

(formula <- paste( "I(log(Y)) ~" , paste(c(E_eff, G_eff_1, G_eff_2, G_eff_3, E_vs_G), collapse = "+")))

M <- lm(formula, data=data1)
summary(M)

anova(M)

install.packages('MASS')

library(MASS)

boxcox(M)

Error: object of type 'closure' is not subsettable

the code runs properly except when it gets to boxcox(M) it gives me that error. what am i doing wrong?

Body:
That is a particularly vague and non-helpful error, but if you understand what a "closure" is then it might provide insight on where to look. Unfortunately, here it is a little difficult to find it ...

TL;DR

Rename your variable from formula to anything else that is not a function name. Your code works fine if you use frm <- paste(...), for instance.

NB: this is a classic example of why you should avoid naming variables the same as a function. Often you'll see variables named just data. In this case, formula is a function that, due to package search paths, is not found in the order you would expect.

Explanation

To find out why, first we need to debug the specific function being called. We can use debug(boxcox) and step our way into it, or we can do debug(MASS:::boxcox.lm) to make sure we debug the correct one. Regardless ...

boxcox(M)
# debugging in: boxcox.lm(M)
# debug: {
#     m <- length(lambda)
#     if (is.null(object$y) || is.null(object$qr))
#         object <- update(object, y = TRUE, qr = TRUE, ...)
#     result <- NextMethod()
#     if (plotit)
#         invisible(result)
#     else result
# }

Stepping through this, it fails with the call to update. Not very informative, we'll need to step within that. We can use s to step into the function. (By the way, it's using MASS:::update.loglm, not an export function.)

# Browse[2]>
s
# debugging in: update(object, y = TRUE, qr = TRUE, ...)
# debug: UseMethod("update")
# Browse[3]>
s
# debugging in: update.default(object, y = TRUE, qr = TRUE, ...)
# debug: {
#     if (is.null(call <- getCall(object)))
#         stop("need an object with call component")
#     extras <- match.call(expand.dots = FALSE)$...
#     if (!missing(formula.))
#         call$formula <- update.formula(formula(object), formula.)
#     if (length(extras)) {
#         existing <- !is.na(match(names(extras), names(call)))
#         for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
#         if (any(!existing)) {
#             call <- c(as.list(call), extras[!existing])
#             call <- as.call(call)
#         }
#     }
#     if (evaluate)
#         eval(call, parent.frame())
#     else call
# }

Stepping through this, it fails on the last command, eval(call, parent.frame()). Not very helpful still, but it's useful while troubleshooting to look at the variables R thinks it is using. For instance, earlier:

# Browse[2]>
object
# Call:
# lm(formula = formula, data = data1)
# Coefficients:
#  (Intercept)      I(cyl^2)     I(disp^2)         I(hp)       I(drat)  I(hp * drat)           cyl
#    3.274e+00    -2.006e-02     9.589e-06    -1.250e-02     2.388e-01     5.869e-04     4.034e-01
#           hp          disp          drat        cyl:hp       hp:disp      cyl:drat     disp:drat
#           NA    -9.728e-03            NA     2.122e-03    -2.418e-05    -1.155e-01     2.064e-03

Okay, that looks correct. Next, realize that the eval call is trying to recall the previous model with an update to it.

# Browse[4]>
call
# lm(formula = formula, data = data1)

That looks similar to how we called it the first time. However, looking at the actual variables, data1 looks correct but ...

# Browse[4]>
formula
# function (x, ...)
# UseMethod("formula")
# <bytecode: 0x000000001a5c20a0>
# <environment: namespace:stats>

Oh. So the formula being referenced in the recent call to lm is not reaching back to the original calling environment, even with eval(...,parent.frame()).

If you instead use:

(frm <- paste( "I(log(Y)) ~" , paste(c(E_eff, G_eff_1, G_eff_2, G_eff_3, E_vs_G), collapse = "+")))
M <- lm(frm, data=data1)

then things work fine.


问:
Faster code numpy
I am writing a Python script from a Matlab one. It happens that in Matlab, the code runs much faster (like 10 minutes less), so maybe you could help me figure out what I'm doing wrong. I ran all the sessions in Python, and I found that the slowest are the two following:

```<code>X = xi * math.cos(theta) + zi * (math.sin(theta))
Y = yi
Z = xi * ((-1) * math.sin(theta)) + zi * (math.cos(theta))

x2 = [a * b * c * X[i] / np.sqrt((a * c * Y[i])**2 + b**2 * (
    c**2 * (X[i])**2 + a**2 * (Z[i])**2)) for i in range(len(X))]
y2 = [a * b * c * Y[i] / np.sqrt((a * c * Y[i])**2 + b**2 * (
    c**2 * X[i]**2 + a**2 * Z[i]**2)) for i in range(len(X))]
zt = c**2 * (1 - (x2 / a)**2 - (y2 / b)**2)
i = 0
z2 = []
for i in range(len(Z)):
    z2.append((-1 if Z[i] < 0 else 1) * np.sqrt(zt[i]))
</code>```

where xi,yi and zi are numpy floats of more than 1 million elements

thank you

Title: Faster code numpy

Body:
I am writing a Python script from a Matlab one. It happens that in Matlab, the code runs much faster (like 10 minutes less), so maybe you could help me figure out what I'm doing wrong. I ran all the sessions in Python, and I found that the slowest are the two following:

X = xi * math.cos(theta) + zi * (math.sin(theta))
Y = yi
Z = xi * ((-1) * math.sin(theta)) + zi * (math.cos(theta))

x2 = [a * b * c * X[i] / np.sqrt((a * c * Y[i])**2 + b**2 * (
    c**2 * (X[i])**2 + a**2 * (Z[i])**2)) for i in range(len(X))]
y2 = [a * b * c * Y[i] / np.sqrt((a * c * Y[i])**2 + b**2 * (
    c**2 * X[i]**2 + a**2 * Z[i]**2)) for i in range(len(X))]
zt = c**2 * (1 - (x2 / a)**2 - (y2 / b)**2)
i = 0
z2 = []
for i in range(len(Z)):
    z2.append((-1 if Z[i] < 0 else 1) * np.sqrt(zt[i]))

where xi,yi and zi are numpy floats of more than 1 million elements

thank you

Body:
for for z2 part

In [1]: import numpy as np
In [2]: zz =np.array([1, 2, 3, -1, -2, -3, 0])
In [3]: aa = np.array([1, 2, 3, 4, 5, 6, 64])
In [4]: Z =np.array([1, 2, 3, -1, -2, -3, 0])
In [5]: zt = np.array([1, 2, 3, 4, 5, 6, 64])
In [6]: np.sign(Z) * np.sqrt(zt)
Out[7]:
array([ 1., 1.41421356, 1.73205081, -2., -2.23606798, -2.44948974, 0. ])


问:
jQuery result beign overwritten by the info sent from the GET Method
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

Html of the modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

GET Method:

```<code>    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }
</code>```

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

```<code><script type="text/javascript">

    var wasclicked = 0;
    var $this = this;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            //is AddNew Store button is hitted, this var = 1
            wasclicked = 1;
        };

        $('#modal-action-store').on('hidden.bs.modal', function () {
            //global.wasclicked = 0;
            wasclicked = 0;
            $(this).removeData('bs.modal');
        });

        $('#modal-action-store').on('shown.bs.modal', function (e) {
            console.log($('#DistrictID').length);
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            };
        });
    });
</script>
</code>```

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

```<code>  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
</code>```

And this line is lost:

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
</code>```

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

答:
Try to replace your code:

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
</code>```

by

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
var currentItems = $('#DistrictID').html();
$('#DistrictID').html(items + currentItems)
</code>```

Hope this helps you :)

Body:
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

              NEW STORE

Html of the modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

GET Method:

    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"

And this line is lost:

var items = "<option value='0'>-- Seleccione Distrito --</option>";

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

Body:
Try to replace your code:

var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);

by

var items = "<option value='0'>-- Seleccione Distrito --</option>";
var currentItems = $('#DistrictID').html();
$('#DistrictID').html(items + currentItems)

Hope this helps you :)


问:
How to compare two array and alert the result?
I have two simple arrays:

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.
</code>```

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

```<code>arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)
</code>```

I use $.each but it's only check the array. Not comparing them.

```<code>$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});
</code>```

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

答:
You can do by simple javascript with your log message</p>

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
//This is varies depend of the array created.

var numberNotAvailable = [];

for(var i = 0; i<arr_must_exist.length; i++){
  console.log(arr_created.indexOf(arr_must_exist[i]));
  if(arr_created.indexOf(arr_must_exist[i]) < 0){
        console.log(arr_must_exist[i] + ' added');
        numberNotAvailable.push(arr_must_exist[i])
  }
}

var logMessage ;
if(numberNotAvailable.length == 0){
  logMessage = 'Your choice is valid';
}
else if(numberNotAvailable.length == 1){
  logMessage = 'Your choice must contain ' + numberNotAvailable[0];
}
else if(numberNotAvailable.length == 2){
  logMessage = 'Your choice must contain ' + numberNotAvailable[0] + ' and ' + numberNotAvailable[1];
}
else if(numberNotAvailable.length > 2){
  logMessage = 'Your choice must contain ' + fruits.join();
}

console.log(logMessage);
</code>```

Body:
I have two simple arrays:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

I use $.each but it's only check the array. Not comparing them.

$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

Body:
You can do by simple javascript with your log message

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
//This is varies depend of the array created.

var numberNotAvailable = [];

for(var i = 0; i<arr_must_exist.length; i++){
  console.log(arr_created.indexOf(arr_must_exist[i]));
  if(arr_created.indexOf(arr_must_exist[i]) < 0){
        console.log(arr_must_exist[i] + ' added');
        numberNotAvailable.push(arr_must_exist[i])
  }
}

var logMessage ;
if(numberNotAvailable.length == 0){
  logMessage = 'Your choice is valid';
}
else if(numberNotAvailable.length == 1){
  logMessage = 'Your choice must contain ' + numberNotAvailable[0];
}
else if(numberNotAvailable.length == 2){
  logMessage = 'Your choice must contain ' + numberNotAvailable[0] + ' and ' + numberNotAvailable[1];
}
else if(numberNotAvailable.length > 2){
  logMessage = 'Your choice must contain ' + fruits.join();
}

console.log(logMessage);


问:
Getting CSS file by ID to manipulate the properties
I have the following snippet that overwrites certain CSS properties:-

```<code>var styleSheet  = document.styleSheets[2]; // refers to the 3rd stylesheet

// Mozilla
if (styleSheet.cssRules) {
    var cssRule     = styleSheet.cssRules;

    // ... do something
}
// IE
else {
    var cssRule     = styleSheet.rules;

    // ... do something
}
</code>```

This code works, but I don't like the fact that I'm referencing the stylesheet using document.styleSheets[2] because it is brittle. So, I assigned an id to the link tag, hoping that I can use JQuery to easily get that stylesheet by id. However, I'm not sure how to cast the returned object from JQuery into a CSSStyleSheet object so that I can assign it to styleSheet variable.

```<code>// I want to change this...
var styleSheet  = document.styleSheets[2]; // [object CSSStyleSheet]

// ... to something like this...
var styleSheet  = $("link#layout"); // not right because it is a [object Object]
</code>```

Any clue? Thanks.

UPDATE

Per @TJ's suggestion, after futzing around, I think I might go with title instead of href... at least for now until I find any incompatibilities next time. Right now, this works in FF, IE, Safari and Chrome.

```<code>for (var i = 0; i < document.styleSheets.length; ++i) {
    var styleSheet  = document.styleSheets[i];

    if (document.styleSheets[i].title == "layout-overwrite") {
        // Mozilla
        if (styleSheet.cssRules) {
            var cssRule = styleSheet.cssRules;
            // .. do something
        }
        // IE
        else {
            var cssRule = styleSheet.rules;
            // .. do something
        }
    }
}
</code>```

答:
native js assuming your link tag as the ID of 'css'</p>

```<code>document.querySelectorAll('link#css')[0].sheet;
</code>```

Body:
I have the following snippet that overwrites certain CSS properties:-

var styleSheet  = document.styleSheets[2]; // refers to the 3rd stylesheet

// Mozilla
if (styleSheet.cssRules) {
    var cssRule     = styleSheet.cssRules;

    // ... do something
}
// IE
else {
    var cssRule     = styleSheet.rules;

    // ... do something
}

This code works, but I don't like the fact that I'm referencing the stylesheet using document.styleSheets[2] because it is brittle. So, I assigned an id to the link tag, hoping that I can use JQuery to easily get that stylesheet by id. However, I'm not sure how to cast the returned object from JQuery into a CSSStyleSheet object so that I can assign it to styleSheet variable.

// I want to change this...
var styleSheet  = document.styleSheets[2]; // [object CSSStyleSheet]

// ... to something like this...
var styleSheet  = $("link#layout"); // not right because it is a [object Object]

Any clue? Thanks.

UPDATE

Per @TJ's suggestion, after futzing around, I think I might go with title instead of href... at least for now until I find any incompatibilities next time. Right now, this works in FF, IE, Safari and Chrome.

for (var i = 0; i < document.styleSheets.length; ++i) {
    var styleSheet  = document.styleSheets[i];

    if (document.styleSheets[i].title == "layout-overwrite") {
        // Mozilla
        if (styleSheet.cssRules) {
            var cssRule = styleSheet.cssRules;
            // .. do something
        }
        // IE
        else {
            var cssRule = styleSheet.rules;
            // .. do something
        }
    }
}

Body:
native js assuming your link tag as the ID of 'css'

document.querySelectorAll('link#css')[0].sheet;


问:
How to change Content-Type in Flurl?
I have a .NET Core 2.0 WebApi application in which I have added the "Flurl.Http" (Version 2.1.0) NuGet package to my project.

I am trying to use Flurl to make a simple REST API call to one of Visual Studio Team Services' (VSTS) Api endpoints.

However, the particular VSTS api endpoint that I am calling requires that the Content-Type be set to "application/json-patch+json" instead of the typical "application/json".

In my Flurl call, I am using the "WithHeader()" method to try and set the Content-Type in the header of the request, but it is not working. Flurl seems to not allow me to override the default or standard Content-Type that is built into the PostJsonAsync method.

Does anyone know how to change the Content-Type of the request using Flurl? Or how to properly override the default behavior of the Content-Type in the Flurl configuration?

Thanks in advance!

My code:

```<code>public bool CreateNewBug(NewBugRequest newBugRequest)
{
    return _apiUrlToCreateNewBug.WithHeader("Authorization", "Basic Base64PersonalAccessTokenGoesHere")
                                .WithHeader("Content-Type", "application/json-patch+json")
                                .PostJsonAsync(newBugRequest.Fields)
                                .Result
                                .IsSuccessStatusCode;
}
</code>```

(This code works, but the response from the VSTS api is that the Content-Type is not allowed and needs to be changed to "application/json-patch+json", which is what I tried to set it to in the header.)

答:
UPDATE: The bug is fixed as of Flurl.Http 2.3.1, so this work-around is no longer necessary.

The short answer is I think you've discovered a bug. PostJsonAsync does set the Content-Type header, but I think it should leave it alone if you've already set it yourself. If you could report it here I should be able to get it fixed for the next release.

The work-around is fairly straightforward. You just need to take a couple extra steps to build the content and then post it using PostAsync instead of PostJsonAsync.

```<code>var json = FlurlHttp.GlobalSettings.JsonSerializer.Serialize(newBugRequest.Fields);
var content = new CapturedStringContent(json, Encoding.UTF8, "application/json-patch+json");

return _apiUrlToCreateNewBug
    .WithHeader("Authorization", "Basic Base64PersonalAccessTokenGoesHere")
    .PostAsync(content);
</code>```

If you need to do this a lot, you could wrap it up in an extension method (PostJsonPatchAsync or similar) so you can call it fluently. See here for the correct way to do that.

Title: How to change Content-Type in Flurl?

Body:
I have a .NET Core 2.0 WebApi application in which I have added the "Flurl.Http" (Version 2.1.0) NuGet package to my project.

I am trying to use Flurl to make a simple REST API call to one of Visual Studio Team Services' (VSTS) Api endpoints.

However, the particular VSTS api endpoint that I am calling requires that the Content-Type be set to "application/json-patch+json" instead of the typical "application/json".

In my Flurl call, I am using the "WithHeader()" method to try and set the Content-Type in the header of the request, but it is not working. Flurl seems to not allow me to override the default or standard Content-Type that is built into the PostJsonAsync method.

Does anyone know how to change the Content-Type of the request using Flurl? Or how to properly override the default behavior of the Content-Type in the Flurl configuration?

Thanks in advance!

My code:

public bool CreateNewBug(NewBugRequest newBugRequest)
{
    return _apiUrlToCreateNewBug.WithHeader("Authorization", "Basic Base64PersonalAccessTokenGoesHere")
                                .WithHeader("Content-Type", "application/json-patch+json")
                                .PostJsonAsync(newBugRequest.Fields)
                                .Result
                                .IsSuccessStatusCode;
}

(This code works, but the response from the VSTS api is that the Content-Type is not allowed and needs to be changed to "application/json-patch+json", which is what I tried to set it to in the header.)

Body:
UPDATE: The bug is fixed as of Flurl.Http 2.3.1, so this work-around is no longer necessary.

The short answer is I think you've discovered a bug. PostJsonAsync does set the Content-Type header, but I think it should leave it alone if you've already set it yourself. If you could report it here I should be able to get it fixed for the next release.

The work-around is fairly straightforward. You just need to take a couple extra steps to build the content and then post it using PostAsync instead of PostJsonAsync.

var json = FlurlHttp.GlobalSettings.JsonSerializer.Serialize(newBugRequest.Fields);
var content = new CapturedStringContent(json, Encoding.UTF8, "application/json-patch+json");

return _apiUrlToCreateNewBug
    .WithHeader("Authorization", "Basic Base64PersonalAccessTokenGoesHere")
    .PostAsync(content);

If you need to do this a lot, you could wrap it up in an extension method (PostJsonPatchAsync or similar) so you can call it fluently. See here for the correct way to do that.


问:
Installing Java libraries
As I'm quite new to Java, I would like to know the proper procedure of installing new libraries (those that are no available in my linux dist repositories).
Where should I place them? and how to install them?
For instance, I downloaded openCsv (http://opencsv.sourceforge.net/), and I have no idea how to install it.</p>

答: It's up to you really - I use /opt/javalib, but you might consider a directory in /usr/local as well.

Title: Installing Java libraries