问:
Assist with simple count out of a list
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

```<code>public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}
</code>```

答:
Ok, first of all, we're doing something bad in the loop.

You're declaring newAgents, and setting it over and over again, so it will always have values equal to the last item in e.CmsData.Agents. For example, if you have a list, and the AgNames of the items in the list are:

```<code>Bob
Michael
James
</code>```

newAgents is always going to have an AgentName of "James" when the loop completes, because it's declared out of scope of the loop. Fix this by moving the declaration of your NewAgent placeholder inside the scope of the loop, like following:

```<code>List<NewAgent> newAgentList = new List<NewAgent>();
foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();
    // perform your data transforms
    newAgentList.Add(newAgents);
}
</code>```

That will make it so you're actually adding elements to your list that correspond to the data you're trying to manipulate, and there is no need for that variable to exist outside the loop.

Are you trying to count the number of reasons per Agent in the list, or are you trying to count all "Break" reasons in all agents? The reason I ask is again, you're doing your last foreach loop on your iterator variable, after your iteration process has completed.

To count all elements' breaks, do this instead of your second loop:

```<code>int count = newAgentList.Sum(agent =>
    agent.AuxReasons.Count(reasons =>
        !string.IsNullOrEmpty(reasons) && reasons.StartsWith("Break")));
</code>```

If you want to count the iterator while you're operating on it, use the inner lambda function in your first loop like this:

```<code>foreach (var item in e.CmsData.Agents)
{
    // other logic from above
    int count = newAgents.AuxReasons.Count(r =>
        !string.IsNullOrEmpty(r) && r.StartsWith("Break");
    // do something with count before loop ends
}
</code>```

If you do this latter version, you're going to need to do something with that count before the loop's iteration completes or it will be lost.

If all this is unclear, here's a fully modified version of your code:

```<code>List<NewAgent> newAgentList = new List<NewAgent>();

foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = newAgentList.Count(agent =>
    !string.IsNullOrEmpty(agent.AuxReasons) && agent.AuxReasons.StartsWith("Break"));
</code>```

Title: Assist with simple count out of a list

Body:
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}

Body:
Ok, first of all, we're doing something bad in the loop.

You're declaring newAgents, and setting it over and over again, so it will always have values equal to the last item in e.CmsData.Agents. For example, if you have a list, and the AgNames of the items in the list are:

Bob
Michael
James

newAgents is always going to have an AgentName of "James" when the loop completes, because it's declared out of scope of the loop. Fix this by moving the declaration of your NewAgent placeholder inside the scope of the loop, like following:

List<NewAgent> newAgentList = new List<NewAgent>();
foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();
    // perform your data transforms
    newAgentList.Add(newAgents);
}

That will make it so you're actually adding elements to your list that correspond to the data you're trying to manipulate, and there is no need for that variable to exist outside the loop.

Are you trying to count the number of reasons per Agent in the list, or are you trying to count all "Break" reasons in all agents? The reason I ask is again, you're doing your last foreach loop on your iterator variable, after your iteration process has completed.

To count all elements' breaks, do this instead of your second loop:

int count = newAgentList.Sum(agent =>
    agent.AuxReasons.Count(reasons =>
        !string.IsNullOrEmpty(reasons) && reasons.StartsWith("Break")));

If you want to count the iterator while you're operating on it, use the inner lambda function in your first loop like this:

foreach (var item in e.CmsData.Agents)
{
    // other logic from above
    int count = newAgents.AuxReasons.Count(r =>
        !string.IsNullOrEmpty(r) && r.StartsWith("Break");
    // do something with count before loop ends
}

If you do this latter version, you're going to need to do something with that count before the loop's iteration completes or it will be lost.

If all this is unclear, here's a fully modified version of your code:

List<NewAgent> newAgentList = new List<NewAgent>();

foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = newAgentList.Count(agent =>
    !string.IsNullOrEmpty(agent.AuxReasons) && agent.AuxReasons.StartsWith("Break"));


来源: stackexchange

问:
Deep clone of Hibernate entity
I am wondering how can I create a deep copy of a persisted object with all of its association.
Let say I have the following model.

```<code>class Document {
    String title;
    String content;
    Person owner;
    Set<Citation> citations;
}

class Person {
    String name;
    Set<Document> documents;
}

class Citation {
    String title;
    Date date;
    Set<Document> documents;
}
</code>```

I have a scenario in which a user might want to grab a copy of a particular document from a person and make the document his/hers then later he / she can change its content and name.
In that case I can think of one way to implement that kind of scenario which is creating a deep copy of that document (with its associations).

Or maybe if anyone knows of any other possible way to do such thing without doing huge copy of data because I know it may be bad for the app performance.

I was also thinking of may be creating a reference of to the original document like having an attribute originalDocument but that way I won't be able to know which attribute (or maybe association) has been changed.

答:
Jackon serialisation configuration for hibernate :

```<code>  ObjectMapper mapperInstance
     Hibernate4Module module = new Hibernate4Module();
        module.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, false);

        mapperInstance.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapperInstance.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
        mapperInstance.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapperInstance.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        mapperInstance.registerModule(module);
</code>```

And next

```<code>clone = getMapperInstance().readValue(getMapperInstance().writeValueAsString(this));
</code>```

Ok it cost some memory and cpu...

ContentLicense: CC BY-SA 3.0

Title: Deep clone of Hibernate entity

Body:
I am wondering how can I create a deep copy of a persisted object with all of its association.
Let say I have the following model.

class Document {
    String title;
    String content;
    Person owner;
    Set<Citation> citations;
}

class Person {
    String name;
    Set<Document> documents;
}

class Citation {
    String title;
    Date date;
    Set<Document> documents;
}

I have a scenario in which a user might want to grab a copy of a particular document from a person and make the document his/hers then later he / she can change its content and name.
In that case I can think of one way to implement that kind of scenario which is creating a deep copy of that document (with its associations).

Or maybe if anyone knows of any other possible way to do such thing without doing huge copy of data because I know it may be bad for the app performance.

I was also thinking of may be creating a reference of to the original document like having an attribute originalDocument but that way I won't be able to know which attribute (or maybe association) has been changed.

Body:
Jackon serialisation configuration for hibernate :

  ObjectMapper mapperInstance
     Hibernate4Module module = new Hibernate4Module();
        module.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, false);

        mapperInstance.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapperInstance.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
        mapperInstance.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapperInstance.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        mapperInstance.registerModule(module);

And next

clone = getMapperInstance().readValue(getMapperInstance().writeValueAsString(this));

Ok it cost some memory and cpu...


问:
Reading different kind of variables of unknown quantity from a .txt file line by line
I need to read an integer,a string and then integers of unknown quantity from the .txt file.And this should be done line by line.

An example .txt file:

```<code>541 Andy  76 55 84 80
841 Kevin 51 37 60 55 71 68
418 Erik 25 85 40
966 Martha  64 82 71 83 55
</code>```

The output should be like:

```<code>ID:541 Name:Andy Values: [76, 55, 84, 80]
ID:841 Name:Kevin Values: [51, 37, 60, 55, 71, 68]
ID:418 Name:Erik Values: [25, 85, 40]
ID:966 Name:Martha Values: [64, 82, 71, 83, 55]
</code>```

The problem is, I don't know how many values a person has.So my code should keep adding the new integers to an array until it sees the end of the line.I will have to pass these information to functions after this.So simply printing these to screen is not enough.I should be able to access and use them.And I can't scan all the .txt file (so can't use fscanf) because I need to pass them to functions person by person.

答:
I'd start with defining a Person structure

```<code>struct Person {
    int id;
    char *name;
    int *nums;
    size_t nums_size;
};
</code>```

and an array of Persons.

```<code>#define BUFFER_SIZE 128
struct Person *persons;
int persons_index = 0;
size_t persons_size = BUFFER_SIZE;
persons = malloc(persons_size * sizeof(struct Person));
</code>```

In a loop, read one character at a time using fgetc until you encounter a newline character normally \n on Unix-like systems. Note that you should always check for buffer overruns and extend the buffer as necessary.

```<code>char *buffer;
int buffer_index = 0;
size_t buffer_size = BUFFER_SIZE;
buffer = malloc(buffer_size * sizeof(char));
while ((c = fgetc(file)) != EOF) {
    if (buffer_index > buffer_size - 2) {
        buffer_size *= 2;
        buffer = realloc(buffer, buffer_size);
    }

    if (c == '\n') {
        /* Tokenize here */
    } else {
        /* Store the character and null terminate the buffer */
    }
}
</code>```

Given a whole line is in the buffer, tokenize the line using strtok. Convert each string integer using atoi. Converting the values followed by persons names is basically the same as above.

```<code>int nums_index = 0;
size_t nums_size = BUFFER_SIZE;
persons[persons_index].nums = malloc(nums_size * sizeof(int));
/* Assuming strtok has been called before for person's id and name */
while ((token = strtok(NULL, " ")) != NULL) {
    if (nums_index > nums_size - 1) {
        nums_size *= 2;
        persons[persons_index].nums = realloc(
            persons[persons_index].nums, nums_size);
    }
    persons[persons_index].nums[nums_index] = atoi(token);
    nums_index++;
}
persons[persons_index].nums_size = nums_index;
</code>```

Don't forget to free the buffer and the persons array with your done with them and please note that I left lots of details and error checkings out.

Body:
I need to read an integer,a string and then integers of unknown quantity from the .txt file.And this should be done line by line.

An example .txt file:

541 Andy  76 55 84 80
841 Kevin 51 37 60 55 71 68
418 Erik 25 85 40
966 Martha  64 82 71 83 55

The output should be like:

ID:541 Name:Andy Values: [76, 55, 84, 80]
ID:841 Name:Kevin Values: [51, 37, 60, 55, 71, 68]
ID:418 Name:Erik Values: [25, 85, 40]
ID:966 Name:Martha Values: [64, 82, 71, 83, 55]

The problem is, I don't know how many values a person has.So my code should keep adding the new integers to an array until it sees the end of the line.I will have to pass these information to functions after this.So simply printing these to screen is not enough.I should be able to access and use them.And I can't scan all the .txt file (so can't use fscanf) because I need to pass them to functions person by person.

Body:
I'd start with defining a Person structure

struct Person {
    int id;
    char *name;
    int *nums;
    size_t nums_size;
};

and an array of Persons.

#define BUFFER_SIZE 128
struct Person *persons;
int persons_index = 0;
size_t persons_size = BUFFER_SIZE;
persons = malloc(persons_size * sizeof(struct Person));

In a loop, read one character at a time using fgetc until you encounter a newline character normally \n on Unix-like systems. Note that you should always check for buffer overruns and extend the buffer as necessary.

char *buffer;
int buffer_index = 0;
size_t buffer_size = BUFFER_SIZE;
buffer = malloc(buffer_size * sizeof(char));
while ((c = fgetc(file)) != EOF) {
    if (buffer_index > buffer_size - 2) {
        buffer_size *= 2;
        buffer = realloc(buffer, buffer_size);
    }

    if (c == '\n') {
        /* Tokenize here */
    } else {
        /* Store the character and null terminate the buffer */
    }
}

Given a whole line is in the buffer, tokenize the line using strtok. Convert each string integer using atoi. Converting the values followed by persons names is basically the same as above.

int nums_index = 0;
size_t nums_size = BUFFER_SIZE;
persons[persons_index].nums = malloc(nums_size * sizeof(int));
/* Assuming strtok has been called before for person's id and name */
while ((token = strtok(NULL, " ")) != NULL) {
    if (nums_index > nums_size - 1) {
        nums_size *= 2;
        persons[persons_index].nums = realloc(
            persons[persons_index].nums, nums_size);
    }
    persons[persons_index].nums[nums_index] = atoi(token);
    nums_index++;
}
persons[persons_index].nums_size = nums_index;

Don't forget to free the buffer and the persons array with your done with them and please note that I left lots of details and error checkings out.


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
For the sample case where results only contains two different integers:

```<code>import numpy as np

results = np.array([100, 100, -100, 100, -100, -100])

output = list(zip(np.where(results > 0)[0], np.where(results < 0)[0]))
</code>```

Output:

```<code>[(0, 2), (1, 4), (3, 5)]
</code>```

Time is ~0.002 for results * 1000.

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
For the sample case where results only contains two different integers:

import numpy as np

results = np.array([100, 100, -100, 100, -100, -100])

output = list(zip(np.where(results > 0)[0], np.where(results < 0)[0]))

Output:

[(0, 2), (1, 4), (3, 5)]

Time is ~0.002 for results * 1000.


问:
compare objects by multiple fields, how to add in one method?
How can I combine the following compare method in one compare method(comparator1) and (comparator2) ?

´´´

```<code>private List<Bonus> getBonusListSortedByHasAccountAndDate(List<Bonus> bonusList) {

    final Comparator<Bonus> comparator1 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return Boolean.compare(o1.isActive(), o2.isActive());
        }
    };

    bonusList.sort(comparator1);
    List bonusList2 = bonusList;

    final Comparator<Bonus> comparator2 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    };
    bonusList2.sort(comparator2);
    return bonusList2;
}

@Test
public void test() {
    List<Bonus> bonus = createBonus();
    List<Bonus> getBonusListSortedByHasAccountAndDate = getBonusDTOListSortedByHasAccount2(bonus);
    assertThat(getBonusListSortedByHasAccountAndDate.get(0).getName(), is("2"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(1).getName(), is("3"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(2).getName(), is("1"));
}
</code>```

updated: for my compare and sorting I want to have "the oldest Bonus created" and "Bonus should be activated"

many thanks in advance.
zoram

答:
How about:-

```<code>final Comparator<Bonus> comparator = new Comparator<Bonus>() {
    public int compare(Bonus o1, Bonus o2) {
        if (Boolean.compare(o1.isActive(), o2.isActive()) == 0) {
            return o1.getDate().compareTo(o2.getDate());
        } else {
            return Boolean.compare(o1.isActive(), o2.isActive());
        }
    }
};
</code>```

I'm assuming that isActive() takes precedence over getDate().

(Thanks to @Jaroslaw Pawlak for pointing out the n00b error).

Body:
How can I combine the following compare method in one compare method(comparator1) and (comparator2) ?

´´´

private List<Bonus> getBonusListSortedByHasAccountAndDate(List<Bonus> bonusList) {

    final Comparator<Bonus> comparator1 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return Boolean.compare(o1.isActive(), o2.isActive());
        }
    };

    bonusList.sort(comparator1);
    List bonusList2 = bonusList;

    final Comparator<Bonus> comparator2 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    };
    bonusList2.sort(comparator2);
    return bonusList2;
}

@Test
public void test() {
    List<Bonus> bonus = createBonus();
    List<Bonus> getBonusListSortedByHasAccountAndDate = getBonusDTOListSortedByHasAccount2(bonus);
    assertThat(getBonusListSortedByHasAccountAndDate.get(0).getName(), is("2"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(1).getName(), is("3"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(2).getName(), is("1"));
}

updated: for my compare and sorting I want to have "the oldest Bonus created" and "Bonus should be activated"

many thanks in advance.
zoram

Body:
How about:-

final Comparator<Bonus> comparator = new Comparator<Bonus>() {
    public int compare(Bonus o1, Bonus o2) {
        if (Boolean.compare(o1.isActive(), o2.isActive()) == 0) {
            return o1.getDate().compareTo(o2.getDate());
        } else {
            return Boolean.compare(o1.isActive(), o2.isActive());
        }
    }
};

I'm assuming that isActive() takes precedence over getDate().

(Thanks to @Jaroslaw Pawlak for pointing out the n00b error).


问:
How to change my user account on git?
I changed my username and my email and I would like to change my username_old to username_new but I have always this git error.

$ git push

remote: Permission to k***/minetest.git denied to username_old.

fatal: unable to access 'https://github.com/k***/minetest.git/': The requested URL returned error: 403

I tried this link: https://help.github.com/articles/setting-your-username-in-git/

When I ask about my username it show username_new

I think that I must to delete a certificate on Windows 10 but I dont know where is this file?

I have the same error but in windows 10  :
https://superuser.com/questions/1064197/how-to-switch-git-user-at-terminal

答:
your question is already answered in this question:

remove credentials from git

"Open User Accounts by clicking the Start button Picture of the Start button, clicking Control Panel, clicking User Accounts and Family Safety (or clicking User Accounts, if you are connected to a network domain), and then clicking User Accounts. In the left pane, click Manage your credentials."

There you can delete the info and execute the git command again with a user/command prompt.

Title: How to change my user account on git?


问:
How to avoid losing event on input after toggle visivility?
I have an input which should keep the focus, because of program requirements. While using the software the input might be hidden at some point but when showing up again it should recover the focus, but it doesn't. Still if you check the binded events on the input you can see it did not actually lost the event.

There's a simple jsfiddle showing this behaviour: https://jsfiddle.net/5puu261v/

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('#barcode').toggle()">Toggle input</button>
<input type="text" id="barcode" /></code>```

It would be appreciated if I could fix or avoid it without binding the event back again.

Edit:

The point is: Why does the input doesn't get focused, after being toggled, when clicking on any other element (as the button that makes it visible again)?

答:
You can call the method focus again at onclick event of button:

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('#barcode').toggle();$('#barcode').focus();">Toggle input</button>
<input type="text" id="barcode" /></code>```

Body:
I have an input which should keep the focus, because of program requirements. While using the software the input might be hidden at some point but when showing up again it should recover the focus, but it doesn't. Still if you check the binded events on the input you can see it did not actually lost the event.

There's a simple jsfiddle showing this behaviour: https://jsfiddle.net/5puu261v/

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});

<button onclick="$('#barcode').toggle()">Toggle input</button>
<input type="text" id="barcode" />

It would be appreciated if I could fix or avoid it without binding the event back again.

Edit:

The point is: Why does the input doesn't get focused, after being toggled, when clicking on any other element (as the button that makes it visible again)?

Body:
You can call the method focus again at onclick event of button:

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('#barcode').toggle();$('#barcode').focus();">Toggle input</button>
<input type="text" id="barcode" />


问:
Solving (nonlinear) equations in simulation tools
I am intersted, how a modelling tool (in my case OpenModelica and Dymola - modelling language Modelica) solves systems of equations (linear and/or nonlinear). These tools are designed for solving differential algebraic equations. I know a little bit the theory behind transforming a differential algebraic equation sytem into an ODE (keyword "index-reduction"). My questions:

How do these tools solve a system of equations without differential equations? Is the system nevertheless transformed (index reduction) into an ODE?

What if I have a model that has a few algebraic equations and a few ODE - but they are not coupled?

Thank you very much.

答: OpenModelica will use an equidistant time grid based on the number of output time points (or number of intervals) and solve the algebraic system for each of these time points.</p>


问:
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference Retrofit
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()

on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!

MyBlog Adapter:

```<code>public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
    List<BlogResponse> postsList;
    Context context;
    public static String blog_Id, blogID;
    private LayoutInflater inflater;

    public MyBlogAdapter(Context context, List<BlogResponse> postsList){
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.postsList = postsList;
    }

    @Override
    public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.custom_view,parent, false);
        return new BlogViewHolder(view);
    }

    @Override
    public void onBindViewHolder(BlogViewHolder holder, int position) {
        final BlogResponse posts= postsList.get(position);
        holder.summary.setText(posts.getBlogExcerpt().trim().toString());
        holder.title.setText(posts.getBlogTitle().trim().toString());
        //  Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);

        holder.blogHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AnotherSingleView.class);
                blog_Id = posts.getBlogId();
                intent.putExtra(blogID,blog_Id);
                Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);

                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.d("MyBlogAdapter,","getItemCount"+postsList.size());

        return postsList == null ? (0) : postsList.size();
    }
}
</code>```

SecondActivity:

```<code>public class AnotherSingleView extends AppCompatActivity {
    String postID;
    int position;
    public TextView blogTitle,blogSub,blogContent;
    public ImageView blogPic;
    List<SingleBlogPost> singleBlogPosts;
    SingleBlogPost singleBlogPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another_single_view);

        Intent intent  = getIntent();
        Bundle showBlogId = intent.getExtras();
        postID = showBlogId.getString(blogID);
        Log.d("AnotherSingleView","Please check blog Id: "+postID);

        singleBlogPosts = new ArrayList<>();

        blogContent = (TextView)findViewById(R.id.blog_content);
        blogSub = (TextView) findViewById(R.id.blog_subtitle);
        blogTitle =(TextView) findViewById(R.id.blog_title);
        blogPic =(ImageView) findViewById(R.id.blog_pix);
        singlePostDisplay();

    }

private void singlePostDisplay() {
    BlogaPI api = ApiClient.getBlogInterface();
    Call<List<SingleBlogPost>> call = api.postResponse(postID);
    call.enqueue(new Callback<List<SingleBlogPost>>() {
        @Override
        public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
            singleBlogPosts = response.body();
            if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
                for (SingleBlogPost posts : singleBlogPosts){
                    Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
                    blogTitle.setText(posts.getBlogTitle());
                    blogSub.setText(posts.getBlogSubtitle());
                    blogContent.setText(posts.getBlogContent());
                    // Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
                }
            }
            else{
                Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
            }            }

            @Override
            public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
                Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
</code>```

Interface:

```<code>public interface BlogaPI {
    @GET("blog")
    Call<BlogList> response();

    @GET("post/{blog_id}")
    Call<List<SingleBlogPost>> postResponse(@Path("blog_id") String blog_id);
    //Call<List<SingleBlogPost>> postResponse();
}
</code>```

SingleBlogPost:

```<code>public class SingleBlogPost {

@SerializedName("blog_id")
@Expose
private String blogId;
@SerializedName("blog_title")
@Expose
private String blogTitle;
@SerializedName("blog_subtitle")
@Expose
private String blogSubtitle;
@SerializedName("blog_excerpt")
@Expose
private String blogExcerpt;
@SerializedName("blog_content")
@Expose
private String blogContent;
@SerializedName("blog_thumbnail")
@Expose
private String blogThumbnail;
@SerializedName("blog_medimg")
@Expose
private String blogMedimg;
@SerializedName("category_title")
@Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
                      String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
    this.blogId = blogId;
    this.blogTitle = blogTitle;
    this.blogSubtitle = blogSubtitle;
    this.blogExcerpt = blogExcerpt;
    this.blogContent = blogContent;
    this.blogThumbnail = blogThumbnail;
    this.blogMedimg = blogMedimg;
    this.categoryTitle = categoryTitle;
}

public String getBlogId() {
    return blogId;
}

public void setBlogId(String blogId) {
    this.blogId = blogId;
}

public String getBlogTitle() {
    return blogTitle;
}

public void setBlogTitle(String blogTitle) {
    this.blogTitle = blogTitle;
}

public String getBlogSubtitle() {
    return blogSubtitle;
}

public void setBlogSubtitle(String blogSubtitle) {
    this.blogSubtitle = blogSubtitle;
}

public String getBlogExcerpt() {
    return blogExcerpt;
}

public void setBlogExcerpt(String blogExcerpt) {
    this.blogExcerpt = blogExcerpt;
}

public String getBlogContent() {
    return blogContent;
}

public void setBlogContent(String blogContent) {
    this.blogContent = blogContent;
}

public String getBlogThumbnail() {
    return blogThumbnail;
}

public void setBlogThumbnail(String blogThumbnail) {
    this.blogThumbnail = blogThumbnail;
}

public String getBlogMedimg() {
    return blogMedimg;
}

public void setBlogMedimg(String blogMedimg) {
    this.blogMedimg = blogMedimg;
}

public String getCategoryTitle() {
    return categoryTitle;
}

public void setCategoryTitle(String categoryTitle) {
    this.categoryTitle = categoryTitle;
}

}
</code>```

答: you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.</p>

Body:
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()

on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!

MyBlog Adapter:

public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
    List<BlogResponse> postsList;
    Context context;
    public static String blog_Id, blogID;
    private LayoutInflater inflater;

    public MyBlogAdapter(Context context, List<BlogResponse> postsList){
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.postsList = postsList;
    }

    @Override
    public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.custom_view,parent, false);
        return new BlogViewHolder(view);
    }

    @Override
    public void onBindViewHolder(BlogViewHolder holder, int position) {
        final BlogResponse posts= postsList.get(position);
        holder.summary.setText(posts.getBlogExcerpt().trim().toString());
        holder.title.setText(posts.getBlogTitle().trim().toString());
        //  Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);

        holder.blogHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AnotherSingleView.class);
                blog_Id = posts.getBlogId();
                intent.putExtra(blogID,blog_Id);
                Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);

                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.d("MyBlogAdapter,","getItemCount"+postsList.size());

        return postsList == null ? (0) : postsList.size();
    }
}

SecondActivity:

public class AnotherSingleView extends AppCompatActivity {
    String postID;
    int position;
    public TextView blogTitle,blogSub,blogContent;
    public ImageView blogPic;
    List<SingleBlogPost> singleBlogPosts;
    SingleBlogPost singleBlogPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another_single_view);

        Intent intent  = getIntent();
        Bundle showBlogId = intent.getExtras();
        postID = showBlogId.getString(blogID);
        Log.d("AnotherSingleView","Please check blog Id: "+postID);

        singleBlogPosts = new ArrayList<>();

        blogContent = (TextView)findViewById(R.id.blog_content);
        blogSub = (TextView) findViewById(R.id.blog_subtitle);
        blogTitle =(TextView) findViewById(R.id.blog_title);
        blogPic =(ImageView) findViewById(R.id.blog_pix);
        singlePostDisplay();

    }

private void singlePostDisplay() {
    BlogaPI api = ApiClient.getBlogInterface();
    Call<List<SingleBlogPost>> call = api.postResponse(postID);
    call.enqueue(new Callback<List<SingleBlogPost>>() {
        @Override
        public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
            singleBlogPosts = response.body();
            if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
                for (SingleBlogPost posts : singleBlogPosts){
                    Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
                    blogTitle.setText(posts.getBlogTitle());
                    blogSub.setText(posts.getBlogSubtitle());
                    blogContent.setText(posts.getBlogContent());
                    // Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
                }
            }
            else{
                Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
            }            }

            @Override
            public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
                Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Interface:

public interface BlogaPI {
    @GET("blog")
    Call<BlogList> response();

    @GET("post/{blog_id}")
    Call<List<SingleBlogPost>> postResponse(@Path("blog_id") String blog_id);
    //Call<List<SingleBlogPost>> postResponse();
}

SingleBlogPost:

public class SingleBlogPost {

@SerializedName("blog_id")
@Expose
private String blogId;
@SerializedName("blog_title")
@Expose
private String blogTitle;
@SerializedName("blog_subtitle")
@Expose
private String blogSubtitle;
@SerializedName("blog_excerpt")
@Expose
private String blogExcerpt;
@SerializedName("blog_content")
@Expose
private String blogContent;
@SerializedName("blog_thumbnail")
@Expose
private String blogThumbnail;
@SerializedName("blog_medimg")
@Expose
private String blogMedimg;
@SerializedName("category_title")
@Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
                      String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
    this.blogId = blogId;
    this.blogTitle = blogTitle;
    this.blogSubtitle = blogSubtitle;
    this.blogExcerpt = blogExcerpt;
    this.blogContent = blogContent;
    this.blogThumbnail = blogThumbnail;
    this.blogMedimg = blogMedimg;
    this.categoryTitle = categoryTitle;
}

public String getBlogId() {
    return blogId;
}

public void setBlogId(String blogId) {
    this.blogId = blogId;
}

public String getBlogTitle() {
    return blogTitle;
}

public void setBlogTitle(String blogTitle) {
    this.blogTitle = blogTitle;
}

public String getBlogSubtitle() {
    return blogSubtitle;
}

public void setBlogSubtitle(String blogSubtitle) {
    this.blogSubtitle = blogSubtitle;
}

public String getBlogExcerpt() {
    return blogExcerpt;
}

public void setBlogExcerpt(String blogExcerpt) {
    this.blogExcerpt = blogExcerpt;
}

public String getBlogContent() {
    return blogContent;
}

public void setBlogContent(String blogContent) {
    this.blogContent = blogContent;
}

public String getBlogThumbnail() {
    return blogThumbnail;
}

public void setBlogThumbnail(String blogThumbnail) {
    this.blogThumbnail = blogThumbnail;
}

public String getBlogMedimg() {
    return blogMedimg;
}

public void setBlogMedimg(String blogMedimg) {
    this.blogMedimg = blogMedimg;
}

public String getCategoryTitle() {
    return categoryTitle;
}

public void setCategoryTitle(String categoryTitle) {
    this.categoryTitle = categoryTitle;
}

}


问:
Android converting stream to byte array Out of Memory Exceptions
I have ran into a situation where I am getting out of memory exceptions when trying to convert an input stream into a byte array. On newer Android phones it's no problem, but some of these cheaper models are experiencing it. Here is the method I'm using. Is there a more efficient way to do this?</p>

```<code>public byte[] convertStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buff = new byte[1024];
  int i = 0;
  while ((i = is.read(buff, 0, buff.length)) > 0) {
    baos.write(buff, 0, i);
  }
  return baos.toByteArray();
}
</code>```

答:
Try to create an byte array with the size of InputStream like this :

```<code>public byte[] convertStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[is.available()];
    int i = 0;
    while ((i = is.read(buff, 0, buff.length)) > 0) {
        baos.write(buff, 0, i);
    }
    return baos.toByteArray();
</code>```

}

Body:
I have ran into a situation where I am getting out of memory exceptions when trying to convert an input stream into a byte array. On newer Android phones it's no problem, but some of these cheaper models are experiencing it. Here is the method I'm using. Is there a more efficient way to do this?

public byte[] convertStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buff = new byte[1024];
  int i = 0;
  while ((i = is.read(buff, 0, buff.length)) > 0) {
    baos.write(buff, 0, i);
  }
  return baos.toByteArray();
}

Body:
Try to create an byte array with the size of InputStream like this :

public byte[] convertStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[is.available()];
    int i = 0;
    while ((i = is.read(buff, 0, buff.length)) > 0) {
        baos.write(buff, 0, i);
    }
    return baos.toByteArray();

}


问:
Chome Extension - QuotaExceededError localStorage
I'm developing a Chrome extension and using old localStorage to store settings and cache instead of new chrome.storage.local and chrome.storage.sync. I have unlimitedStorage permission and then my cache becomes huge. I'm receiving QuotaExceededError.

How to overcome the problem?

答:
localStorage is not, and will not be, unlimited

The fact that the unlimitedStorage permission does not apply to localStorage is stated in the documentation. The referenced bug, issue 58985, was marked as "WontFix" in December of 2010. Thus, there is not, and will not be, a solution for you to store unlimited data in localStorage. You will need to select some other method of storing your data.

Unlimited storage options

storage.local

Your options include chrome.storage which is explicitly intended for extensions to store data. You can store data that is local to the machine, using storage.local (can be unlimited with the unlimitedStorage permission), or data that is synchronized across the user's Google account, with storage.sync (quota is not set to unlimited by unlimitedStorage).

Web SQL Database

There are other options for storing data. For instance, the Web SQL Database, which is specifically granted unlimited storage by the unlimitedStorage permission.

HTML5 local File API (MDN)

The amount of data you can store with the File API becomes unlimited with the unlimitedStorage permission. You can also separately request a specific quota size with a call to webkitStorageInfo.requestQuota(), without using the unlimitedStorage permission. When you do, the user will be asked to approve the storage request. If you do use the unlimitedStorage permission, you do not need to separately request a quota.

What to use

What is best to use will depend on exactly what you are using storage for. You have provided no information as to your actual use, so there is no way for us to gauge what might be a good fit in your case.

Application cache

As to your issue with the application cache growing to a large size with the unlimitedStorage permission: Yes, the documenation explicitly states that declaring the unlimitedStorage permission will result in the application cache becoming unlimited. If this is an issue, you will need to not declare the unlimitedStorage permission.

ContentLicense: CC BY-SA 4.0


问:
cloudera navigator multi-tenancy capability
In short, can Cloudera Navigator be configured for a multi-tenancy context ?
In detail, we have a datalake (Hadoop cluster) with many business entities, and we want that each business ventity view, manage and access only it own data using the cloudera navigator.

I didn't find any information on the net, and the ui seems to not provide such option.

thanks in advance

答:
At the current version, Cloudera navigator is not multi-tenancy enabled.

So, at short time one of the solution is custom dev using the Cloudera navigator API coupled with other technologies.


问:
Angular: resolve all route segments configuration by URL
Given a URL, e.g. /path/path2/path3/123;sdf=df and a routes configuration:

```<code>{ path: 'path', data: { g: 'h' }, children: [
  { path: 'path2', data: { c: 'd' }, children: [
    { path: 'something', component: TestpageComponent, data: { a: 'b' } },
    { path: 'path3/create', component: TestpageComponent, data: { b: 'c' } },
    { path: 'path3/:id', component: TestpageComponent, data: { b: 'c' } },
  ] }
] },
</code>```

What I need is to find an actual configuration for all the segments in order to get a result set of all data parameters on all levels (each segment of the url).

I can split the URL in the segments by e.g.

```<code>console.log(this.router.parseUrl(url));
</code>```

or to be more precise

```<code>console.log(this.router.parseUrl(url).root.children['primary'].segments);
</code>```

which will return

```<code>[{"path":"path","parameters":{}},{"path":"path2","parameters":{}},{"path":"and","parameters":{}},{"path":"123","parameters":{"sdf":"df"}}]
</code>```

So, splitting the URL into segments is not a problem. However I need to get a configuration for each segment.

I can get the actual configuration for all the routes with

```<code>console.log(this.router.config);
</code>```

I can go with the segments through the configuration tree and find out the branch I need, but it can cause troubles e.g. while resolving :id against create segment. So, I would like to use the router's way of resolving the configuration that if the inner router implementation changes I would not need to change mine.

Example: imagine I have a 50% of the URLs protected by some guard (e.g. only logged in users could go there) and other 50% is not protected (displayed for everybody). So, on the navigation menu level (outside of the router-outlet) I want to display only the links which are relevant for the current user, so I need to know which routes are protected by the guard. Guards / data / whatever is just a particular case of the problem.

Please do not stick to the example, I am searching for a common way to get the configuration set for a particular URL.

Is this anyhow possible?

答:
There is another way to get the data config for routes.  It involves knowing what the key property in the data object.

In your component you can get the data for that exact route with

```<code>this.route.snapshot.data['key']
</code>```

You could get the parent's data with

```<code>this.route.snapshot.parent.data['key']
</code>```

Or even the grandparent's data with

```<code>this.route.snapshot.parent.parent.data['key']
</code>```

Since you are using different keys on all your routes, that makes it more difficult.  In that case, you'd need to get a list of the keys and iterate over that:

```<code>let keys = Object.keys(this.route.snapshot.data);
keys.map(x => {
    console.log('key', x);
    console.log('data', this.route.snapshot.data[x]);
}
</code>```

Also, if you know your url segments you can even match on that to get the config for a particular path:

```<code>let configForRoute = this.router.config.find(x => x.path === this. route.snapshot.url.toString())

let dataForSegment = this.router.config.find(x => x.path === 'somePath').data['key']
</code>```

A crude solution to get all the data you need would look something like this:

```<code>obj = {};
getData(routeData){
  let keys = Object.keys(routeData);
  keys.map(x => this.obj[x] = routeData[x])
}

this.getData(this.route.snapshot.parent.parent.data);
this.getData(this.route.snapshot.parent.data);
this.getData(this.route.snapshot.data);
console.log(obj);
</code>```

Hopefully this helps get you on the right track to getting the data you need.

EDIT

I may have misunderstood the original question.

Since the addition of:

Why would I need that? Imagine I have a 50% of the URLs protected by
  some guard (e.g. only logged in users could go there) and other 50% is
  not protected (displayed for everybody). So, on the navigation menu
  level (outside of the router-outlet) I want to display only the links
  which are relevant for the current user, so I need to know which
  routes are protected by the guard. Guards / data / whatever is just a
  particular case of the problem.

The way I solved this problem of hiding links either unauthenticated users could see or hiding links unauthorized users could see is to create a function on my authentication service that can either check whether a user is authenticated or authorized. It is the same function that is also used by my guards on my routes.

For example, I may have a CheckPermissions guard on my routes with the route data data: { permissions:[permission1, permission2] }  Behind the scenes this guard uses a function on the auth service to check whether the user has permission using the listed permissions in the data field.  I can also use that same function from the auth service to hide links in my main menu with *ngIf="authSvc.CheckPermission(permission1) etc.  This way I'm not having to duplicate the logic anywhere.  Ultimately the API endpoints should be protected server side as well.

As for being able to give the router a url and get back the route that it matches without navigating to it, I can't find a documented way to do that.  Hope this is at least a little bit of help.

Body:
Given a URL, e.g. /path/path2/path3/123;sdf=df and a routes configuration:

{ path: 'path', data: { g: 'h' }, children: [
  { path: 'path2', data: { c: 'd' }, children: [
    { path: 'something', component: TestpageComponent, data: { a: 'b' } },
    { path: 'path3/create', component: TestpageComponent, data: { b: 'c' } },
    { path: 'path3/:id', component: TestpageComponent, data: { b: 'c' } },
  ] }
] },

What I need is to find an actual configuration for all the segments in order to get a result set of all data parameters on all levels (each segment of the url).

I can split the URL in the segments by e.g.

console.log(this.router.parseUrl(url));

or to be more precise

console.log(this.router.parseUrl(url).root.children['primary'].segments);

which will return

[{"path":"path","parameters":{}},{"path":"path2","parameters":{}},{"path":"and","parameters":{}},{"path":"123","parameters":{"sdf":"df"}}]

So, splitting the URL into segments is not a problem. However I need to get a configuration for each segment.

I can get the actual configuration for all the routes with

console.log(this.router.config);

I can go with the segments through the configuration tree and find out the branch I need, but it can cause troubles e.g. while resolving :id against create segment. So, I would like to use the router's way of resolving the configuration that if the inner router implementation changes I would not need to change mine.

Example: imagine I have a 50% of the URLs protected by some guard (e.g. only logged in users could go there) and other 50% is not protected (displayed for everybody). So, on the navigation menu level (outside of the router-outlet) I want to display only the links which are relevant for the current user, so I need to know which routes are protected by the guard. Guards / data / whatever is just a particular case of the problem.

Please do not stick to the example, I am searching for a common way to get the configuration set for a particular URL.

Is this anyhow possible?

Body:
There is another way to get the data config for routes.  It involves knowing what the key property in the data object.

In your component you can get the data for that exact route with

this.route.snapshot.data['key']

You could get the parent's data with

this.route.snapshot.parent.data['key']

Or even the grandparent's data with

this.route.snapshot.parent.parent.data['key']

Since you are using different keys on all your routes, that makes it more difficult.  In that case, you'd need to get a list of the keys and iterate over that:

let keys = Object.keys(this.route.snapshot.data);
keys.map(x => {
    console.log('key', x);
    console.log('data', this.route.snapshot.data[x]);
}

Also, if you know your url segments you can even match on that to get the config for a particular path:

let configForRoute = this.router.config.find(x => x.path === this. route.snapshot.url.toString())

let dataForSegment = this.router.config.find(x => x.path === 'somePath').data['key']

A crude solution to get all the data you need would look something like this:

obj = {};
getData(routeData){
  let keys = Object.keys(routeData);
  keys.map(x => this.obj[x] = routeData[x])
}

this.getData(this.route.snapshot.parent.parent.data);
this.getData(this.route.snapshot.parent.data);
this.getData(this.route.snapshot.data);
console.log(obj);

Hopefully this helps get you on the right track to getting the data you need.

EDIT

I may have misunderstood the original question.

Since the addition of:

Why would I need that? Imagine I have a 50% of the URLs protected by
  some guard (e.g. only logged in users could go there) and other 50% is
  not protected (displayed for everybody). So, on the navigation menu
  level (outside of the router-outlet) I want to display only the links
  which are relevant for the current user, so I need to know which
  routes are protected by the guard. Guards / data / whatever is just a
  particular case of the problem.

The way I solved this problem of hiding links either unauthenticated users could see or hiding links unauthorized users could see is to create a function on my authentication service that can either check whether a user is authenticated or authorized. It is the same function that is also used by my guards on my routes.

For example, I may have a CheckPermissions guard on my routes with the route data data: { permissions:[permission1, permission2] }  Behind the scenes this guard uses a function on the auth service to check whether the user has permission using the listed permissions in the data field.  I can also use that same function from the auth service to hide links in my main menu with *ngIf="authSvc.CheckPermission(permission1) etc.  This way I'm not having to duplicate the logic anywhere.  Ultimately the API endpoints should be protected server side as well.

As for being able to give the router a url and get back the route that it matches without navigating to it, I can't find a documented way to do that.  Hope this is at least a little bit of help.


问:
How to show datetime in Django in specific timezone?
I have a Django (v1.10.6) project that has some models with datetime fields, for example:

```<code>created_at = models.DateTimeField(auto_now_add=True)
</code>```

that are stored in PostgreSQL database without timezone information:

```<code>created_at timestamp without time zone NOT NULL
</code>```

postgresql.conf:

```<code>timezone = 'UTC'
</code>```

I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration:

```<code>TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True

SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'
</code>```

but when I write

```<code>{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}
</code>```

in templates, it still shows the date in UTC format.

Update:

I added the following middleware, but it didn't help:

```<code>class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        timezone.activate(pytz.timezone(settings.TIME_ZONE))
</code>```

Update 2:

It works the following way:

```<code>import pytz
from django.utils import timezone

timezone.is_naive(object.created_at)  # True
object.created_at.replace(tzinfo=timezone.utc)
</code>```

(forcing the date to be in UTC timezone and then passing it to template without localize filter) but I don't understand why Django still returns naive datetime when USE_TZ is set to True.

答:
```<code>{% load tz %}
{{ value|localtime }}
</code>```

https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#template-filters

Body:
I have a Django (v1.10.6) project that has some models with datetime fields, for example:

created_at = models.DateTimeField(auto_now_add=True)

that are stored in PostgreSQL database without timezone information:

created_at timestamp without time zone NOT NULL

postgresql.conf:

timezone = 'UTC'

I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration:

TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True

SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'

but when I write

{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}

in templates, it still shows the date in UTC format.

Update:

I added the following middleware, but it didn't help:

class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        timezone.activate(pytz.timezone(settings.TIME_ZONE))

Update 2:

It works the following way:

import pytz
from django.utils import timezone

timezone.is_naive(object.created_at)  # True
object.created_at.replace(tzinfo=timezone.utc)

(forcing the date to be in UTC timezone and then passing it to template without localize filter) but I don't understand why Django still returns naive datetime when USE_TZ is set to True.

Body:
{% load tz %}
{{ value|localtime }}

https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#template-filters


问:
Creating new database in DataGrip JetBrains
Anybody know how to create new database in DataGrip (database IDE from JetBrains)?
Could not find in DataGrip Help page.

答: In DataGrip 2017.1 UI for this was introduced


问:
In SQL Server select record which are completed without going to resolved state
I want to find records in SQL Server which are marked as completed but they do not go through resolved state.

Here is the example below.

```<code>tracking_id task_id task status   old_status new_status_id
1195372     140717  ABC  Complete NULL       NULL
1195373     140717  ABC  Complete NULL       New
1195374     140717  ABC  Complete New        Completed
1195380     140718  XYZ  Complete NULL       NULL
1195381     140718  XYZ  Complete NULL       New
1195382     140718  XYZ  Complete New        Completed
1195383     140719  PQR  Complete NULL       NULL
1195384     140719  PQR  Complete NULL       Resolved
1195385     140719  PQR  Complete Resolved   Completed
</code>```

Now in the table as task_id 140717 and 140718 is marked as Completed but it never went to state Resolved. Where as task_id 140719 is also marked completed but it goes through state Resolved. So I want to write SQL Query to just get record with task_id 140717 and 140718.

Any help with how to write query for this will be appreciated.

答:
```<code>select * from mytable
where new_status_id = 'Completed'
      and old_status <> 'Resolved'
</code>```

Body:
I want to find records in SQL Server which are marked as completed but they do not go through resolved state.

Here is the example below.

tracking_id task_id task status   old_status new_status_id
1195372     140717  ABC  Complete NULL       NULL
1195373     140717  ABC  Complete NULL       New
1195374     140717  ABC  Complete New        Completed
1195380     140718  XYZ  Complete NULL       NULL
1195381     140718  XYZ  Complete NULL       New
1195382     140718  XYZ  Complete New        Completed
1195383     140719  PQR  Complete NULL       NULL
1195384     140719  PQR  Complete NULL       Resolved
1195385     140719  PQR  Complete Resolved   Completed

Now in the table as task_id 140717 and 140718 is marked as Completed but it never went to state Resolved. Where as task_id 140719 is also marked completed but it goes through state Resolved. So I want to write SQL Query to just get record with task_id 140717 and 140718.

Any help with how to write query for this will be appreciated.


问:
[Python+Bokeh]: how to make a needle dial?
I need a needle dial, showing a real time value. This value changes the needle angle, not position.

Up to now all I could do is to use a ray() or annular_wedge() glyph, but this solution has a number of problems: previous lines are not deleted, after a few updates it freezes, artifacts. Completely unusable.

This is the stripped down code I am working on at the moment.

```<code>from bokeh.driving import linear
from bokeh.plotting import figure, curdoc
import random

p = figure(plot_width=400, plot_height=400,
       x_range=[0, 2], y_range=[0, 2],
       x_axis_type=None, y_axis_type=None)

@linear()
def update(step):
    ref_angle = random.random() * 2 * 3.14
    p.ray(x=[1], y=[1], length=0.5, angle=ref_angle, color="red", line_width=2)

curdoc().add_root(p)
curdoc().add_periodic_callback(update, 1000)
</code>```

As you can see I need to rotate the ray updating ref_angle.

Any idea?

答:
Instead of drawing a new ray on each update, you could make a ColumnDataSource object containing the ref_angle data, and then update that data.

The following code should just work if you have a bokeh server running already (in a different terminal run bokeh serve).

```<code>from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, curdoc
from bokeh.client import push_session
import random

p = figure(plot_width=400, plot_height=400,
           x_range=[0, 2], y_range=[0, 2],
           x_axis_type=None, y_axis_type=None)

source = ColumnDataSource(dict(ref_angle=[0]))
p.ray(x=1, y=1, length=0.5, angle='ref_angle', color="red",
      line_width=2, source=source)

# open a session to keep our local document in sync with server
session = push_session(curdoc())

def update():
    source.data.update(ref_angle=[random.random() * 2 * 3.14])

curdoc().add_periodic_callback(update, 1000)

session.show(p)  # open the document in a browser
session.loop_until_closed()  # run forever
</code>```

Body:
I need a needle dial, showing a real time value. This value changes the needle angle, not position.

Up to now all I could do is to use a ray() or annular_wedge() glyph, but this solution has a number of problems: previous lines are not deleted, after a few updates it freezes, artifacts. Completely unusable.

This is the stripped down code I am working on at the moment.

from bokeh.driving import linear
from bokeh.plotting import figure, curdoc
import random

p = figure(plot_width=400, plot_height=400,
       x_range=[0, 2], y_range=[0, 2],
       x_axis_type=None, y_axis_type=None)

@linear()
def update(step):
    ref_angle = random.random() * 2 * 3.14
    p.ray(x=[1], y=[1], length=0.5, angle=ref_angle, color="red", line_width=2)

curdoc().add_root(p)
curdoc().add_periodic_callback(update, 1000)

As you can see I need to rotate the ray updating ref_angle.

Any idea?

Body:
Instead of drawing a new ray on each update, you could make a ColumnDataSource object containing the ref_angle data, and then update that data.

The following code should just work if you have a bokeh server running already (in a different terminal run bokeh serve).

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, curdoc
from bokeh.client import push_session
import random

p = figure(plot_width=400, plot_height=400,
           x_range=[0, 2], y_range=[0, 2],
           x_axis_type=None, y_axis_type=None)

source = ColumnDataSource(dict(ref_angle=[0]))
p.ray(x=1, y=1, length=0.5, angle='ref_angle', color="red",
      line_width=2, source=source)

# open a session to keep our local document in sync with server
session = push_session(curdoc())

def update():
    source.data.update(ref_angle=[random.random() * 2 * 3.14])

curdoc().add_periodic_callback(update, 1000)

session.show(p)  # open the document in a browser
session.loop_until_closed()  # run forever


问:
What is the function of a commented out function and "comma splice"?
I've been dissecting a few bits of code over the past two weeks and I keep seeing some reoccurring themes... For example, what is the point of the following...?

```<code>class eventHandler(object):
    def create_event(self, event):
        """A general note here.

        :tagged param event:
            description
        :tagged type event:
            :class: `another class` # I do not understand the comma splices ( ` ).
        """
        # I do not understand why it ends here with no real purpose. Perhaps I'm not catching on to something.

    def next_event(self, event):
        ...
        # Continues with the same logic from above
</code>```

I have seen it in the Python Module "watchdog" as well as other modules and code snippets from the past that are scattered around on the internet. Is this just a sudo-code format for keeping notes? Were the functions discontinued? Am I just not understanding something in particular?

Edit:

Artagel brought up a good reference, I hadn't read deep enough PEP-0008.

答:
The backquotes probably have meaning to some sort of documentation generator that parses doc strings to produce nicely formatted documentation. They have no meaning in the Python language itself.

create_event is probably a method intended to be implemented by a subclass of eventHandler. The doc string alone is sufficient, syntactically, to serve as the body of the method. Without the doc string, you would need to use the pass statement to serve as a placeholder for a "real" body.

```<code>def create_event(self, event):
    pass
</code>```

Body:
I've been dissecting a few bits of code over the past two weeks and I keep seeing some reoccurring themes... For example, what is the point of the following...?

class eventHandler(object):
    def create_event(self, event):
        """A general note here.

        :tagged param event:
            description
        :tagged type event:
            :class: `another class` # I do not understand the comma splices ( ` ).
        """
        # I do not understand why it ends here with no real purpose. Perhaps I'm not catching on to something.

    def next_event(self, event):
        ...
        # Continues with the same logic from above

I have seen it in the Python Module "watchdog" as well as other modules and code snippets from the past that are scattered around on the internet. Is this just a sudo-code format for keeping notes? Were the functions discontinued? Am I just not understanding something in particular?

Edit:

Artagel brought up a good reference, I hadn't read deep enough PEP-0008.

Body:
The backquotes probably have meaning to some sort of documentation generator that parses doc strings to produce nicely formatted documentation. They have no meaning in the Python language itself.

create_event is probably a method intended to be implemented by a subclass of eventHandler. The doc string alone is sufficient, syntactically, to serve as the body of the method. Without the doc string, you would need to use the pass statement to serve as a placeholder for a "real" body.

def create_event(self, event):
    pass


问:
Reliable access to locked remote computer
What I have: I have Windows 7 on my home PC.

What I'm trying to do: I'm trying to keep TeamViewer running at home so I can always get to my home computer.  The other day it got completely messed up and would not let me connect but everything else on the PC was just fine.

Items I've looked at:

I looked at this thread and it does not seem to apply to what I need:

Is it possible to start Teamviewer, to accept connections, from commandline?

... but it does not appear to be what I'm looking for.

I have looked at this:

https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes

... and to test the script at the above URL, I stopped a service on my computer and pointed the above vbs script to that service and the vbs script will not restart that service, so that's not working.

What's happening:

From time to time on my home computer, TeamViewer hangs or gets messed up in some way and I cannot connect to my home computer.  The last time this happened, the TeamViewer UI was still running but there was a little red dot next to the tray icon and the id numbers and password were blank in the UI so I had to right click and kill it and restart the computer and all was OK.

What I'd like to do:

Is there a way I can run some kind of script or something that will completely kill all TeamViewer processes and services and restart it completely?  I'd like to schedule this type of activity once an hour so I can be assured of pretty much always being able to get into my home computer or else just wait an hour and it should be back up and available?

I have 20 years in IT with networking background, databases, GUI development, website development, hardware and software installation but no experience in brain surgery.  I've given it a good try but am now asking for some help.

Thanks.

答:
I think that task scheduler, taskkill and batch script is your friend here.
create a batch file to stop any current team viewer process and then restart it.
crate a batch file something like:

```<code>taskkill /IM TeamViewer.exe
start "" "C:\Program Files (x86)\TeamViewer\TeamViewer.exe"
</code>```

(substitute the path to TeamViewer.exe on your own machine).
Then create an hourly scheduled task to run the script using the highest privileges (using Windows Task Scheduler).

Lookup taskkill for more info on killing tasks from the command line.

Just to add that you'll have to have the PC in a associated in your teamviewer account in a group (e.g. My Computers) and use the same account to connect - otherwise the password change on restart will prevent you connecting (you won't know the new password).

Body:
I think that task scheduler, taskkill and batch script is your friend here.
create a batch file to stop any current team viewer process and then restart it.
crate a batch file something like:

taskkill /IM TeamViewer.exe
start "" "C:\Program Files (x86)\TeamViewer\TeamViewer.exe"

(substitute the path to TeamViewer.exe on your own machine).
Then create an hourly scheduled task to run the script using the highest privileges (using Windows Task Scheduler).

Lookup taskkill for more info on killing tasks from the command line.

Just to add that you'll have to have the PC in a associated in your teamviewer account in a group (e.g. My Computers) and use the same account to connect - otherwise the password change on restart will prevent you connecting (you won't know the new password).


问:
Neural Network learning to hover. Time delay?
I'm diving into machine learning with neural networks and after reading some theory and looking into torch I'd now like to use a neural network to learn how much thrust a simple helicopter with a unknown model needs to generate to hover in place at a reference height.

I have a control background and I know that one usually wouldn't use neural networks or machine learning in general for this, however I thought this would be a good first task to do.

I figured that all I needed was a simple linear regression (in NN form) to learn the function that maps measured height to thrust (producing exactly the right amount of thrust to counteract gravity at reference height).

But this already seems a bit complicated to do. Assume that I have a simple dynamics simulator and that I'm given a height measurement every fs Hz. I do a forward pass on my model (see model code below) to calculate the thrust for the model. So far so good. However the effect will not be instantly visible, so using the current measurement to also perform a forward and backward pass on the loss function seems the wrong thing to do. Or is it?

So ultimately the question is: Can I solve the stated problem with the simple linear regression that I proposed or do I need something more complex to capture the "response time" of the model.

```<code>require 'torch'
require 'nn'

local model = nn.Sequential()
model:add(nn.Linear(1, 1)) -- Simple linear regression with one input (measured height) and one output (thrust)

local criterion = nn.MSECriterion -- Simple mean squared error loss function.

heigh_ref = 1

function height_measurement_callback(height_meas)
    local thrust = model:forward(height_meas)

    criterion:forward(height_meas, heigh_ref) -- ??
    local grad = criterion:backward(height_meas, heigh_ref) -- ??
    model:backward(height_meas, grad) -- ??

    return thrust
end
</code>```

答:
Problem: Set a particular height h_desired and have the program find corresponding thrust value. Assuming that there is one to one correspondence between the thrust and the height.

Rational solution: Minimize the h_desired - h_current by adjusting the thrust based on current difference between heights.

Machine learning solution: Have a bunch of measurements, run regression on them, try to use obtained model to predict new values, verify prediction, add actual values to the training set.

Assuming that the "forward path of the NN" is the calculation of deviations of predicted values from the actual ones: delta_i=(y_predicted_i - y_observed_i), and the backward pass is the calculation of k and b in y_predicted_i = k * x_i + b, there's no need to separate them. It is actually difficult to me to think of anything reasonable to do in-between those operations.

Now using the updated model you predict new value of thrust, that should bring you to desired height, and then you make new measurement, you set new thrust value and see which height value it corresponds to. Obviously, you must wait till the helicopter stops moving before putting new thrust-height pair to the training data and doing next iteration of linear regression. This is not so much about "Neural network model" but rather about the data acquisition process. You should not confuse them together. You must always finish measurement before adding the data to the experience of the model.

Body:
I'm diving into machine learning with neural networks and after reading some theory and looking into torch I'd now like to use a neural network to learn how much thrust a simple helicopter with a unknown model needs to generate to hover in place at a reference height.

I have a control background and I know that one usually wouldn't use neural networks or machine learning in general for this, however I thought this would be a good first task to do.

I figured that all I needed was a simple linear regression (in NN form) to learn the function that maps measured height to thrust (producing exactly the right amount of thrust to counteract gravity at reference height).

But this already seems a bit complicated to do. Assume that I have a simple dynamics simulator and that I'm given a height measurement every fs Hz. I do a forward pass on my model (see model code below) to calculate the thrust for the model. So far so good. However the effect will not be instantly visible, so using the current measurement to also perform a forward and backward pass on the loss function seems the wrong thing to do. Or is it?

So ultimately the question is: Can I solve the stated problem with the simple linear regression that I proposed or do I need something more complex to capture the "response time" of the model.

require 'torch'
require 'nn'

local model = nn.Sequential()
model:add(nn.Linear(1, 1)) -- Simple linear regression with one input (measured height) and one output (thrust)

local criterion = nn.MSECriterion -- Simple mean squared error loss function.

heigh_ref = 1

function height_measurement_callback(height_meas)
    local thrust = model:forward(height_meas)

    criterion:forward(height_meas, heigh_ref) -- ??
    local grad = criterion:backward(height_meas, heigh_ref) -- ??
    model:backward(height_meas, grad) -- ??

    return thrust
end


问:
Is there any way to show less decimals than the specified accuracy in Odoo 8 views?
I am trying to manage the following behaviour in Odoo 8:

Set a product price of 5 decimals. For that, I set decimal accuracy of Product Price to 5.

In sale.order view, show only 3 decimals, but calculate the subtotal of the line taking into account the 5 decimals. For this step, I am modifying the view to put this on price_unit field:

```<code><xpath expr="//field[@name='order_line']/tree/field[@name='price_unit']" position="replace">
    <field name="price_unit" digits="(16,3)"/>
</xpath>
</code>```

But that digits attribute is altering the result.

Example:

I store a product with price 1,00123. I add 5 units of it on a sale
  order. If I do not use digits in the XML view, the subtotal is 5,01.
  Because 1,00123 * 5 = 5,00615, rounding this to Account Accuracy (2
  decimals) gives 5,01. But if I use digits in XML view, the subtotal is
  5,00. Because 1,001 * 5 = 5,005, rounding this to Account Accuracy (2
  decimals) gives 5,00.

In fact, I show with logger the line.price_unit value in
  sale.order.line method _calc_line_base_price. With digits in XML
  view, line.price_unit values 1,001, without it, it gives 1,00123.

Can anyone tell me how could I show 3 decimals for price unit in XML
view without altering the decimal accuracy of 5 decimals? It must be
done only for visualization.

答: If the xml digits are indeed taken into account for calculations (can't verify that at the moment), you can always have two fields - hidden one for calculations with maximum accuracy, and another for display purposes, which displays already calculated numbers with specified accuracy.

Body:
I am trying to manage the following behaviour in Odoo 8:

Set a product price of 5 decimals. For that, I set decimal accuracy of Product Price to 5.

In sale.order view, show only 3 decimals, but calculate the subtotal of the line taking into account the 5 decimals. For this step, I am modifying the view to put this on price_unit field:

<xpath expr="//field[@name='order_line']/tree/field[@name='price_unit']" position="replace">
    <field name="price_unit" digits="(16,3)"/>
</xpath>

But that digits attribute is altering the result.

Example:

I store a product with price 1,00123. I add 5 units of it on a sale
  order. If I do not use digits in the XML view, the subtotal is 5,01.
  Because 1,00123 * 5 = 5,00615, rounding this to Account Accuracy (2
  decimals) gives 5,01. But if I use digits in XML view, the subtotal is
  5,00. Because 1,001 * 5 = 5,005, rounding this to Account Accuracy (2
  decimals) gives 5,00.

In fact, I show with logger the line.price_unit value in
  sale.order.line method _calc_line_base_price. With digits in XML
  view, line.price_unit values 1,001, without it, it gives 1,00123.

Can anyone tell me how could I show 3 decimals for price unit in XML
view without altering the decimal accuracy of 5 decimals? It must be
done only for visualization.


问:
Oracle SQL - Before-Insert Trigger not firing
I'm new to Oracle SQL and today I wanted to try a sample trigger that does the same as the 'UNIQUE' statement. So the trigger should check before inserting if a specific attribute ('cityid') is already in the dataset.

The problem is that my trigger doesn't fire! Compilation works fine, but none of the commands are working.

Here is it:

```<code>CREATE OR REPLACE TRIGGER check_cityid
BEFORE INSERT
    ON city
    FOR EACH ROW
BEGIN

    IF :old.cityid <> :new.cityid THEN
        insert into city (cityid, name, country, province, population, latitude, longitude) values (:new.cityid, :new.name, :new.country, :new.province, :new.population, :new.latitude, :new.longitude);
        DBMS_OUTPUT.PUT_LINE('OK');
    ELSE
        DBMS_OUTPUT.PUT_LINE('The attribute CITYID is already present!');
    END IF;

END;
/
</code>```

And here is my table 'city' with NAME+COUNTRY+PROVINCE as primary key:

```<code>SQL> describe city;
 Name                                                  Null?    Typ
 ----------------------------------------------------- -------- -------
 NAME                                                  NOT NULL VARCHAR2(35)
 COUNTRY                                               NOT NULL VARCHAR2(4)
 PROVINCE                                              NOT NULL VARCHAR2(32)
 POPULATION                                                     NUMBER
 LONGITUDE                                                      NUMBER
 LATITUDE                                                       NUMBER
 CITYID                                                         NUMBER(38)
</code>```

Btw, I know that the PK should refer to 'cityid', but this is just an exercise ...

Anyone knows how to fix this?

Thanks in advance.

答:
Well, I found an appropriate solution:

```<code>CREATE OR REPLACE TRIGGER check_cityid
BEFORE INSERT
    ON city
    FOR EACH ROW
DECLARE
    cityid_new city.cityid%TYPE := 0;
BEGIN

    select cityid into cityid_new from city where cityid = :new.cityid;

    IF cityid_new = :new.cityid THEN
        raise_application_error(-20001, 'FEHLER: Diese CITYID ist bereits vorhanden!');
    END IF;

EXCEPTION

    WHEN NO_DATA_FOUND THEN
    BEGIN
        DBMS_OUTPUT.PUT_LINE('CITYID check OK.');
    END;

END;
/
</code>```

If a row alreday exists, I correctly get the error -20001. And if there's no such CITYID, the trigger falls into the EXCEPTION, but does nothing.

Many thanks to all who helped me and for showing me the possibilites!

Body:
I'm new to Oracle SQL and today I wanted to try a sample trigger that does the same as the 'UNIQUE' statement. So the trigger should check before inserting if a specific attribute ('cityid') is already in the dataset.

The problem is that my trigger doesn't fire! Compilation works fine, but none of the commands are working.

Here is it:

CREATE OR REPLACE TRIGGER check_cityid
BEFORE INSERT
    ON city
    FOR EACH ROW
BEGIN

    IF :old.cityid <> :new.cityid THEN
        insert into city (cityid, name, country, province, population, latitude, longitude) values (:new.cityid, :new.name, :new.country, :new.province, :new.population, :new.latitude, :new.longitude);
        DBMS_OUTPUT.PUT_LINE('OK');
    ELSE
        DBMS_OUTPUT.PUT_LINE('The attribute CITYID is already present!');
    END IF;

END;
/

And here is my table 'city' with NAME+COUNTRY+PROVINCE as primary key:

SQL> describe city;
 Name                                                  Null?    Typ
 ----------------------------------------------------- -------- -------
 NAME                                                  NOT NULL VARCHAR2(35)
 COUNTRY                                               NOT NULL VARCHAR2(4)
 PROVINCE                                              NOT NULL VARCHAR2(32)
 POPULATION                                                     NUMBER
 LONGITUDE                                                      NUMBER
 LATITUDE                                                       NUMBER
 CITYID                                                         NUMBER(38)

Btw, I know that the PK should refer to 'cityid', but this is just an exercise ...

Anyone knows how to fix this?

Thanks in advance.

Body:
Well, I found an appropriate solution:

CREATE OR REPLACE TRIGGER check_cityid
BEFORE INSERT
    ON city
    FOR EACH ROW
DECLARE
    cityid_new city.cityid%TYPE := 0;
BEGIN

    select cityid into cityid_new from city where cityid = :new.cityid;

    IF cityid_new = :new.cityid THEN
        raise_application_error(-20001, 'FEHLER: Diese CITYID ist bereits vorhanden!');
    END IF;

EXCEPTION

    WHEN NO_DATA_FOUND THEN
    BEGIN
        DBMS_OUTPUT.PUT_LINE('CITYID check OK.');
    END;

END;
/

If a row alreday exists, I correctly get the error -20001. And if there's no such CITYID, the trigger falls into the EXCEPTION, but does nothing.

Many thanks to all who helped me and for showing me the possibilites!


答:
use NOT EXISTS like so:

```<code>select *
from yourtable t
where status = 'Complete'
and not exists
     (select top 1 1
      from yourtable o
      where o.task_id = t.task_id
      and o.old_status = 'Resolved')
</code>```

Title: In SQL Server select record which are completed without going to resolved state

Body:
use NOT EXISTS like so:

select *
from yourtable t
where status = 'Complete'
and not exists
     (select top 1 1
      from yourtable o
      where o.task_id = t.task_id
      and o.old_status = 'Resolved')


问:
How to append value to an array keeping old value intact in Javascript?
Google visualization API requires arrays like this:

```<code>var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);
</code>```

I have separately array of columns

```<code>var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
</code>```

for values

```<code>var values = [8.94, 10.49, 19.30, 21.45];
</code>```

and for colors

```<code>var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];
</code>```

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

答:
ES6 solution using reduce function

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
var values = [8.94, 10.49, 19.30, 21.45];
var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

// Reduce all arrays to one vlaue
var result  = columns.reduce((acc, init, i) => {
    acc.push([init, values[i], styles[i]])
    return acc
}, [])

var out = [
         ['Element', 'Density', { role: 'style' }],
         ...result
      ]

console.log(out)```

Body:
Google visualization API requires arrays like this:

var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);

I have separately array of columns

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];

for values

var values = [8.94, 10.49, 19.30, 21.45];

and for colors

var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.


问:
Update Style/Remove Attribute
I need remove style attribute of a div

Line 85
https://github.com/PolymerElements/app-layout/blob/master/app-toolbar/app-toolbar.html

```<code>::content > [condensed-title] {
        pointer-events: none;
        @apply(--layout-flex)*;
      }
</code>```

*(I don't wanna apply flexbox to [condensed-title] in a espefic head component I had made)

Line 133 https://github.com/PolymerElements/iron-flex-layout/blob/master/iron-flex-layout.html

```<code>    --layout-flex: {
  -ms-flex: 1 1 0.000000001px;
  -webkit-flex: 1;
  flex: 1;
  -webkit-flex-basis: 0.000000001px;
  flex-basis: 0.000000001px;
};
</code>```

My code

```<code><app-toolbar>
        <div class="logo-title">
          <iron-icon icon="custom-icons:casinha"></iron-icon>
        </div>
        <div id="outAlert" condensed-title>
          <paper-icon-button icon="card-membership"></paper-icon-button>
        </div>
        <div class="sublogo-title">
          <h4>Sublogo</h4>
        </div>
      </app-toolbar>
</code>```

答:
I solved problem using following code:</p>

```<code>      #outAlert{
        @apply(--layout-flex-none);
      }
</code>```

Title: Update Style/Remove Attribute

Body:
I need remove style attribute of a div

Line 85
https://github.com/PolymerElements/app-layout/blob/master/app-toolbar/app-toolbar.html

::content > [condensed-title] {
        pointer-events: none;
        @apply(--layout-flex)*;
      }

*(I don't wanna apply flexbox to [condensed-title] in a espefic head component I had made)

Line 133 https://github.com/PolymerElements/iron-flex-layout/blob/master/iron-flex-layout.html

    --layout-flex: {
  -ms-flex: 1 1 0.000000001px;
  -webkit-flex: 1;
  flex: 1;
  -webkit-flex-basis: 0.000000001px;
  flex-basis: 0.000000001px;
};

My code

<app-toolbar>

          <iron-icon icon="custom-icons:casinha"></iron-icon>

          <paper-icon-button icon="card-membership"></paper-icon-button>

Sublogo

      </app-toolbar>

Body:
I solved problem using following code:

      #outAlert{
        @apply(--layout-flex-none);
      }


答:
If the old_status_id is not always 'resolved' for 'completed' then using not exists():

```<code>select *
from t
where new_status_id = 'completed'
  and not exists (
    select 1
    from t as i
    where i.task_id = t.task_id
      and i.new_status_id = 'resolved'
  )
</code>```

Body:
If the old_status_id is not always 'resolved' for 'completed' then using not exists():

select *
from t
where new_status_id = 'completed'
  and not exists (
    select 1
    from t as i
    where i.task_id = t.task_id
      and i.new_status_id = 'resolved'
  )


问:
How to avoid losing event on input after toggle visivility?
I have an input which should keep the focus, because of program requirements. While using the software the input might be hidden at some point but when showing up again it should recover the focus, but it doesn't. Still if you check the binded events on the input you can see it did not actually lost the event.

There's a simple jsfiddle showing this behaviour: https://jsfiddle.net/5puu261v/

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('#barcode').toggle()">Toggle input</button>
<input type="text" id="barcode" /></code>```

It would be appreciated if I could fix or avoid it without binding the event back again.

Edit:

The point is: Why does the input doesn't get focused, after being toggled, when clicking on any other element (as the button that makes it visible again)?

答:
Updated fiddle.

You could add the .focus() to the click event so every time the button clicked the input will be focused, like :

```<code>$('button').click(function(){
    $('#barcode').toggle().focus();
});
</code>```

HTML :

```<code><button>Toggle input</button>
<input type="text" id="barcode" />
</code>```

Hope this helps.

$('#barcode').focus()

$('#barcode').focusout(function(){
    $(this).focus();
});

$('button').click(function(){
    $('#barcode').toggle().focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Toggle input</button>
<input type="text" id="barcode" /></code>```

Body:
I have an input which should keep the focus, because of program requirements. While using the software the input might be hidden at some point but when showing up again it should recover the focus, but it doesn't. Still if you check the binded events on the input you can see it did not actually lost the event.

There's a simple jsfiddle showing this behaviour: https://jsfiddle.net/5puu261v/

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});

<button onclick="$('#barcode').toggle()">Toggle input</button>
<input type="text" id="barcode" />

It would be appreciated if I could fix or avoid it without binding the event back again.

Edit:

The point is: Why does the input doesn't get focused, after being toggled, when clicking on any other element (as the button that makes it visible again)?

Body:
Updated fiddle.

You could add the .focus() to the click event so every time the button clicked the input will be focused, like :

$('button').click(function(){
    $('#barcode').toggle().focus();
});

HTML :

<button>Toggle input</button>
<input type="text" id="barcode" />

Hope this helps.

$('#barcode').focus()

$('#barcode').focusout(function(){
    $(this).focus();
});

$('button').click(function(){
    $('#barcode').toggle().focus();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Toggle input</button>
<input type="text" id="barcode" />