问:
Dependency injection for non controller classes and calling them
Trying to wrap my head around dependency injection, coming from the world of static classes and instantiated classes. Here is what I currently have:

```<code>[SomeFilter]
public class AController : Controller
{
    private readonly IOptions<AppSettings> _appSettings;

    public AController(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

// GET: /characters/
public IActionResult Index()
{
    //do something
}
</code>```

SomeFilter gets called immediately, and does this:

```<code>public class SomeFilter: ActionFilterAttribute, IActionFilter
{
     public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       OtherClass.RunMe();
    }
}
</code>```

OtherClass looks like this:

```<code>public class OtherClass
{
    private readonly IOptions<AppSettings> _appSettings;

    public OtherClass(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

public RunMe()
{
    //do something
}
</code>```

I also have OtherClass registered as a service.Singleton in the Startup.cs.

I get an error stating:

"An object reference is required for a non-static field"

for the OtherClass.RunMe(); call.

I was under the assumption that I can call this class from anywhere within my code instead of having to create a new instance of it? Essentially, how do I call methods from other classes using dependency injection?

答:
You can't constructor injection on filters. It's all about run time order. When you try injection on constructor, your IoC container not reachable at the moment. You should be use property/setter injection.

I prefer using structuremap container for to do this. Because structuremap has very easy to apply any type injection. For example when you have a filter registry like this

```<code> public class ActionFilterRegistry : Registry
    {
        public ActionFilterRegistry(Func<IContainer> containerFactory)
        {
            For<IFilterProvider>().Use(
                new StructureMapFilterProvider(containerFactory));

            Policies.SetAllProperties(x =>
                x.Matching(p =>
                    p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) &&
                    p.DeclaringType.Namespace.StartsWith("YourNameSpace") &&
                    !p.PropertyType.IsPrimitive &&
                    p.PropertyType != typeof(string)));
        }
    }
</code>```

And you register it on your global.asax(prefer) or one of your startup class.
Example app_Start method.

```<code>DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => Container ?? ObjectFactory.Container));
            ObjectFactory.Container.Configure(cfg =>
            {
                cfg.AddRegistry(new StandardRegistry());
                cfg.AddRegistry(new ControllerRegistry());
                cfg.AddRegistry(new ActionFilterRegistry(() => Container));
                cfg.AddRegistry(new MvcRegistry());
            });
</code>```

Then you can use any filter with injection. But pay attention you shouldn't be use contructor injection like you do.

ContentLicense: CC BY-SA 4.0

Body:
Trying to wrap my head around dependency injection, coming from the world of static classes and instantiated classes. Here is what I currently have:

[SomeFilter]
public class AController : Controller
{
    private readonly IOptions<AppSettings> _appSettings;

    public AController(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

// GET: /characters/
public IActionResult Index()
{
    //do something
}

SomeFilter gets called immediately, and does this:

public class SomeFilter: ActionFilterAttribute, IActionFilter
{
     public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       OtherClass.RunMe();
    }
}

OtherClass looks like this:

public class OtherClass
{
    private readonly IOptions<AppSettings> _appSettings;

    public OtherClass(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

public RunMe()
{
    //do something
}

I also have OtherClass registered as a service.Singleton in the Startup.cs.

I get an error stating:

"An object reference is required for a non-static field"

for the OtherClass.RunMe(); call.

I was under the assumption that I can call this class from anywhere within my code instead of having to create a new instance of it? Essentially, how do I call methods from other classes using dependency injection?

Body:
You can't constructor injection on filters. It's all about run time order. When you try injection on constructor, your IoC container not reachable at the moment. You should be use property/setter injection.

I prefer using structuremap container for to do this. Because structuremap has very easy to apply any type injection. For example when you have a filter registry like this

 public class ActionFilterRegistry : Registry
    {
        public ActionFilterRegistry(Func<IContainer> containerFactory)
        {
            For<IFilterProvider>().Use(
                new StructureMapFilterProvider(containerFactory));

            Policies.SetAllProperties(x =>
                x.Matching(p =>
                    p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) &&
                    p.DeclaringType.Namespace.StartsWith("YourNameSpace") &&
                    !p.PropertyType.IsPrimitive &&
                    p.PropertyType != typeof(string)));
        }
    }

And you register it on your global.asax(prefer) or one of your startup class.
Example app_Start method.

DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => Container ?? ObjectFactory.Container));
            ObjectFactory.Container.Configure(cfg =>
            {
                cfg.AddRegistry(new StandardRegistry());
                cfg.AddRegistry(new ControllerRegistry());
                cfg.AddRegistry(new ActionFilterRegistry(() => Container));
                cfg.AddRegistry(new MvcRegistry());
            });

Then you can use any filter with injection. But pay attention you shouldn't be use contructor injection like you do.


来源: stackexchange

问:
How can I remove every listener from a page?
I know how to remove a listener from an element, but how can I remove every event listener from every element on the page?

A jQuery and pure JS solution would be nice.

答:
You can loop through the form elements as below to remove the event listeners at your preferred way.

The fastest way to do this is to just clone the node which will remove all event listeners but this won't remove if 'onclick' attribute is used.

document.getElementById('button').addEventListener('click', onClick, false);

function onClick() {
   console.log('Form clicked');
   var form = document.getElementById('myForm');

   for(var i = 0; i < form.elements.length; i++){
       var elm = form.elements[i];
       removeEvents(elm);
   }
}

function removeEvents(elm) {
  // The fastest way to do this is to just clone the node, which will remove all event listeners:

   var new_element = elm.cloneNode(true);
   elm.parentNode.replaceChild(new_element, elm);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="myForm">
   <input id="button" type="button" value="Click" />
</form></code>```

ContentLicense: CC BY-SA 3.0

Body:
You can loop through the form elements as below to remove the event listeners at your preferred way.

The fastest way to do this is to just clone the node which will remove all event listeners but this won't remove if 'onclick' attribute is used.

document.getElementById('button').addEventListener('click', onClick, false);

function onClick() {
   console.log('Form clicked');
   var form = document.getElementById('myForm');

   for(var i = 0; i < form.elements.length; i++){
       var elm = form.elements[i];
       removeEvents(elm);
   }
}

function removeEvents(elm) {
  // The fastest way to do this is to just clone the node, which will remove all event listeners:

   var new_element = elm.cloneNode(true);
   elm.parentNode.replaceChild(new_element, elm);
}

<form id="myForm">
   <input id="button" type="button" value="Click" />
</form>


问:
How to get string from arraylist
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

```<code>public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}
</code>```

}

答:
You should declare Get and Set Method in your Product  Class

```<code> nowyEkran.putExtra("1st column value", mProductList.get(position).getProduct());
</code>```

Example

```<code>        /**
         * Created by Intellij Amiyo  on 03-04-2017.
         */

        public class Product implements Serializable {

        public String product,price,description;
        int id;

        // Empty constructor
        public Product()
        {

        }

        // constructor
        public Product( int id,String product,String price,String description) {

            this.price = price;
            this.product = product;
            this.description = description;
            this.id=id;

        }

          public String getprice() {
            return this.price;
        }

        public void setprice(String price) {
            this.price = price;
        }
         public String getProduct() {
            return this.product;
        }

        public void setProduct(String product) {
            this.product = product;
        }
         public String getDescription() {
            return this.description;
        }

        public void setDescription(String product) {
            this.description = description;
        }

        public int getID() {
            return this.id;
        }

        public void setID(int id) {
            this.id = id;
        }

}
</code>```

Title: How to get string from arraylist

Body:
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}

}

Body:
You should declare Get and Set Method in your Product  Class

 nowyEkran.putExtra("1st column value", mProductList.get(position).getProduct());

Example

        /**
         * Created by Intellij Amiyo  on 03-04-2017.
         */

        public class Product implements Serializable {

        public String product,price,description;
        int id;

        // Empty constructor
        public Product()
        {

        }

        // constructor
        public Product( int id,String product,String price,String description) {

            this.price = price;
            this.product = product;
            this.description = description;
            this.id=id;

        }

          public String getprice() {
            return this.price;
        }

        public void setprice(String price) {
            this.price = price;
        }
         public String getProduct() {
            return this.product;
        }

        public void setProduct(String product) {
            this.product = product;
        }
         public String getDescription() {
            return this.description;
        }

        public void setDescription(String product) {
            this.description = description;
        }

        public int getID() {
            return this.id;
        }

        public void setID(int id) {
            this.id = id;
        }

}


问:
wso2 identity server - sending email when user changed password
I am using WSO2 IS 5.3.0 server and I am wondering if it is possible to send an email when user changes his password or any other attribute, etc., email.? Is this feature already built in WSO2 IS (I couldn't find anything in WSDL services) or is it then possible to extend something?

Any comments about this issue would be appreciated.

答:
Please do the following steps to achieve this task.

Write a custom user operation event listener extending the AbstractUserOperationEventListener.java

Implement the doPostUpdateCredential method. doPostUpdateCredential

Trigger notification event handler to send a notification to the user. EventHandlerNotification


问:
unable to append option in multiple select
I have a multipleSelect, it is created dynamically using javascript and I am currently not able to append options in it.

Below is a Fiddle

Here is what I tried :

```<code>$(selectEventTypeAssetId).append($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html('<option value="1">234</option>');
$(selectEventTypeAssetId).append('<option value="1">234</option>');
$(selectEventTypeAssetId).text('<option value="1">234</option>');
</code>```

None of these seem to help.

Any help would be appreciated.

答:
Your issue is because you need to append the new option element before you instantiate the multipleSelect plugin on the element, like this:

```<code>var $selectEventTypeAssetId = $('<select id="eventTypeSelect" class="form-control" />').appendTo('.alertTypeMultipleSelect');
$selectEventTypeAssetId.append('<option value="1">234</option>');

$('.alertTypeMultipleSelect').multipleSelect({
  placeholder: "Event Type",
  selectAll: false,
  width: "100%",
  filter: true,
  sort: true,
});
</code>```

Updated fiddle

Body:
I have a multipleSelect, it is created dynamically using javascript and I am currently not able to append options in it.

Below is a Fiddle

Here is what I tried :

$(selectEventTypeAssetId).append($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html('<option value="1">234</option>');
$(selectEventTypeAssetId).append('<option value="1">234</option>');
$(selectEventTypeAssetId).text('<option value="1">234</option>');

None of these seem to help.

Any help would be appreciated.

Body:
Your issue is because you need to append the new option element before you instantiate the multipleSelect plugin on the element, like this:

var $selectEventTypeAssetId = $('<select id="eventTypeSelect" class="form-control" />').appendTo('.alertTypeMultipleSelect');
$selectEventTypeAssetId.append('<option value="1">234</option>');

$('.alertTypeMultipleSelect').multipleSelect({
  placeholder: "Event Type",
  selectAll: false,
  width: "100%",
  filter: true,
  sort: true,
});

Updated fiddle


问:
Custom CSS / meta tag for iPad/iPhone
I am working on a web app that uses Extjs components, PHP, and MySQL.
I want to correctly display my apps on iPad.  Are there special CSS rules or meta tags?</p>

答:
Your question is fairly vague. Here are some tips for developing a web application on iOS:

For fixed width sites, use a <meta> tag to tell mobile Safari what the width of your site should be, similar to:

<meta name = "viewport" content = "width = 320, initial-scale = 2.3, user-scalable = no">

You can get a list of other <meta> tags supported by mobile Safari here.

Mobile Safari adds new events to the JavaScript DOM in order to support touch and orientation change. Here is the Apple reference to them.

Here's a useful overview of how to make a web app suitable for use on iPad.

Finally, try a Google search.

Title: Custom CSS / meta tag for iPad/iPhone

ContentLicense: CC BY-SA 2.5


问:
Using Google OAuth 2 on embedded Android-based device
We have an application for embedded Android-based device, it uses WebView and inside it we use Google OAuth 2 to login to the app. Unfortunately Google will soon block OAuth 2 inside WebView, and we have lots of restrictions:

The device doesn't have Google Services installed, so probably no 'official' way of logging in would work (or maybe any of them would work without Google Services?)

We can't just invoke Android browser to do login, because it shows address bar, which would allow the user to surf the internet, which we can't allow

We don't fully control the software installed on the device: can't install Google Services, update Android version, install Google Chrome, etc..., we can just update our app.

What else could we do having those restrictions?

答:
As per the problems on your side it would be best to open an Intent from within the App targeted towards the sign in Weburl [this won't trigger up address bar link]

Refer to this stackOverflow page
how to open "Add a Google Account" activity using intent?

now you may use  Shared preferences  to store the Authentication data for further logins [ if the requirements of the app permits it.]

https://developer.android.com/reference/android/content/SharedPreferences.html


问:
NoReverseMatch in 'a href' HTML link
I'm trying to make a link that redirects to another page in my django application, I have the view, I have the url and I have the template, all are ok in my eyes, but when I try to 'href' the page to do the link I get the Following error:

Reverse for 'views.candidate_detail' with arguments '()' and keyword
  arguments '{'pk': ''}' not found. 0 pattern(s) tried: []

views.py

```<code>from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()
    evaluation = Evaluation.objects.all()

    ######################## Ponho todos os candidatos e suas respectivas médias em um array em formato dict({Candidato:N})
    sum = 0
    cont = 1
    med = 0
    lista = []
    for cand in candidates:
        cont = 0
        sum = 0
        med = 0
        for e in evaluation:
            if cand == e.candidate:
                sum += e.score
                cont += 1
        if cont > 0:
            med = sum / cont

        data = {str(cand):med}              ## a Key recebe o candidato no formato string
        lista += [data]

    ##### passo os dicionários contidos na lista anterior para outra lista convertendo-os em string
    lista2 = []
    for l in lista:
        lista2 += [str(l)]

    lista2 = [re.sub(r'[^\w\d.:]+',"",e) for e in lista2]

    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    context = {
        'candidates': candidates,
        'evaluation': evaluation,
        'lista2':lista2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)
</code>```

urls.py

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

urlpatterns = [
    url(r'^$', views.canditate_list, name='canditate_list'),
    url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidate_detail, name='candidate_detail'),
    url(r'^cadastrar/$', views.register, name='register'),  # <--! o cadastro fica num link independete
    url(r'^grid/$', views.grid, name='grid'),
    url(r'^candidato/[0-9]+/avaliacao/$', views.evaluation, name='evaluate'),

]
</code>```

template html:

```<code>{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
    <link href="{% static 'css/app.css' %}" rel="stylesheet">
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in lista2 %}
        <p class="tr"><a href="{% url 'views.candidate_detail' pk=post.pk %}">{{l}}</a></p>
    {% endfor %}

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

答:
Replace href to the following:

```<code>{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
    <link href="{% static 'css/app.css' %}" rel="stylesheet">
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in lista2 %}
        <p class="tr"><a href="{% url 'candidate_detail' post.pk %}">{{l}}</a></p>
    {% endfor %}

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

In Django, when referencing a view using url, you need to use the name attribute that you have defined for it in the urls.py

Screenshot from OP: file

Title: NoReverseMatch in 'a href' HTML link

Body:
I'm trying to make a link that redirects to another page in my django application, I have the view, I have the url and I have the template, all are ok in my eyes, but when I try to 'href' the page to do the link I get the Following error:

Reverse for 'views.candidate_detail' with arguments '()' and keyword
  arguments '{'pk': ''}' not found. 0 pattern(s) tried: []

views.py

from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()
    evaluation = Evaluation.objects.all()

    ######################## Ponho todos os candidatos e suas respectivas médias em um array em formato dict({Candidato:N})
    sum = 0
    cont = 1
    med = 0
    lista = []
    for cand in candidates:
        cont = 0
        sum = 0
        med = 0
        for e in evaluation:
            if cand == e.candidate:
                sum += e.score
                cont += 1
        if cont > 0:
            med = sum / cont

        data = {str(cand):med}              ## a Key recebe o candidato no formato string
        lista += [data]

    ##### passo os dicionários contidos na lista anterior para outra lista convertendo-os em string
    lista2 = []
    for l in lista:
        lista2 += [str(l)]

    lista2 = [re.sub(r'[^\w\d.:]+',"",e) for e in lista2]

    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    context = {
        'candidates': candidates,
        'evaluation': evaluation,
        'lista2':lista2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.canditate_list, name='canditate_list'),
    url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidate_detail, name='candidate_detail'),
    url(r'^cadastrar/$', views.register, name='register'),  # <--! o cadastro fica num link independete
    url(r'^grid/$', views.grid, name='grid'),
    url(r'^candidato/[0-9]+/avaliacao/$', views.evaluation, name='evaluate'),

]

template html:

{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>

    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
    <link href="{% static 'css/app.css' %}" rel="stylesheet">

Lista de Candidatos

    {% for l in lista2 %}

{{l}}

    {% endfor %}

Body:
Replace href to the following:

{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
    <link href="{% static 'css/app.css' %}" rel="stylesheet">
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in lista2 %}
        <p class="tr"><a href="{% url 'candidate_detail' post.pk %}">{{l}}</a></p>
    {% endfor %}

</body>
</html>

In Django, when referencing a view using url, you need to use the name attribute that you have defined for it in the urls.py

Screenshot from OP: file


问:
Load new a new component onKeyPress - reactjs
I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows.

```<code>    class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");

            }
        }

        render() {

            return (

                <div className="search_bar_div">

                    <div className="search_bar_internal_div">

                        {/* Search bar for desktop and tablets */}
                        <span className="Rev_logo">Revegator</span>

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

                    </div>

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

I get the console log correctly but the problem i have is how to load the component when i press Enter.

答:
for example, my index would look like this

```<code>ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path='/' component={App}>
        <IndexRoute component={Welcome} />
        <Route path='/signin' component={SignIn} />
        <Route path='/signout' component={SignOut} />
        <Route path='/register' component={SignUp} />
        <Route path='/map' component={Map} />
        <Route path='/dashboard' component={RequireAuth(Dashboard)} />
        <Route path='/admin' component={RequireAdmin(Admin)} />
        <Router path='*' component={Welcome} />
      </Route>
</Router>
</code>```

with my main App component (the top level Route under Router)

```<code>render() {
return (
  <div>
  <Header />
    {this.props.children}
  </div>
)
}
</code>```

this means that '/' is rendered from the App component, and any route declared after the '/' will be rendered INTO the app component, instead of it's own page.

Body:
I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows.

    class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");

            }
        }

        render() {

            return (

                        {/* Search bar for desktop and tablets */}
                        Revegator

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

}

I get the console log correctly but the problem i have is how to load the component when i press Enter.

Body:
for example, my index would look like this

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path='/' component={App}>
        <IndexRoute component={Welcome} />
        <Route path='/signin' component={SignIn} />
        <Route path='/signout' component={SignOut} />
        <Route path='/register' component={SignUp} />
        <Route path='/map' component={Map} />
        <Route path='/dashboard' component={RequireAuth(Dashboard)} />
        <Route path='/admin' component={RequireAdmin(Admin)} />
        <Router path='*' component={Welcome} />
      </Route>
</Router>

with my main App component (the top level Route under Router)

render() {
return (
  <div>
  <Header />
    {this.props.children}
  </div>
)
}

this means that '/' is rendered from the App component, and any route declared after the '/' will be rendered INTO the app component, instead of it's own page.


问:
Magento - get specific category name from product id
This is my code:

```<code>$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();

foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
     if ($category_id == 3 || 4 || 5 || 6 || 7 || 8) {
          echo $_cat->getName();
     }
}
</code>```

I want to display only one specific category(cat) name:

If the product (it is always just one which is displayed) is in a specific cat (the specific cat ids are: 3,4,5,6,7,8) it should display the cat name (but only the cat name of one of these ids).

Every product is in only one of these cats but it has more cats (child cats and default cat).

For Example: I have a product from cat 4. My code displays all cat names (default, cat 4 and the child cats), but i just want the name of cat 4. My if expression doesn't work. Has anybody an idea how to fix this?

答:
You can get Magento category name or category id of particular product by product id. You following code:</p>

```<code>    $_proId  = $this->getProduct()->getId();
    $product = Mage::getModel('catalog/product')->load($_proId);
    $cats = $product->getCategoryIds();

    foreach ($cats as $category_id) {
        $_cat = Mage::getModel('catalog/category')->load($category_id) ;
        $currentCategory = $_cat->getId();
    }
</code>```

Body:
This is my code:

$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();

foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
     if ($category_id == 3 || 4 || 5 || 6 || 7 || 8) {
          echo $_cat->getName();
     }
}

I want to display only one specific category(cat) name:

If the product (it is always just one which is displayed) is in a specific cat (the specific cat ids are: 3,4,5,6,7,8) it should display the cat name (but only the cat name of one of these ids).

Every product is in only one of these cats but it has more cats (child cats and default cat).

For Example: I have a product from cat 4. My code displays all cat names (default, cat 4 and the child cats), but i just want the name of cat 4. My if expression doesn't work. Has anybody an idea how to fix this?

Body:
You can get Magento category name or category id of particular product by product id. You following code:

    $_proId  = $this->getProduct()->getId();
    $product = Mage::getModel('catalog/product')->load($_proId);
    $cats = $product->getCategoryIds();

    foreach ($cats as $category_id) {
        $_cat = Mage::getModel('catalog/category')->load($category_id) ;
        $currentCategory = $_cat->getId();
    }


答:
Try this </p>

```<code>mProductList.get(position).getMethod()
</code>```

Title: How to get string from arraylist

Body:
Try this

mProductList.get(position).getMethod()


问:
Django POST data in request.body but can not store in variable
I am posting some raw JSON to my backend

```<code>{
    "access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",
    "id": 3,
    "order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]
}
</code>```

However when I try to

```<code>print (request.POST.get("access_token"))
</code>```

I receive None

But, when I do

```<code>print (request.body)
</code>```

The values seem to there:

b'{\n\t"access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",\n\t"id": 3,\n\t",\n\t"order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]\n}'

I am using Postman to post the data.

I want to store the access token into some variable like so:

```<code>access_token = request.POST.get("access_token")
</code>```

with the post data

I am still fairly new to Django, any help would be great.

答:
Just doing a json.loads should work.</p>

```<code>import json

json_data = json.loads(request.body)
</code>```

Body:
I am posting some raw JSON to my backend

{
    "access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",
    "id": 3,
    "order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]
}

However when I try to

print (request.POST.get("access_token"))

I receive None

But, when I do

print (request.body)

The values seem to there:

b'{\n\t"access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",\n\t"id": 3,\n\t",\n\t"order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]\n}'

I am using Postman to post the data.

I want to store the access token into some variable like so:

access_token = request.POST.get("access_token")

with the post data

I am still fairly new to Django, any help would be great.

Body:
Just doing a json.loads should work.

import json

json_data = json.loads(request.body)


答:
this will get the index 0 1 2 of your array list,it will return the object</p>

```<code>mProductList.get(0);
mProductList.get(1);
mProductList.get(2);
</code>```

Title: How to get string from arraylist

Body:
this will get the index 0 1 2 of your array list,it will return the object

mProductList.get(0);
mProductList.get(1);
mProductList.get(2);


答:
You need to get position reference first and then fetch the value of that position from ArrayList

```<code>mProductList.get(position).getProductName();
</code>```

Happy Coding!

Title: How to get string from arraylist

Body:
You need to get position reference first and then fetch the value of that position from ArrayList

mProductList.get(position).getProductName();

Happy Coding!


问:
mysql get student rank in exam
I have the following query.

```<code>SELECT
  SUM(
    marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
  ),
  FIND_IN_SET(
    SUM(
      marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
    ),
    (SELECT
      GROUP_CONCAT(summarks
        ORDER BY summarks DESC)
    FROM
      (SELECT
        SUM(
          marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
        ) AS summarks
      FROM
        results
      GROUP BY student_id) sm)
  ) AS rank
FROM
  results
WHERE student_id = ".$student_id."
  AND exam_year = ".$year."
  AND exam_id = ".$exam."
  AND results.class_id = ".$class_id."
  AND section_id = ".$section_id."
</code>```

This query works fine for me only when there in one exam in my result table.
When there are more exams,this query calculates marks for all exams and return rank to me. But In case I need student rank for only one exam, I need to put exam_id in the query and when I do that, the query returns 0 as student rank.

In above picture, I got 0th position which is invalid.But if i remove the exam_id condition,then I get the correct rank,but the problem is it sums marks for all entered exams which i dont want as I need rank for a specific exam.

So please anyone tell me where should I put the exam_id condition in my query.

答:
Try to put the exam_id in your sub query too.</p>

```<code>(SELECT
      GROUP_CONCAT(summarks
        ORDER BY summarks DESC)
    FROM
      (SELECT
        SUM(
          marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
        ) AS summarks
      FROM
        results WHERE exam_id = ?
      GROUP BY student_id
</code>```

Title: mysql get student rank in exam

Body:
I have the following query.

SELECT
  SUM(
    marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
  ),
  FIND_IN_SET(
    SUM(
      marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
    ),
    (SELECT
      GROUP_CONCAT(summarks
        ORDER BY summarks DESC)
    FROM
      (SELECT
        SUM(
          marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
        ) AS summarks
      FROM
        results
      GROUP BY student_id) sm)
  ) AS rank
FROM
  results
WHERE student_id = ".$student_id."
  AND exam_year = ".$year."
  AND exam_id = ".$exam."
  AND results.class_id = ".$class_id."
  AND section_id = ".$section_id."

This query works fine for me only when there in one exam in my result table.
When there are more exams,this query calculates marks for all exams and return rank to me. But In case I need student rank for only one exam, I need to put exam_id in the query and when I do that, the query returns 0 as student rank.

In above picture, I got 0th position which is invalid.But if i remove the exam_id condition,then I get the correct rank,but the problem is it sums marks for all entered exams which i dont want as I need rank for a specific exam.

So please anyone tell me where should I put the exam_id condition in my query.

Body:
Try to put the exam_id in your sub query too.

(SELECT
      GROUP_CONCAT(summarks
        ORDER BY summarks DESC)
    FROM
      (SELECT
        SUM(
          marks_obtained_written + marks_obtained_oral + marks_obtained_classwork
        ) AS summarks
      FROM
        results WHERE exam_id = ?
      GROUP BY student_id


问:
ElementName vs. RelativeResource?
What of the following TextBlocks' Bindings costs more performance:

```<code><Window
  x:Name="Me"
  x:Class="MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:WpfApplication1"
  Title="MainWindow">
  <StackPanel>
    <TextBlock Text="{Binding Title, ElementName=Me}"/>
    <TextBlock Text="{Binding Title, RelativeSource={RelativeSource AncestorType={x:Type src:MainWindow}}}"/>
  </StackPanel>
</Window>
</code>```

I am sure my question might take different when the TextBlocks are in a high nesting level having many siblings and ancestors.

Considerations

(based on personal thoughts only, I might be wrong in each particular one!):

ElementName:

Might search and compare current element to more control, thru all its children, siblings, uncles and great uncles including ancestors (maybe there is a HashTable of all the registered names?)

Getting a Name property of a control should cost less performance than calling GetType.

Comparing a string is cheaper than comparing types, especially when you know that most of the controls don't even have their Name set.

FindAncestor:

Will only iterate thru ancestors, not siblingls 'uncles', 'cousins' etc.

Most likely uses GetType to determine ancestor type; GetType costs more performance then a simple Name property getter (maybe DPs are different?)

答:
The later of the two needs to walk the visual tree looking for a particular ancestor type, where as the prior looks directly to the window's namescope for a registered object with that name...my guess would be the later is marginally slower...that said, I don't think there will be a significant performance difference.

Hope it helps,

Aj

Title: ElementName vs. RelativeResource?

Body:
What of the following TextBlocks' Bindings costs more performance:

<Window
  x:Name="Me"
  x:Class="MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:WpfApplication1"
  Title="MainWindow">
  <StackPanel>
    <TextBlock Text="{Binding Title, ElementName=Me}"/>
    <TextBlock Text="{Binding Title, RelativeSource={RelativeSource AncestorType={x:Type src:MainWindow}}}"/>
  </StackPanel>
</Window>

I am sure my question might take different when the TextBlocks are in a high nesting level having many siblings and ancestors.

Considerations

(based on personal thoughts only, I might be wrong in each particular one!):

ElementName:

Might search and compare current element to more control, thru all its children, siblings, uncles and great uncles including ancestors (maybe there is a HashTable of all the registered names?)

Getting a Name property of a control should cost less performance than calling GetType.

Comparing a string is cheaper than comparing types, especially when you know that most of the controls don't even have their Name set.

FindAncestor:

Will only iterate thru ancestors, not siblingls 'uncles', 'cousins' etc.

Most likely uses GetType to determine ancestor type; GetType costs more performance then a simple Name property getter (maybe DPs are different?)


问:
In VSTS, how do I add an email notification task to the build and release definitions?
I am new to VSTS Continuous Integration and configuring one of my first sets of build and release definitions.

Is there a task I can add that will allow me to notify certain team members of events such as a build failed, or a release is ready?

答:
In the latest iteration of the notification settings https://account.visualstudio.com/_notifications (where there is a single global settings page), if (like me) you don't run everything full screen:

Check the add button isn't off the side of the screen!


答:
Put position in your Braces (). like below...

```<code>lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(position));
            newActivity.putExtra("2nd column value", mProductList.get(position));
            newActivity.putExtra("3rd column value", mProductList.get(position));
            newActivity.putExtra("4th column value", mProductList.get(position));
            startActivity(newActivity);
        }
    });
</code>```

Hope this will help you...(:

Title: How to get string from arraylist

Body:
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}

}

Body:
Put position in your Braces (). like below...

lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(position));
            newActivity.putExtra("2nd column value", mProductList.get(position));
            newActivity.putExtra("3rd column value", mProductList.get(position));
            newActivity.putExtra("4th column value", mProductList.get(position));
            startActivity(newActivity);
        }
    });

Hope this will help you...(:


问:
Tizen wearable web application stops running after sometime in Samsung Gear S3
I have installed a Tizen web application in Samsung Gear S3. The application uses sensors and collects the heart rate, pedometer, accelerometer data etc., I want the application to run all the time. But some how, the application is terminated after sometime.

Every 10 minutes in the day time (say 8am to 8pm), user gets a notification to give an input in the application and the application restarts when the user clicks on the link to the application.

This implies, every 10 minutes, the application restarts. Even between those 10 minutes, the application gets terminated. I don't know why.

I tried using CPU_AWAKE to not let the watch go into sleep mode with the following command.

tizen.power.request("CPU", "CPU_AWAKE");

I have also enabled the background support in config.xml file.

The application used to work fine in Samsung Gear S2, I am not able to understand why it gets stopped in S3.

Please let me know if anyone knows the reason and how to fix it.

Thanks.

答:
Tizen Platform is trying to optimize background processes to boost up performance, that's what this release note indicates :

Tizen Release Notes

(Cnrl+F, Search for 'background')

Though it's not specifically stated in the case of 2.3.2 (Gear S3 default), but I guess that could be the case as it is not in previous versions (with the Gear S2). But their exists some procedures. Why don't you give Web Services or Web workers a try, And there is also the opportunity of using Native background service with existing Web UI

Tizen Web Service Application

Web Workers in Tizen

 Tizen Native Service Applications , Tizen Hybrid Service Sample Overview

(Chose which one suits your requirements and your expertise).


问:
Move files with only ".hex" extensions in Python 3
I want to move files with only ".hex" extensions in source path. I wrote the codes like below;

```<code>os.makedirs(dst)
src = "C:\\source_path"
dst = "C:\\destination_path"

for filename in os.listdir():
    if filename.endswith('.hex'):
        shutil.move(src, dst , copy_function = copy2)
</code>```

The file was created but empty.

答:
you need to move the file, not the folder. (use os.path.join(src,filename))

you are not going over the src dir. (use os.listdir(src))

Try something like this:

```<code>os.makedirs(dst)
src = "C:\\source_path"
dst = "C:\\destination_path"

for filename in os.listdir(src):
    if filename.endswith('.hex'):
        shutil.move(os.path.join(src,filename), dst)
</code>```

Body:
I want to move files with only ".hex" extensions in source path. I wrote the codes like below;

os.makedirs(dst)
src = "C:\\source_path"
dst = "C:\\destination_path"

for filename in os.listdir():
    if filename.endswith('.hex'):
        shutil.move(src, dst , copy_function = copy2)

The file was created but empty.

Body:
you need to move the file, not the folder. (use os.path.join(src,filename))

you are not going over the src dir. (use os.listdir(src))

Try something like this:

os.makedirs(dst)
src = "C:\\source_path"
dst = "C:\\destination_path"

for filename in os.listdir(src):
    if filename.endswith('.hex'):
        shutil.move(os.path.join(src,filename), dst)


Title: How to get string from arraylist

Body: mProductList.get(position).price


问:
mp4 files / SSTS info
I am trying to find the fastest way to get a list of all I-frames in a movie.

So far, I tried ffprobe, but it is quite slow and I have been looking for a faster solution.

The other option I found is using the mp4parser tool; it outputs a file with this sectio, the SSTS info:

```<code>-------------------------------------------------------------------------
/moov/trak/mdia/minf/stbl/stss                              @ 0x1c152d8
  Box size: 0x44    version: 0x0    flags: 0x0
  entry_count:              0xd
    sample_number:
     0x1    0x12d    0x259    0x385    ....
</code>```

I can see that I have 13 I frames and they're spaced 300 frames apart (from the 4 values displayed)

Is the spacing of I frames constant through movies? or do I need to write my own SSTS parser to get the whole list?

答:
The command below will quickly provide the timestamp for video keyframes along with other info.

```<code>ffmpeg -skip_frame nokey -i in.mp4 -an -vf showinfo -f null -
</code>```

Output looks like

```<code>[Parsed_showinfo_0 @ 00000000032903a0] n:  55 pts:5748224 pts_time:449.08  pos: 17288779 fmt:yuv420p sar:1/1 s:960x720 i:P iskey:1 type:I checksum:361866A6 plane_checksum:[BA2DCCBF A8E937B3 BD006225] mean:[220 117 133] stdev:[57.8 4.1 5.3]
</code>```

The pts_time gets you the time index. The n is not accurate for absolute frame index, but it is an accurate count for keyframe index i.e. n: 55 is the 56th keyframe in the video.

Title: mp4 files / SSTS info

Body:
I am trying to find the fastest way to get a list of all I-frames in a movie.

So far, I tried ffprobe, but it is quite slow and I have been looking for a faster solution.

The other option I found is using the mp4parser tool; it outputs a file with this sectio, the SSTS info:

-------------------------------------------------------------------------
/moov/trak/mdia/minf/stbl/stss                              @ 0x1c152d8
  Box size: 0x44    version: 0x0    flags: 0x0
  entry_count:              0xd
    sample_number:
     0x1    0x12d    0x259    0x385    ....

I can see that I have 13 I frames and they're spaced 300 frames apart (from the 4 values displayed)

Is the spacing of I frames constant through movies? or do I need to write my own SSTS parser to get the whole list?

Body:
The command below will quickly provide the timestamp for video keyframes along with other info.

ffmpeg -skip_frame nokey -i in.mp4 -an -vf showinfo -f null -

Output looks like

[Parsed_showinfo_0 @ 00000000032903a0] n:  55 pts:5748224 pts_time:449.08  pos: 17288779 fmt:yuv420p sar:1/1 s:960x720 i:P iskey:1 type:I checksum:361866A6 plane_checksum:[BA2DCCBF A8E937B3 BD006225] mean:[220 117 133] stdev:[57.8 4.1 5.3]

The pts_time gets you the time index. The n is not accurate for absolute frame index, but it is an accurate count for keyframe index i.e. n: 55 is the 56th keyframe in the video.


问:
How to use groupby/Lambda
```<code>public class Emp {

    public String name;
    public String department;
    public double salary;

    public Emp(String name, String department, double salary) {

        this.name = name;
        this.department = department;
        this.salary = salary;
    }
}
</code>```

So I am trying to get top 5 departments by summing salaries and

Also trying to top 5 employees in a department say sales

How do I use groupBy in java 8 and then summing and sorting

This is the data I have

Emp("Michael", "Sales",20000.0)
 Emp("Jean","Marketing",250000.0)
 Emp("Jason","Biz-dev",220000.0)
 ..........

答:
I thought about putting directly into a Map that supports order by values. Such a thing does not exist in jdk, but does in guava for example. So your solution could look like this:

```<code> Map<String, Double> map = employees.stream().collect(
            Collectors.collectingAndThen(Collectors.groupingBy(Emp::getDepartment,
                    Collectors.summingDouble(Emp::getSalary)),
                    x -> ImmutableMap.<String, Double> builder()
                            .putAll(x)
                            .orderEntriesByValue(Comparator.comparing((Double d) -> d).reversed())
                            .build()));

    map.entrySet().stream().map(Map.Entry::getValue).limit(5).forEach(System.out::println);
</code>```

This is not better then the solution already provided, it's just something that could be done like this.

Title: How to use groupby/Lambda

Body:
public class Emp {

    public String name;
    public String department;
    public double salary;

    public Emp(String name, String department, double salary) {

        this.name = name;
        this.department = department;
        this.salary = salary;
    }
}

So I am trying to get top 5 departments by summing salaries and

Also trying to top 5 employees in a department say sales

How do I use groupBy in java 8 and then summing and sorting

This is the data I have

Emp("Michael", "Sales",20000.0)
 Emp("Jean","Marketing",250000.0)
 Emp("Jason","Biz-dev",220000.0)
 ..........

Body:
I thought about putting directly into a Map that supports order by values. Such a thing does not exist in jdk, but does in guava for example. So your solution could look like this:

 Map<String, Double> map = employees.stream().collect(
            Collectors.collectingAndThen(Collectors.groupingBy(Emp::getDepartment,
                    Collectors.summingDouble(Emp::getSalary)),
                    x -> ImmutableMap.<String, Double> builder()
                            .putAll(x)
                            .orderEntriesByValue(Comparator.comparing((Double d) -> d).reversed())
                            .build()));

    map.entrySet().stream().map(Map.Entry::getValue).limit(5).forEach(System.out::println);

This is not better then the solution already provided, it's just something that could be done like this.


问:
C++ Aborted (Core Dumped) when returning a vector from a function
I'm trying to return a vector from a function. My code compiles and I've checked my function and reckon that the error comes from the return part. It compiles fine (using Cygwin) but when running it, I get an Aborted (core dumped) error.
Here is my code:

```<code>#include <iostream>
#include <vector>
#include <string>
using namespace std;

//function that returns the square
int f(int n)
{
    return n*n;
}
vector<int> myVec;
int counter = 0;
//function that uses f on all elements in a list
vector<int> map(vector<int> something)
{
    //base case
    if(counter == something.size())
    {
        /*cout << "hello" << endl;
        for (int i=0; i<counter; i++)
        {
            cout << "vector: " << myVec[i] << endl;
        }*/
        counter=0;
        return myVec;
    }
    //recursion
    else
    {
        //cout << "counter: " << counter << endl;
        int n = f(something[counter]);
        //cout << "n: " << n << endl;
        myVec.push_back(n);
        //cout << "vector: " << myVec[counter] << endl;
        counter++;
        map(something);
    }
}

int main()
{
    //making vectors
    vector<int> L;
    vector<int> L1;
    vector<int> L2;
    for (int i=0; i<20; i++)
    {
        L.push_back(i);
    }
    L1 = map(L);
}
</code>```

The code was originally from a class file.

答:
ALWAYS return a vector when your return type is a vector. In your function, there's a branch that won't return anything, and that will cause problems.

```<code>vector<int> map(vector<int>& something)
{
    //base case
    if(counter == something.size())
    {
        /*cout << "hello" << endl;
        for (int i=0; i<counter; i++)
        {
            cout << "vector: " << myVec[i] << endl;
        }*/
        counter=0;
        return myVec;
    }
    //recursion
    else
    {
        //cout << "counter: " << counter << endl;
        int n = f(something[counter]);
        //cout << "n: " << n << endl;
        myVec.push_back(n);
        //cout << "vector: " << myVec[counter] << endl;
        counter++;
        map(something); //you should return a vector here
        return std::vector<int>(); //empty vector
    }
}
</code>```

Also notice the "&" symbol I added at the function call so that the vector is passed by reference. Otherwise you're passing a copy that won't be changed. I don't know what that "map" function does, so I can't suggest better models to what you're doing.

Body:
I'm trying to return a vector from a function. My code compiles and I've checked my function and reckon that the error comes from the return part. It compiles fine (using Cygwin) but when running it, I get an Aborted (core dumped) error.
Here is my code:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

//function that returns the square
int f(int n)
{
    return n*n;
}
vector<int> myVec;
int counter = 0;
//function that uses f on all elements in a list
vector<int> map(vector<int> something)
{
    //base case
    if(counter == something.size())
    {
        /*cout << "hello" << endl;
        for (int i=0; i<counter; i++)
        {
            cout << "vector: " << myVec[i] << endl;
        }*/
        counter=0;
        return myVec;
    }
    //recursion
    else
    {
        //cout << "counter: " << counter << endl;
        int n = f(something[counter]);
        //cout << "n: " << n << endl;
        myVec.push_back(n);
        //cout << "vector: " << myVec[counter] << endl;
        counter++;
        map(something);
    }
}

int main()
{
    //making vectors
    vector<int> L;
    vector<int> L1;
    vector<int> L2;
    for (int i=0; i<20; i++)
    {
        L.push_back(i);
    }
    L1 = map(L);
}

The code was originally from a class file.

Body:
ALWAYS return a vector when your return type is a vector. In your function, there's a branch that won't return anything, and that will cause problems.

vector<int> map(vector<int>& something)
{
    //base case
    if(counter == something.size())
    {
        /*cout << "hello" << endl;
        for (int i=0; i<counter; i++)
        {
            cout << "vector: " << myVec[i] << endl;
        }*/
        counter=0;
        return myVec;
    }
    //recursion
    else
    {
        //cout << "counter: " << counter << endl;
        int n = f(something[counter]);
        //cout << "n: " << n << endl;
        myVec.push_back(n);
        //cout << "vector: " << myVec[counter] << endl;
        counter++;
        map(something); //you should return a vector here
        return std::vector<int>(); //empty vector
    }
}

Also notice the "&" symbol I added at the function call so that the vector is passed by reference. Otherwise you're passing a copy that won't be changed. I don't know what that "map" function does, so I can't suggest better models to what you're doing.


问:
node-request ip addres different from remote ip address
I have a app that uses node and request. It was working well until today, I dont know why but it stoped to work. I'm trying to do a simple request.get() to a specific page and it is sending me a timed out error, but the address the lib tried to access is different from remote adddress. It seems that node-request is not converting the url to proper ip for some reason.

request call:

```<code>request.get({
    url: 'http://www.website.to.request.com:8000/login.aspx',
    headers: headers,
}
</code>```

Node error message:

```<code>address:"200.200.00.00"
code:"ETIMEDOUT"
 errno:"ETIMEDOUT"
message:"connect ETIMEDOUT 200.200.00.00:8000"
port:8000
stack:"Error: connect ETIMEDOUT 200.200.00.00:8000
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)" syscall:"connect"
</code>```

request in chrome debug:

```<code>Request URL:http://www.website.to.request.com:8000/login.aspx
Request Method:GET
Status Code:200 OK
Remote Address:201.11.11.111:8000
Referrer Policy:no-referrer-when-downgrade
</code>```

Note: If I try to access: 201.11.11.111:8000/login.aspx it works, but with 200.200.00.00:8000 not works.

if i try to get the page content using https://www.hurl.it/ and passing the url and content-type works too;

Someone has any idea what this request is wrong??

答:
You can try to hardcode a DNS request, before the requestjs call, and then you can set the request url with the ip you got back.

This is the api you can use to execute the DNS lookup:
https://nodejs.org/api/dns.html

Remember that you can use dns.setServers to hardcode some dns servers (['8.8.8.8', '8.8.4.4'] for google DNS)

Body:
I have a app that uses node and request. It was working well until today, I dont know why but it stoped to work. I'm trying to do a simple request.get() to a specific page and it is sending me a timed out error, but the address the lib tried to access is different from remote adddress. It seems that node-request is not converting the url to proper ip for some reason.

request call:

request.get({
    url: 'http://www.website.to.request.com:8000/login.aspx',
    headers: headers,
}

Node error message:

address:"200.200.00.00"
code:"ETIMEDOUT"
 errno:"ETIMEDOUT"
message:"connect ETIMEDOUT 200.200.00.00:8000"
port:8000
stack:"Error: connect ETIMEDOUT 200.200.00.00:8000
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)" syscall:"connect"

request in chrome debug:

Request URL:http://www.website.to.request.com:8000/login.aspx
Request Method:GET
Status Code:200 OK
Remote Address:201.11.11.111:8000
Referrer Policy:no-referrer-when-downgrade

Note: If I try to access: 201.11.11.111:8000/login.aspx it works, but with 200.200.00.00:8000 not works.

if i try to get the page content using https://www.hurl.it/ and passing the url and content-type works too;

Someone has any idea what this request is wrong??


答:
```<code>var newOption = new Option(key, value, true, false);
$("#selectEventTypeAssetId").append(newOption).trigger('change');
</code>```

Title: unable to append option in multiple select

Body:
I have a multipleSelect, it is created dynamically using javascript and I am currently not able to append options in it.

Below is a Fiddle

Here is what I tried :

$(selectEventTypeAssetId).append($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html('<option value="1">234</option>');
$(selectEventTypeAssetId).append('<option value="1">234</option>');
$(selectEventTypeAssetId).text('<option value="1">234</option>');

None of these seem to help.

Any help would be appreciated.


问:
Diagonal match in Connect 4
Hey guys I'm developing a Connect 4 game in Windows form application in C# everything works perfectly I'm just stuck in the diagonal part. This is what I've developed for the left down diagonal check but I'm not sure if it works perfectly. It's working from the first tile which is (1,1) but I can't tell about the other tiles. I also wanted to know how to create another method for the other side diagonal match. (gameButtons is my 2D array and my form is 6 rows and 7 columns) This is my method:

```<code>private void checkForDiaMatch()
    {
        int countBlue = 0;
        int countRed = 0;

        for (int i = 0; i < 6; i++)
        {
            if (gameButtons[i, i].BackColor == Color.Blue)
            {
                countBlue++;
            }
            else
            {
                countBlue = 0;
            }
            if (gameButtons[i, i].BackColor == Color.Red)
            {
                countRed++;
            }
            else
            {
                countRed = 0;
            }

            if (countBlue >= 4)
            {
                MessageBox.Show("There is a blue diagonal match");
                MessageBox.Show("Blue wins!");
            }
            else if (countRed >= 4)
            {
                MessageBox.Show("There is a red diagonal match");
                MessageBox.Show("Red wins!");
            }

        }
    }
</code>```

Edit: So since I took some help from the comment section I created this but it's still not working. I tried going for the diagonal right match but no luck yet.

```<code>private void checkForDiaMatch(int col,int targetRow)
    {
        int countBlue = 0;
        int countRed = 0;
        int xLocation = gameButtons[col, targetRow].Location.X/50;
        int yLocation = gameButtons[col, targetRow].Location.Y/50;
        //string epop = Convert.ToString(xLocation);
        //MessageBox.Show(epop);

        if (7 > xLocation + 1 && 6 > yLocation + 1)
        {
            if (gameButtons[xLocation + 1, yLocation + 1].BackColor == Color.Blue)
            {
                countBlue++;
                string kappaBlue = Convert.ToString(countBlue);
                MessageBox.Show(kappaBlue);
            }
            else
            {
                countBlue = 0;
            }
            if (gameButtons[xLocation + 1, yLocation + 1].BackColor == Color.Red)
            {
                countRed++;
                string kappaRed = Convert.ToString(countRed);
                MessageBox.Show(kappaRed);
            }
            else
            {
                countRed = 0;
            }
</code>```

答:
Probably the most helpful thing would be to draw your board and indexes on paper, and write the indexes of any random diagonal connect 4:

```<code>-------------------------------            -------------------------------
5 |   |   |   |   |   |   |5,6|            5 |   |   |   |   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
4 |   |   |   |   |   |4,5|   |            4 |   |4,1|   |   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
3 |   |   |   |   |3,4|   |   |            3 |   |   |3,2|   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
2 |   |   |   |2,3|   |   |   |            2 |   |   |   |2,3|   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
1 |   |   |   |   |   |   |   |            1 |   |   |   |   |1,4|   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
0 |   |   |   |   |   |   |   |            0 |   |   |   |   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 |              | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
</code>```

We can see that from any point we need to check in two directions: up/right + down/left (like a /), and up/left + down/right (like a \). We want to count in both these directions the number of same-colored pieces as the one that we started from. As soon as the total number is 4, we can return true. If neither directions has a total of 4 matching pieces, we return false.

I played with this a little, and came up with the following method that works for me. Your classes are probably slightly different (I just did a console app), but hopefully the logic will help:

```<code>private bool CompletesDiagonal(int pieceRow, int pieceCol)
{
    var colorToMatch = Board[pieceRow, pieceCol]; // Board is a ConsoleColor[7,6] array

    var matchingPieces = 1; // We will count the original piece as a match

    // Check forward slash direction '/'

    // First check down/left (decrement both row and column up to 3 times)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow - counter;
        var col = pieceCol - counter;

        // Make sure we stay within our board
        if (row < Board.GetLowerBound(0) || col < Board.GetLowerBound(1)) { break; }

        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // Next check up/right (increment both row and column up to 3 times)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow + counter;
        var col = pieceCol + counter;

        // Make sure we stay within our board
        if (row > Board.GetUpperBound(0) || col > Board.GetUpperBound(1)) { break; }

        // Check for a match
        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // If we got this far, no match was found in forward slash direction,
    // so reset our counter and check the back slash direction '\'
    matchingPieces = 1;

    // First check down/right (decrement row and increment column)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow - counter;
        var col = pieceCol + counter;

        // Make sure we stay within our board
        if (row < Board.GetLowerBound(0) || col > Board.GetUpperBound(1)) { break; }

        // Check for a match
        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // Next check up/left (increment row and decrement column)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow + counter;
        var col = pieceCol - counter;

        // Make sure we stay within our board
        if (row > Board.GetUpperBound(0) || col < Board.GetLowerBound(1)) { break; }

        // Check for a match
        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // If we've gotten this far, then we haven't found a match
    return false;
}
</code>```

Here's the result of a diagonal win:

Title: Diagonal match in Connect 4

Body:
Hey guys I'm developing a Connect 4 game in Windows form application in C# everything works perfectly I'm just stuck in the diagonal part. This is what I've developed for the left down diagonal check but I'm not sure if it works perfectly. It's working from the first tile which is (1,1) but I can't tell about the other tiles. I also wanted to know how to create another method for the other side diagonal match. (gameButtons is my 2D array and my form is 6 rows and 7 columns) This is my method:

private void checkForDiaMatch()
    {
        int countBlue = 0;
        int countRed = 0;

        for (int i = 0; i < 6; i++)
        {
            if (gameButtons[i, i].BackColor == Color.Blue)
            {
                countBlue++;
            }
            else
            {
                countBlue = 0;
            }
            if (gameButtons[i, i].BackColor == Color.Red)
            {
                countRed++;
            }
            else
            {
                countRed = 0;
            }

            if (countBlue >= 4)
            {
                MessageBox.Show("There is a blue diagonal match");
                MessageBox.Show("Blue wins!");
            }
            else if (countRed >= 4)
            {
                MessageBox.Show("There is a red diagonal match");
                MessageBox.Show("Red wins!");
            }

        }
    }

Edit: So since I took some help from the comment section I created this but it's still not working. I tried going for the diagonal right match but no luck yet.

private void checkForDiaMatch(int col,int targetRow)
    {
        int countBlue = 0;
        int countRed = 0;
        int xLocation = gameButtons[col, targetRow].Location.X/50;
        int yLocation = gameButtons[col, targetRow].Location.Y/50;
        //string epop = Convert.ToString(xLocation);
        //MessageBox.Show(epop);

        if (7 > xLocation + 1 && 6 > yLocation + 1)
        {
            if (gameButtons[xLocation + 1, yLocation + 1].BackColor == Color.Blue)
            {
                countBlue++;
                string kappaBlue = Convert.ToString(countBlue);
                MessageBox.Show(kappaBlue);
            }
            else
            {
                countBlue = 0;
            }
            if (gameButtons[xLocation + 1, yLocation + 1].BackColor == Color.Red)
            {
                countRed++;
                string kappaRed = Convert.ToString(countRed);
                MessageBox.Show(kappaRed);
            }
            else
            {
                countRed = 0;
            }

Body:
Probably the most helpful thing would be to draw your board and indexes on paper, and write the indexes of any random diagonal connect 4:

-------------------------------            -------------------------------
5 |   |   |   |   |   |   |5,6|            5 |   |   |   |   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
4 |   |   |   |   |   |4,5|   |            4 |   |4,1|   |   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
3 |   |   |   |   |3,4|   |   |            3 |   |   |3,2|   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
2 |   |   |   |2,3|   |   |   |            2 |   |   |   |2,3|   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
1 |   |   |   |   |   |   |   |            1 |   |   |   |   |1,4|   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
0 |   |   |   |   |   |   |   |            0 |   |   |   |   |   |   |   |
--+---+---+---+---+---+---+---+            --+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 |              | 0 | 1 | 2 | 3 | 4 | 5 | 6 |

We can see that from any point we need to check in two directions: up/right + down/left (like a /), and up/left + down/right (like a \). We want to count in both these directions the number of same-colored pieces as the one that we started from. As soon as the total number is 4, we can return true. If neither directions has a total of 4 matching pieces, we return false.

I played with this a little, and came up with the following method that works for me. Your classes are probably slightly different (I just did a console app), but hopefully the logic will help:

private bool CompletesDiagonal(int pieceRow, int pieceCol)
{
    var colorToMatch = Board[pieceRow, pieceCol]; // Board is a ConsoleColor[7,6] array

    var matchingPieces = 1; // We will count the original piece as a match

    // Check forward slash direction '/'

    // First check down/left (decrement both row and column up to 3 times)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow - counter;
        var col = pieceCol - counter;

        // Make sure we stay within our board
        if (row < Board.GetLowerBound(0) || col < Board.GetLowerBound(1)) { break; }

        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // Next check up/right (increment both row and column up to 3 times)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow + counter;
        var col = pieceCol + counter;

        // Make sure we stay within our board
        if (row > Board.GetUpperBound(0) || col > Board.GetUpperBound(1)) { break; }

        // Check for a match
        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // If we got this far, no match was found in forward slash direction,
    // so reset our counter and check the back slash direction '\'
    matchingPieces = 1;

    // First check down/right (decrement row and increment column)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow - counter;
        var col = pieceCol + counter;

        // Make sure we stay within our board
        if (row < Board.GetLowerBound(0) || col > Board.GetUpperBound(1)) { break; }

        // Check for a match
        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // Next check up/left (increment row and decrement column)
    for (int counter = 1; counter < 4; counter++)
    {
        var row = pieceRow + counter;
        var col = pieceCol - counter;

        // Make sure we stay within our board
        if (row > Board.GetUpperBound(0) || col < Board.GetLowerBound(1)) { break; }

        // Check for a match
        if (Board[row, col] == colorToMatch)
        {
            matchingPieces++;
            if (matchingPieces == 4) return true;
        }
        else { break; }
    }

    // If we've gotten this far, then we haven't found a match
    return false;
}

Here's the result of a diagonal win:


问:
First few microsoft translator API requests succeed , then the calls fails and throws NoArgument exception with invalid appid
I am using Microsoft translator api, i have registered my app to datamarket and got the clientid and clientsecret. My api request succeed for few times . Now i am getting noArgument exceptio  with

NoArgumentException: Invalid appId
Parameter name: appId : ID=1116.V2_Json.Translate.4EEF7E6A - Row_IDArgumentException: Invalid appId

Please let me know in case i have missed something.

答:
It seems that you used a java library microsoft-translator-java-api wrappered an old MS Translator API which comes from https://datamarket.azure.com/dataset/bing/microsofttranslator. As @kwill said and the information from the old website, as below.

THE MICROSOFT TRANSLATOR API IS NOW AVAILABLE ON THE AZURE PORTAL

You can follow the first link of @kwill post to know how to use the new API, or refer to my answer for an existing SO thread MS Translator returns empty response when used with Azure token using the new MS translator API on Azure to try it, but you need to have an Azure subscription to create a Translator Text API service like below.


问:
Build failed with error Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
I am using Xcode 8.2.1. I am also using CoreData in my project.
When I try to generate a build or when I archive I am seeing the following error. Files mentioned in the error also changes at times.

ERROR:

```<code><unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/StateRegionMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataProperties.swift'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

Here is how my CoreData Entities are configured:

Things I have Tried:

Check the location to see if files are actually missing, Files where present exactly at the same path.

I cleaned the build folder and removed derived data and build it again. Nothing helped.

Tried all the answers in this link. Nothing Worked.

Accepted Answer of this question doesn't seem to work either.

I am not sure why this error is coming. Any help is appreciated

EDIT

If I completely remove CoreData from my code then it Archives Successfully.

EDIT 2 :

When I change CodeGen to Manual/None and add files manually as suggested by @Anil . It builds successfully, But when I try to fetch the CoreData entity using :

```<code>let context = appDelegate.persistentContainer.viewContext
let buildingRoofMapping = BuildingRoofMapping(context:context)
</code>```

It gives me run time error.
Error :

```<code>'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'BuildingRoofMapping' must have a valid NSEntityDescription.'
</code>```

EDIT 3:
   Sample Code link. Run it in simulator. It crashes in fetchBasicPrice() of ViewController.swift file

答:
I'll tell you what I have faced the same issue. In my case from Xcode 8 CoreData creates NSManagedObject class files in documents directory. I am sure you must have also created the same NSManagedObject files by your own.

You need to do following changes .xcdatamodel and regenerate a build. I have attached image below.

Make a change in Module and set it to Current Product Module and change the Codegen to Manual/None.

Let me know if you have more questions.

Body:
I am using Xcode 8.2.1. I am also using CoreData in my project.
When I try to generate a build or when I archive I am seeing the following error. Files mentioned in the error also changes at times.

ERROR:

<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/StateRegionMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataProperties.swift'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Here is how my CoreData Entities are configured:

Things I have Tried:

Check the location to see if files are actually missing, Files where present exactly at the same path.

I cleaned the build folder and removed derived data and build it again. Nothing helped.

Tried all the answers in this link. Nothing Worked.

Accepted Answer of this question doesn't seem to work either.

I am not sure why this error is coming. Any help is appreciated

EDIT

If I completely remove CoreData from my code then it Archives Successfully.

EDIT 2 :

When I change CodeGen to Manual/None and add files manually as suggested by @Anil . It builds successfully, But when I try to fetch the CoreData entity using :

let context = appDelegate.persistentContainer.viewContext
let buildingRoofMapping = BuildingRoofMapping(context:context)

It gives me run time error.
Error :

'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'BuildingRoofMapping' must have a valid NSEntityDescription.'

EDIT 3:
   Sample Code link. Run it in simulator. It crashes in fetchBasicPrice() of ViewController.swift file


问:
Upgrading mongodb has no effect and still shows the old version
Following are the commands which I used to upgrade my mongodb version from 2.6.9 to latest, but its still showing me the previous version. Let me know what I am doing wrong with the upgrading process. The problem is that mongod -version still shows the old version installed after upgrade.

Docs which I refer to - Mongodb Docs

Steps I followed -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org

Result -

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be upgraded:
  mongodb-org
1 upgraded, 0 newly installed, 0 to remove and 139 not upgraded.
Need to get 3,608 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://repo.mongodb.org/apt/ubuntu/ trusty/mongodb-org/3.0/multiverse mongodb-org amd64 3.0.2 [3,608 B]
Fetched 3,608 B in 0s (18.3 kB/s)
(Reading database ... 298790 files and directories currently installed.)
Preparing to unpack .../mongodb-org_3.0.2_amd64.deb ...
arg: upgrade
Unpacking mongodb-org (3.0.2) over (2.6.9) ...
Setting up mongodb-org (3.0.2) ...
</code>```

After this I re started the service - sudo service mongod restart

But still its showing me version 2.6.9 Let me know what I am doing wrong here..or missed any step ?

答:
Step 1: First you need to uninstall existing mongodb

stop Mongodb service

sudo service mongod stop

Remove Packages.

sudo apt-get purge mongodb-org*

Remove Data Directories. (optional)

sudo rm -r /var/log/mongodb

sudo rm -r /var/lib/mongodb

Step 2: Then Install latest mongodb (i.e. 3.4)

1. Import the public key used by the package management system.

```<code>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
</code>```

2. Create a list file for MongoDB. (Ubuntu 16.04)

```<code>echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
</code>```

3. Reload local package database.

sudo apt-get update

4. Install the latest stable version of MongoDB

sudo apt-get install -y mongodb-org

5. Start MongoDB.

sudo service mongod start

6. Verify that MongoDB has started successfully

Verify that the mongod process has started successfully by checking
the contents of the log file at /var/log/mongodb/mongod.log for a line
reading

[initandlisten] waiting for connections on port

where  is the port configured in /etc/mongod.conf, 27017 by default.

Body:
Following are the commands which I used to upgrade my mongodb version from 2.6.9 to latest, but its still showing me the previous version. Let me know what I am doing wrong with the upgrading process. The problem is that mongod -version still shows the old version installed after upgrade.

Docs which I refer to - Mongodb Docs

Steps I followed -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org

Result -

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be upgraded:
  mongodb-org
1 upgraded, 0 newly installed, 0 to remove and 139 not upgraded.
Need to get 3,608 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://repo.mongodb.org/apt/ubuntu/ trusty/mongodb-org/3.0/multiverse mongodb-org amd64 3.0.2 [3,608 B]
Fetched 3,608 B in 0s (18.3 kB/s)
(Reading database ... 298790 files and directories currently installed.)
Preparing to unpack .../mongodb-org_3.0.2_amd64.deb ...
arg: upgrade
Unpacking mongodb-org (3.0.2) over (2.6.9) ...
Setting up mongodb-org (3.0.2) ...

After this I re started the service - sudo service mongod restart

But still its showing me version 2.6.9 Let me know what I am doing wrong here..or missed any step ?

Body:
Step 1: First you need to uninstall existing mongodb

stop Mongodb service

sudo service mongod stop

Remove Packages.

sudo apt-get purge mongodb-org*

Remove Data Directories. (optional)

sudo rm -r /var/log/mongodb

sudo rm -r /var/lib/mongodb

Step 2: Then Install latest mongodb (i.e. 3.4)

1. Import the public key used by the package management system.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

2. Create a list file for MongoDB. (Ubuntu 16.04)

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

3. Reload local package database.

sudo apt-get update

4. Install the latest stable version of MongoDB

sudo apt-get install -y mongodb-org

5. Start MongoDB.

sudo service mongod start

6. Verify that MongoDB has started successfully

Verify that the mongod process has started successfully by checking
the contents of the log file at /var/log/mongodb/mongod.log for a line
reading

[initandlisten] waiting for connections on port

where  is the port configured in /etc/mongod.conf, 27017 by default.


问:
what is the diffrent between these codes:one of them does'nt change label text
I wrote this code to change label text. but id does not change:

```<code>void DateTimes::on_btnHourP_clicked()
{
    int h=ui->txtHour->text().toInt();
    if(h==24)
        h=-1;
    ui->txtHour->setText(QString::number(h++));//*
}
</code>```

but my label text not change. then I change the code to this:

```<code>void DateTimes::on_btnHourP_clicked()
{
    int h=ui->txtHour->text().toInt();
    if(h==24)
        h=-1;
    h+=1;//*
    ui->txtHour->setText(QString::number(h));//*
}
</code>```

then the text of my label is change.

why?! could anyone solve my question?

答:
Incremet operator ++ will use the value and then increment. If you want to use the incremented h value within the same expresion. use ++h.</p>

```<code>ui->txtHour->setText(QString::number(++h));
</code>```

Body:
I wrote this code to change label text. but id does not change:

void DateTimes::on_btnHourP_clicked()
{
    int h=ui->txtHour->text().toInt();
    if(h==24)
        h=-1;
    ui->txtHour->setText(QString::number(h++));//*
}

but my label text not change. then I change the code to this:

void DateTimes::on_btnHourP_clicked()
{
    int h=ui->txtHour->text().toInt();
    if(h==24)
        h=-1;
    h+=1;//*
    ui->txtHour->setText(QString::number(h));//*
}

then the text of my label is change.

why?! could anyone solve my question?

Body:
Incremet operator ++ will use the value and then increment. If you want to use the incremented h value within the same expresion. use ++h.

ui->txtHour->setText(QString::number(++h));