问:
Configuring Jackson for Spring Integration
Another question for the same project once mentioned in this question. We have now developed quite a few routes to serve a REST/JSON web service from a composite back-end.

The endpoint is an <int-http:inbound-gateway> that performs implicit JSON to object from the request and object to JSON for the response.
Now we really need to tune Jackson to solve a few issues with the JSON we deliver in the responses. Nothing fancy or unusual: mostly, serve dates as String instead of Timestamps, removing null attributes, registering the JSR-310 module.

For the other modules in the platform, we use Java DSL with a @Configuration class and a bean like this:

```<code>@Configuration
public class ControllerConfig {
  @Bean
  @Primary
  public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    return objectMapper;
  }
}
</code>```

But it seems to have no effect on Spring Integration. I have also tried Spring Boot configuration:

```<code>spring.jackson.default-property-inclusion=NON_NULL
</code>```

and it does not work either. I read very carefully this thread and my understanding from Artem Bilan's answer is that indeed, Spring Integration does not consider the Spring Boot configuration.

So... I'm feeling stupid: what is the canonical way of configuring Jackson globally for Spring Integration ?

jackson 2.8.7 / spring 4.3.7 / spring boot 1.5.2 / spring integration 4.3.8

答:
A big thank you to @Artem Bilan for answering my question promptly and showing me the way to go (after I fought for two days on my own).

Customizing the HttpMessageConverter is indeed the good direction. The code below is not the finest I've written but it does the job nicely. I have added this stanza to our @Configuration bean:

```<code>@Bean
public List<HttpMessageConverter<?>> customMessageConverters() {
  MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new JavaTimeModule());
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  objectMapper.setSerializationInclusion(Include.NON_NULL);
  jsonConverter.setObjectMapper(objectMapper);

  List<HttpMessageConverter<?>> result = new ArrayList<HttpMessageConverter<?>>();
  result.add(jsonConverter);

  return result;
}
</code>```

Then, the magic suggested by Artem Bilan works nicely: we have just added

```<code>message-converters="customMessageConverters"
</code>```

to our inbound-gateway.

I hope this helps someone, someday. My apologies for any typo but all this is coded in a bank where posting to StackOverflow is blocked, hence no copy and paste...

Body:
Another question for the same project once mentioned in this question. We have now developed quite a few routes to serve a REST/JSON web service from a composite back-end.

The endpoint is an <int-http:inbound-gateway> that performs implicit JSON to object from the request and object to JSON for the response.
Now we really need to tune Jackson to solve a few issues with the JSON we deliver in the responses. Nothing fancy or unusual: mostly, serve dates as String instead of Timestamps, removing null attributes, registering the JSR-310 module.

For the other modules in the platform, we use Java DSL with a @Configuration class and a bean like this:

@Configuration
public class ControllerConfig {
  @Bean
  @Primary
  public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    return objectMapper;
  }
}

But it seems to have no effect on Spring Integration. I have also tried Spring Boot configuration:

spring.jackson.default-property-inclusion=NON_NULL

and it does not work either. I read very carefully this thread and my understanding from Artem Bilan's answer is that indeed, Spring Integration does not consider the Spring Boot configuration.

So... I'm feeling stupid: what is the canonical way of configuring Jackson globally for Spring Integration ?

jackson 2.8.7 / spring 4.3.7 / spring boot 1.5.2 / spring integration 4.3.8

Body:
A big thank you to @Artem Bilan for answering my question promptly and showing me the way to go (after I fought for two days on my own).

Customizing the HttpMessageConverter is indeed the good direction. The code below is not the finest I've written but it does the job nicely. I have added this stanza to our @Configuration bean:

@Bean
public List<HttpMessageConverter<?>> customMessageConverters() {
  MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new JavaTimeModule());
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  objectMapper.setSerializationInclusion(Include.NON_NULL);
  jsonConverter.setObjectMapper(objectMapper);

  List<HttpMessageConverter<?>> result = new ArrayList<HttpMessageConverter<?>>();
  result.add(jsonConverter);

  return result;
}

Then, the magic suggested by Artem Bilan works nicely: we have just added

message-converters="customMessageConverters"

to our inbound-gateway.

I hope this helps someone, someday. My apologies for any typo but all this is coded in a bank where posting to StackOverflow is blocked, hence no copy and paste...


来源: stackexchange

问:
List of possible combinations of characters with OR statement
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?  </p>

```<code>items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
</code>```

答:
itertools.product is suitable for representing these distinct groups in a way which generalizes well. Just let the exclusive elements belong to the same iterable passed to the Cartesian product.

For instance, to get a list with the items you're looking for,

```<code>from itertools import chain, permutations, product

list(chain.from_iterable(map(permutations, product(*items, 'df'))))

# [('a', 'b', 'c', 'd'),
#  ('a', 'b', 'd', 'c'),
#  ('a', 'c', 'b', 'd'),
#  ('a', 'c', 'd', 'b'),
#  ('a', 'd', 'b', 'c'),
#  ('a', 'd', 'c', 'b'),
#  ('b', 'a', 'c', 'd'),
#  ('b', 'a', 'd', 'c'),
#  ('b', 'c', 'a', 'd'),
#  ('b', 'c', 'd', 'a'),
#  ('b', 'd', 'a', 'c'),
#  ('b', 'd', 'c', 'a'),
#  ('c', 'a', 'b', 'd'),
#  ('c', 'a', 'd', 'b'),
#  ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?

items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

Body:
itertools.product is suitable for representing these distinct groups in a way which generalizes well. Just let the exclusive elements belong to the same iterable passed to the Cartesian product.

For instance, to get a list with the items you're looking for,

from itertools import chain, permutations, product

list(chain.from_iterable(map(permutations, product(*items, 'df'))))

# [('a', 'b', 'c', 'd'),
#  ('a', 'b', 'd', 'c'),
#  ('a', 'c', 'b', 'd'),
#  ('a', 'c', 'd', 'b'),
#  ('a', 'd', 'b', 'c'),
#  ('a', 'd', 'c', 'b'),
#  ('b', 'a', 'c', 'd'),
#  ('b', 'a', 'd', 'c'),
#  ('b', 'c', 'a', 'd'),
#  ('b', 'c', 'd', 'a'),
#  ('b', 'd', 'a', 'c'),
#  ('b', 'd', 'c', 'a'),
#  ('c', 'a', 'b', 'd'),
#  ('c', 'a', 'd', 'b'),
#  ...


问:
R interactive plot?
How can a user interactively change one aspect (e.g., orientation or length of a line) on a 2D plot?</p>

答:
latticist and playwith are offering the interactive functionality for R's statistical plots.

For modifying specific details you can save the graph in SVG format and edit it in inkscape.

ContentLicense: CC BY-SA 2.5

Title: R interactive plot?


问:
Exclude nodes based on other relationship
I am trying to get a result of Users and Accounts that are simultaneously :USER and :ADMIN of Accounts that does not have the :PARENT relation to or from any other account.

Background:

This gives me all accounts that are neither parent accounts nor child accounts:

```<code>MATCH (a: Account)
WHERE NOT (a)-[:PARENT]-()
RETURN a
</code>```

This gives me all accounts where all Users also have the :ADMIN relation to an Account:

```<code>MATCH (u)-[:ADMIN]-(a)-[:USER]-(u)
RETURN a, u
</code>```

Problem:

When trying to combine the two, I still get Accounts with :PARENT relations in my results:

```<code>MATCH (u)-[:ADMIN]-(a)-[:USER]-(u)
WHERE NOT (a)-[:PARENT]-()
RETURN u, a
</code>```

It's like the WHERE on row 2 here does not have any effect. It is possible that the unwanted Accounts show up because they match the first MATCH but from here I would like to exclude all Accounts that has any :PARENT relation.

What I have tried

I have been trying using OPTIONAL MATCH, the WITH keyword and matching in different orders and variations for the criteria. The three snippets above is the closest I can get to describing where it goes wrong.

Another way to approach this I imagine could be

```<code>MATCH (a: Account)
OPTIONAL MATCH (a)-[p:PARENT]-()
WITH a, p
WHERE p IS NULL
OPTIONAL MATCH (u)-[relu: USER]-(a)-[rela: ADMIN]-(u)
with u, a, relu, rela
WHERE NOT relu IS NULL
AND NOT rela IS NULL
RETURN a, u
</code>```

Here I get too few results. It's missing several accounts that are not having any :PARENT relation but still has Users with both :USER and :ADMIN relations to the account.

Seems like I missed some vital point of how the queries are aggregated.

答:
(This answer is work-in-progress.)

I created a small example data set:

```<code>CREATE
  (a:Account {name: 'acc1'}),
  (u:User {name: 'user1'}),
  (u)-[:ADMIN]->(a),
  (u)-[:USER]->(a)
</code>```

This query seems to work. The only difference from you 3rd query is the addition of :Account.

```<code>MATCH (u)-[:ADMIN]-(a:Account)-[:USER]-(u)
WHERE NOT (a)-[:PARENT]-()
RETURN u, a
</code>```

Body:
I am trying to get a result of Users and Accounts that are simultaneously :USER and :ADMIN of Accounts that does not have the :PARENT relation to or from any other account.

Background:

This gives me all accounts that are neither parent accounts nor child accounts:

MATCH (a: Account)
WHERE NOT (a)-[:PARENT]-()
RETURN a

This gives me all accounts where all Users also have the :ADMIN relation to an Account:

MATCH (u)-[:ADMIN]-(a)-[:USER]-(u)
RETURN a, u

Problem:

When trying to combine the two, I still get Accounts with :PARENT relations in my results:

MATCH (u)-[:ADMIN]-(a)-[:USER]-(u)
WHERE NOT (a)-[:PARENT]-()
RETURN u, a

It's like the WHERE on row 2 here does not have any effect. It is possible that the unwanted Accounts show up because they match the first MATCH but from here I would like to exclude all Accounts that has any :PARENT relation.

What I have tried

I have been trying using OPTIONAL MATCH, the WITH keyword and matching in different orders and variations for the criteria. The three snippets above is the closest I can get to describing where it goes wrong.

Another way to approach this I imagine could be

MATCH (a: Account)
OPTIONAL MATCH (a)-[p:PARENT]-()
WITH a, p
WHERE p IS NULL
OPTIONAL MATCH (u)-[relu: USER]-(a)-[rela: ADMIN]-(u)
with u, a, relu, rela
WHERE NOT relu IS NULL
AND NOT rela IS NULL
RETURN a, u

Here I get too few results. It's missing several accounts that are not having any :PARENT relation but still has Users with both :USER and :ADMIN relations to the account.

Seems like I missed some vital point of how the queries are aggregated.

Body:
(This answer is work-in-progress.)

I created a small example data set:

CREATE
  (a:Account {name: 'acc1'}),
  (u:User {name: 'user1'}),
  (u)-[:ADMIN]->(a),
  (u)-[:USER]->(a)

This query seems to work. The only difference from you 3rd query is the addition of :Account.

MATCH (u)-[:ADMIN]-(a:Account)-[:USER]-(u)
WHERE NOT (a)-[:PARENT]-()
RETURN u, a


问:
Counting all entries with KSQL
Is it possible to use KSQL to not only count entries of a specific column via GROUP BY but instead get an aggregate over all the entries that stream through the application?

I'm searching for something like this:

```<code>| Count all | Count id1 | count id2 |
| ---245----|----150----|----95-----|
</code>```

Or more like this in KSQL:

```<code>[some timestamp] | Count all | 245
[some timestamp] | Count id1 | 150
[some timestamp] | Count id2 | 95
.
.
.
</code>```

Thank you

- Tim

答:
You cannot have both counts for the all and count for each key in the same query. You can have two queries here, one for counting each value in the given column and another for counting all values in the given column.
Let's assume you have a stream with two columns, col1 and col2.
To count each value in col1 with infinite window size you can use the following query:

```<code>SELECT col1, count(*) FROM mystream1 GROUP BY col1;
</code>```

To count all the rows you need to write two queries since KSQL always needs GROUP BY clause for aggregation. First you create a new column with constant value and then you can count the values in new column and since it is a constant, the count will represent the count of all rows. Here is an example:

```<code>CREATE STREAM mystream2 AS SELECT 1 AS col3 FROM mystream1;
SELECT col3, count(*) FROM mystream2 GROUP BY col3;
</code>```

Title: Counting all entries with KSQL

Body:
Is it possible to use KSQL to not only count entries of a specific column via GROUP BY but instead get an aggregate over all the entries that stream through the application?

I'm searching for something like this:

| Count all | Count id1 | count id2 |
| ---245----|----150----|----95-----|

Or more like this in KSQL:

[some timestamp] | Count all | 245
[some timestamp] | Count id1 | 150
[some timestamp] | Count id2 | 95
.
.
.

Thank you

- Tim

Body:
You cannot have both counts for the all and count for each key in the same query. You can have two queries here, one for counting each value in the given column and another for counting all values in the given column.
Let's assume you have a stream with two columns, col1 and col2.
To count each value in col1 with infinite window size you can use the following query:

SELECT col1, count(*) FROM mystream1 GROUP BY col1;

To count all the rows you need to write two queries since KSQL always needs GROUP BY clause for aggregation. First you create a new column with constant value and then you can count the values in new column and since it is a constant, the count will represent the count of all rows. Here is an example:

CREATE STREAM mystream2 AS SELECT 1 AS col3 FROM mystream1;
SELECT col3, count(*) FROM mystream2 GROUP BY col3;


问:
Creating An In-Game Web Browser on iPhone
In my game, I'd like to have a kinda of "message of the day" feature. Basically, when I hit the "message of the day" button in themain menu, it would open up a browser view in-game. When the user is done, he taps a "close" button and the view disappears, returning him to the game menu.

So, is it possible to dynamically create a browser view? If yes, how?

答:
Sounds like a job for UIWebView :-)

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIWebView_Class/Reference/Reference.html


问:
easier way to navigate between vim split panes
I am using NERDTree on vim and usually open files with i

Is there an easy way to switch between different panes? Currently I use CTRL+W+W to move from one pane to another.

答:
I know this is an old question, but I have a perfect way. Using the number of the split.

split_number C-w C-w

The panes are numbered from top-left to bottom-right with the first one getting the number 1.

for example to go to split number 3 do this 3 C-w C-w, press Ctrl-w twice.

ContentLicense: CC BY-SA 4.0


问:
Finding Groovy on Mac OS after installing it via SDKMAN
I am using Mac OS and have installed groovy via SDKMAN. It says that groovy is installed however I do not know where it has been installed or how to open it and if I need to install an environment to open it in. Any help would be hugely appreciated.</p>

答:
When you install groovy (or other tool) via sdkman, it defines an environment variable: _TOOL_HOME in this particular case it will be GROOVY_HOME.

Run:

```<code>echo $GROOVY_HOME
</code>```

in terminal and you will know the place where it's installed.

Body:
When you install groovy (or other tool) via sdkman, it defines an environment variable: _TOOL_HOME in this particular case it will be GROOVY_HOME.

Run:

echo $GROOVY_HOME

in terminal and you will know the place where it's installed.


问:
Having problems sorting items in a listbox
I am reading a list of high scores for my game from a text file using StreamReader. I am then sorting it using .Sort()

I converted it to an array and passed it into a list box on a form in the game.
The score is saved to the text file in a string (score+" - "+username)

```<code>public frmHighScores()
    {
        InitializeComponent();

        List<string> scores = new List<string>();
        StreamReader inputFile = File.OpenText("High Scores.txt");
        while (!inputFile.EndOfStream)
        {
            scores.Add(inputFile.ReadLine());
        }
        scores.Sort();
        lstScores.Items.AddRange(scores.ToArray());
    }
</code>```

As it is a string the Sort method is only sorting the first number in the score and I'm not sure how to rectify it.

Here is the image of the sorted list

I want it to read as follows

```<code>200
120
105
65
</code>```

答:
You could use the LINQ OrderByDescending extension method and pass inn the value which comes before the "-" sign, something like that:</p>

```<code>scores = scores.OrderByDescending(x=>Convert.ToInt32(x.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]).Trim());
</code>```

Body:
I am reading a list of high scores for my game from a text file using StreamReader. I am then sorting it using .Sort()

I converted it to an array and passed it into a list box on a form in the game.
The score is saved to the text file in a string (score+" - "+username)

public frmHighScores()
    {
        InitializeComponent();

        List<string> scores = new List<string>();
        StreamReader inputFile = File.OpenText("High Scores.txt");
        while (!inputFile.EndOfStream)
        {
            scores.Add(inputFile.ReadLine());
        }
        scores.Sort();
        lstScores.Items.AddRange(scores.ToArray());
    }

As it is a string the Sort method is only sorting the first number in the score and I'm not sure how to rectify it.

Here is the image of the sorted list

I want it to read as follows

200
120
105
65

Body:
You could use the LINQ OrderByDescending extension method and pass inn the value which comes before the "-" sign, something like that:

scores = scores.OrderByDescending(x=>Convert.ToInt32(x.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]).Trim());


问:
want to put logo centre of the page between two lines
I want to make a grid-like 5.5-1-5.5. Is it possible because I want to put that logo in the center of the page and two lines on the left & right?
(my English is not good)

答:
flex and pseudos will do :

.lines {
  display: flex;
  align-items: center;
}

.lines:before,
.lines:after {
  content: '';
  border: 4px solid black;
  flex: 1;
}

img {
  margin: 0 1em;
  border-radius:50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lines"><img src="http://dummyimage.com/150x150&text=logo"></div></code>```

Body:
flex and pseudos will do :

.lines {
  display: flex;
  align-items: center;
}

.lines:before,
.lines:after {
  content: '';
  border: 4px solid black;
  flex: 1;
}

img {
  margin: 0 1em;
  border-radius:50%;
}

<div class="lines"><img src="http://dummyimage.com/150x150&text=logo"></div>


问:
How to get DropDownList selected Text in MVC controller
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID

```<code> @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })
</code>```

On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.

Controller side code line:

```<code>detailsConfig.Project = Convert.ToString(form["Project"]);
</code>```

For example:
If the dropdownlist values are

```<code>Project     ID
test        1
testagain   2
</code>```

In controller I should get test, not 1. Please help

答:
You use that drop-down change event and store that name in hidden filed and get that value to controller.

View:-

```<code>@Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control",@id="ddlProject" })

<input type="hidden" id = "hdnProjectName" name="ProjectName" />
</code>```

Jquery:-

```<code>$("#ddlProject").on("change", function () {
              $("#hdnProjectName").val($(this).find("option:selected").text());
        });
</code>```

Controller:-

```<code>public ActionResult Save(FormCollection formcollection)
{
   var projectName = formcollection["ProjectName"];
 }
</code>```

Body:
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID

 @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })

On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.

Controller side code line:

detailsConfig.Project = Convert.ToString(form["Project"]);

For example:
If the dropdownlist values are

Project     ID
test        1
testagain   2

In controller I should get test, not 1. Please help

Body:
You use that drop-down change event and store that name in hidden filed and get that value to controller.

View:-

@Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control",@id="ddlProject" })

<input type="hidden" id = "hdnProjectName" name="ProjectName" />

Jquery:-

$("#ddlProject").on("change", function () {
              $("#hdnProjectName").val($(this).find("option:selected").text());
        });

Controller:-

public ActionResult Save(FormCollection formcollection)
{
   var projectName = formcollection["ProjectName"];
 }


问:
Retrieve next to last date SQL Server
I think this is a simple problem but I cannot find an easy answer. I need to retrieve the last 2 entries by date. I have used max() to get the latest date; but do not know how to retrieve the next most recent.

The stored procedure code for latest date is:

```<code>SELECT *
FROM Table
WHERE Date=(SELECT MAX(Date) FROM Table);
</code>```

So using a separate procedure how do I get the next most recent?

答:
You can use order by and top:

```<code>select top 2 t.*
from t
order by date desc;
</code>```

Title: Retrieve next to last date SQL Server

Body:
I think this is a simple problem but I cannot find an easy answer. I need to retrieve the last 2 entries by date. I have used max() to get the latest date; but do not know how to retrieve the next most recent.

The stored procedure code for latest date is:

SELECT *
FROM Table
WHERE Date=(SELECT MAX(Date) FROM Table);

So using a separate procedure how do I get the next most recent?

Body:
You can use order by and top:

select top 2 t.*
from t
order by date desc;


问:
Relationship to find ancestor in SQLAlchemy
I have a tree of one-to-many relationships that looks like this:

organization -> operation -> region -> area -> site

The organization is the top level ancestor. A site has an area_id, area has a region_id, and so on up the tree.

For each entity under organization, I'd like to be able to quickly access the organization ancestor through a relationship like site.organization, area.organization, etc.

What would the relationship on each entity look like to make this work?

答:
A solution would be to use a composite "secondary" join for those classes that do not have a direct relationship with organization. For example site:

```<code>class Site(Base):

    organization = relationship(
        "Organization",
        secondary="join(Operation, Region).join(Area)",
        uselist=False,
        innerjoin=True,
        viewonly=True)
</code>```

while region should just use the table operation as a secondary:

```<code>class Region(Base):

    organization = relationship(
        "Organization",
        secondary="operation",
        uselist=False,
        innerjoin=True,
        viewonly=True)
</code>```

The above is a reduced version displaying only the relationship configurations. A concrete example follows:

```<code>from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("sqlite://")

Base = declarative_base()
Base.metadata.bind = engine

Session = sessionmaker()

class Organization(Base):
    __tablename__ = 'organization'
    id = Column(Integer, primary_key=True)

class Operation(Base):
    __tablename__ = 'operation'
    id = Column(Integer, primary_key=True)
    organization_id = Column(ForeignKey('organization.id'))
    organization = relationship("Organization")

class Region(Base):
    __tablename__ = 'region'
    id = Column(Integer, primary_key=True)
    operation_id = Column(ForeignKey('operation.id'))
    organization = relationship(
        "Organization",
        secondary="operation",
        uselist=False, innerjoin=True, viewonly=True)
    operation = relationship("Operation")

class Area(Base):
    __tablename__ = 'area'
    id = Column(Integer, primary_key=True)
    region_id = Column(ForeignKey('region.id'))
    organization = relationship(
        "Organization",
        secondary="join(Operation, Region)",
        uselist=False, innerjoin=True, viewonly=True)
    region = relationship("Region")

class Site(Base):
    __tablename__ = 'site'
    id = Column(Integer, primary_key=True)
    area_id = Column(ForeignKey('area.id'))
    organization = relationship(
        "Organization",
        secondary="join(Operation, Region).join(Area)",
        uselist=False, innerjoin=True, viewonly=True)
    area = relationship("Area")

Base.metadata.create_all()

session = Session()
session.add(Site(area=Area(region=Region(operation=Operation(organization=Organization())))))
session.commit()

site = session.query(Site).options(joinedload(Site.organization)).first()
print(site)
print(site.organization)
print(site.area.organization)
print(site.area.region.organization)
print(site.area.region.operation.organization)
</code>```

Body:
A solution would be to use a composite "secondary" join for those classes that do not have a direct relationship with organization. For example site:

class Site(Base):

    organization = relationship(
        "Organization",
        secondary="join(Operation, Region).join(Area)",
        uselist=False,
        innerjoin=True,
        viewonly=True)

while region should just use the table operation as a secondary:

class Region(Base):

    organization = relationship(
        "Organization",
        secondary="operation",
        uselist=False,
        innerjoin=True,
        viewonly=True)

The above is a reduced version displaying only the relationship configurations. A concrete example follows:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("sqlite://")

Base = declarative_base()
Base.metadata.bind = engine

Session = sessionmaker()

class Organization(Base):
    __tablename__ = 'organization'
    id = Column(Integer, primary_key=True)

class Operation(Base):
    __tablename__ = 'operation'
    id = Column(Integer, primary_key=True)
    organization_id = Column(ForeignKey('organization.id'))
    organization = relationship("Organization")

class Region(Base):
    __tablename__ = 'region'
    id = Column(Integer, primary_key=True)
    operation_id = Column(ForeignKey('operation.id'))
    organization = relationship(
        "Organization",
        secondary="operation",
        uselist=False, innerjoin=True, viewonly=True)
    operation = relationship("Operation")

class Area(Base):
    __tablename__ = 'area'
    id = Column(Integer, primary_key=True)
    region_id = Column(ForeignKey('region.id'))
    organization = relationship(
        "Organization",
        secondary="join(Operation, Region)",
        uselist=False, innerjoin=True, viewonly=True)
    region = relationship("Region")

class Site(Base):
    __tablename__ = 'site'
    id = Column(Integer, primary_key=True)
    area_id = Column(ForeignKey('area.id'))
    organization = relationship(
        "Organization",
        secondary="join(Operation, Region).join(Area)",
        uselist=False, innerjoin=True, viewonly=True)
    area = relationship("Area")

Base.metadata.create_all()

session = Session()
session.add(Site(area=Area(region=Region(operation=Operation(organization=Organization())))))
session.commit()

site = session.query(Site).options(joinedload(Site.organization)).first()
print(site)
print(site.organization)
print(site.area.organization)
print(site.area.region.organization)
print(site.area.region.operation.organization)


问:
Can't disappear "untracked" folder in git status
I'm new to Git. A couple of days ago I tried to undo a "git add --all" with "git reset" after a quick Google suggested that. Luckily it appears no material harm was inflicted on my working directory, however Git has added a folder of angularjs modules I had listed in .gitignore, and now this folder (and everything in it) is showing up as "untracked" in "git status". It didn't prior to the reset, and nothing else in gitignore is doing this. I've tried a few solutions including "git rm -r --cached node_modules" and this Git untracked files list is wrong but it's still there. All suggestions appreciated!</p>

答:
I had a similar issue with an untracked folder persisting. I solved this by using the answer described here, I had to run:

```<code>git clean -f -d
</code>```

To ensure directories were removed.

Body:
I had a similar issue with an untracked folder persisting. I solved this by using the answer described here, I had to run:

git clean -f -d

To ensure directories were removed.


答:
It means that you have a memory error.  You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once.  You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.

Any number of programming errors can cause this problem.  You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs.  If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

Title: Error: free(): invalid next size (fast):

Body:
What is this strange error I'm getting? I'm compiling C++ using g++ on Ubuntu 10.10. It pops up randomly when I run the executable (maybe 2 times in 8 hours, with 10 compiles an hour). However, if I make clean and recompile it goes away most of the time.

*** glibc detected *** ./emailQueue.app: free(): invalid next size (fast): 0x0000000001c40270 ***
======= Backtrace: =========
/lib/libc.so.6(+0x774b6)[0x7f490d95e4b6]
/lib/libc.so.6(cfree+0x73)[0x7f490d964c83]
./emailQueue.app[0x401f47]
/lib/libc.so.6(__libc_start_main+0xfe)[0x7f490d905d8e]
./emailQueue.app[0x401cc9]
======= Memory map: ========
00400000-0040d000 r-xp 00000000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
0060d000-0060e000 r--p 0000d000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
0060e000-0060f000 rw-p 0000e000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
01c40000-01c82000 rw-p 00000000 00:00 0                                  [heap]
7f4908000000-7f4908021000 rw-p 00000000 00:00 0
7f4908021000-7f490c000000 ---p 00000000 00:00 0
7f490ce52000-7f490ce5e000 r-xp 00000000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490ce5e000-7f490d05d000 ---p 0000c000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05d000-7f490d05e000 r--p 0000b000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05e000-7f490d05f000 rw-p 0000c000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05f000-7f490d075000 r-xp 00000000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d075000-7f490d275000 ---p 00016000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d275000-7f490d276000 r--p 00016000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d276000-7f490d277000 rw-p 00017000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d277000-7f490d28e000 r-xp 00000000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d28e000-7f490d48d000 ---p 00017000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48d000-7f490d48e000 r--p 00016000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48e000-7f490d48f000 rw-p 00017000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48f000-7f490d491000 rw-p 00000000 00:00 0
7f490d491000-7f490d49a000 r-xp 00000000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d49a000-7f490d69a000 ---p 00009000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69a000-7f490d69b000 r--p 00009000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69b000-7f490d69c000 rw-p 0000a000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69c000-7f490d6ca000 rw-p 00000000 00:00 0
7f490d6ca000-7f490d6e2000 r-xp 00000000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d6e2000-7f490d8e1000 ---p 00018000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e1000-7f490d8e2000 r--p 00017000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e2000-7f490d8e3000 rw-p 00018000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e3000-7f490d8e7000 rw-p 00000000 00:00 0
7f490d8e7000-7f490da61000 r-xp 00000000 08:01 1048743                    /lib/libc-2.12.1.so
7f490da61000-7f490dc60000 ---p 0017a000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc60000-7f490dc64000 r--p 00179000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc64000-7f490dc65000 rw-p 0017d000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc65000-7f490dc6a000 rw-p 00000000 00:00 0
7f490dc6a000-7f490dc7f000 r-xp 00000000 08:01 1048655                    /lib/libgcc_s.so.1
7f490dc7f000-7f490de7e000 ---p 00015000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de7e000-7f490de7f000 r--p 00014000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de7f000-7f490de80000 rw-p 00015000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de80000-7f490df02000 r-xp 00000000 08:01 1051246                    /lib/libm-2.12.1.so
7f490df02000-7f490e101000 ---p 00082000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e101000-7f490e102000 r--p 00081000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e102000-7f490e103000 rw-p 00082000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e103000-7f490e1eb000 r-xp 00000000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e1eb000-7f490e3ea000 ---p 000e8000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3ea000-7f490e3f2000 r--p 000e7000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3f2000-7f490e3f4000 rw-p 000ef000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3f4000-7f490e409000 rw-p 00000000 00:00 0
7f490e409000-7f490e5c7000 r-xp 00000000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e5c7000-7f490e7c7000 ---p 001be000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e7c7000-7f490e7cc000 r--p 001be000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e7cc000-7f490e816000 rw-p 001c3000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e816000-7f490e817000 rw-p 00000000 00:00 0
7f490e817000-7f490e837000 r-xp 00000000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea15000-7f490ea1c000 rw-p 00000000 00:00 0
7f490ea33000-7f490ea37000 rw-p 00000000 00:00 0
7f490ea37000-7f490ea38000 r--p 00020000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea38000-7f490ea39000 rw-p 00021000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea39000-7f490ea3a000 rw-p 00000000 00:00 0
7fffb85b9000-7fffb85da000 rw-p 00000000 00:00 0                          [stack]
7fffb85ff000-7fffb8600000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted


问:
phoenix hbase table presplit with multiple split points for the same region
I am using apachephoenix 4.9.1 and hbase-1.1.2.
For prespliting the table i am using following option at the table creation time

SPLIT ON(0,1,2,3,4,5,6,7,8,9,10)

```<code>1) is it possible to split (0&1,2&3,4&5,5&6,6&7,8&9)  like this?

2) i tried merging the regions manually using hbase shell. if i
merge a presplit table to (0&1,2&3,4&5,5&6,6&7,8&9) whether it will
contain the presplit info of both regions?
</code>```

答:
is it possible to split (0&1,2&3,4&5,5&6,6&7,8&9)  like this?'

Yes, just use SPLIT ON(1,3,5,7,9).

In this case, everything <=1 would go in the first split, <1 and >=3 in the second split, <3 and >=5 in the third split, and so on.

I'm assuming here that having the same key in multiple splits (e.g. key "5" in 4&5, 5&6) was a typo. You can't have the same key in multiple splits.

2) i tried merging the regions manually using hbase shell. if i
  merge a presplit table to (0&1,2&3,4&5,5&6,6&7,8&9) whether it will
  contain the presplit info of both regions?

Yes, it would.

Body:
I am using apachephoenix 4.9.1 and hbase-1.1.2.
For prespliting the table i am using following option at the table creation time

SPLIT ON(0,1,2,3,4,5,6,7,8,9,10)

1) is it possible to split (0&1,2&3,4&5,5&6,6&7,8&9)  like this?

2) i tried merging the regions manually using hbase shell. if i
merge a presplit table to (0&1,2&3,4&5,5&6,6&7,8&9) whether it will
contain the presplit info of both regions?


问:
Firebase problems, cant set data
RULES FILES

```<code>   {
      "rules": {
        ".write": true,
        "users": {
          ".validate": "newData.hasChildren(['uuid', 'on'])",
          "on": {
            ".validate": "newData.isNumber() &&
                          newData.val() >= 0 &&
                          newData.val() <= 1"
          },
          "uuid": {

          }
        }
      }
    }
</code>```

this is my code (node.js).

```<code>firebase.initializeApp({
    serviceAccount: "BITCOIN-f9a190c06e27.json",
    databaseURL: "https://bitcoin-865ac.firebaseio.com"
});

var users = firebase.database().ref('/users')

    users.set({
        uuid: 'xxxx',
        on: '0'

    });
</code>```

I have this mistake.

FIREBASE WARNING: set at /users failed: permission_denied
(node:444) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: PERMISSION_DENIED: Permission denied

i dont have any idea, i thought the write "true", was enough to give any permissions

答:
with "users" node this is a simple user auth rules that can work: </p>

```<code>{
 "rules": {
  "users": {
    ".read": "false",
    ".write": "true",
  "$uid": {
    ".read": "auth.uid === $uid",
    ".write": "auth.uid === $uid"
    }
   }
  }
}
</code>```

Title: Firebase problems, cant set data

Body:
RULES FILES

   {
      "rules": {
        ".write": true,
        "users": {
          ".validate": "newData.hasChildren(['uuid', 'on'])",
          "on": {
            ".validate": "newData.isNumber() &&
                          newData.val() >= 0 &&
                          newData.val() <= 1"
          },
          "uuid": {

          }
        }
      }
    }

this is my code (node.js).

firebase.initializeApp({
    serviceAccount: "BITCOIN-f9a190c06e27.json",
    databaseURL: "https://bitcoin-865ac.firebaseio.com"
});

var users = firebase.database().ref('/users')

    users.set({
        uuid: 'xxxx',
        on: '0'

    });

I have this mistake.

FIREBASE WARNING: set at /users failed: permission_denied
(node:444) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: PERMISSION_DENIED: Permission denied

i dont have any idea, i thought the write "true", was enough to give any permissions

Body:
with "users" node this is a simple user auth rules that can work:

{
 "rules": {
  "users": {
    ".read": "false",
    ".write": "true",
  "$uid": {
    ".read": "auth.uid === $uid",
    ".write": "auth.uid === $uid"
    }
   }
  }
}


问:
Get Task Name only from SCHTASKS /query through bat file
I need t get only task name instead of TaskName, NextRuntime, Status from SCHTASKS /query query, how can i do the same?

答:
```<code>for /f "tokens=1*" %%a in ('schtasks /query /fo list^|findstr /b "Aufgabenname"') do @echo %%b
</code>```

Replace "Aufgabenname" with the corresponding term in your language ("TaskName" in English)

If you need the taskname without path, use echo %%~nxb

For use directly at command line, replace every %% with % only.

Body:
for /f "tokens=1*" %%a in ('schtasks /query /fo list^|findstr /b "Aufgabenname"') do @echo %%b

Replace "Aufgabenname" with the corresponding term in your language ("TaskName" in English)

If you need the taskname without path, use echo %%~nxb

For use directly at command line, replace every %% with % only.


问:
Handle too many textures Unity
At present one of my quiz game require, many images of flowers based on questions asked.
I can say total 250+ images with resolution of 512x435 each.
Plus other games textures get loaded at a time.

So when game screen get opened which showing all these images, its on the spot get crashed.
I am testing this on iPhone devices. So how to handle these many textures? I was stuck in this point.

Here is overview of flowers textures.

I was displaying all these in grid view so in one scrollable screen all get displayed.
Now I hope, you understand my side point of view.

答: With in the application you could split them into 25 at a time on the screen and you could swipe to the right to go to the next 25 or swipe back to the previous. This is how i solved a similar problem in unity a while back. </p>

Title: Handle too many textures Unity


答: We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.


问:
Mocking remote api calls in golang
I'm trying to get better at writing mocked golang tests that call a remote api
I can similate a single call pretty easily with the httptest library but am a
bit stuck handling other functions that call single endpoint calls multiple times.

For example given a simple create function

```<code>func createItem(url string, product Product) (int, error) {
    // make request
    return createdId, nil
}
</code>```

I can write some tests that look like this

```<code>func TestCreateItem(t *testing.T) {
    mock_ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`37`))
    }))

    prod := Product{...}

    _, err := createItem(mock_ts.URL, 1, prod)
    if err != nil {
        t.Errorf("Error saving item: %v", err)
    }
}
</code>```

Now if I have this other wrapper function I won't be able to pass in the
mock test server url.

```<code>func someFunctionThatMakesManyItems(...) {
    url = "http://www.realapiendpoint.com" // or some func that gets api url

    // this function might generate a list of items
    for _, item := range items {
        createItem(url, item)
    }

}
</code>```

I could need to pass in the url to the someFunctionThatMakesManyItems and any
functions that rely on api functions and that just seems like the wrong approach.

Any advice on how to model this better to help with my tests?

答: Make the endpoint URL configurable instead of hard-coding it - make it a function parameter, or a field of some configuration struct, or returned from an internal configuration service, something like that. Designing for testability is all about avoiding hard-coded configuration and dependencies: code should receive its configuration values and its dependencies from the caller rather than setting or creating them itself.

Title: Mocking remote api calls in golang

Body:
I'm trying to get better at writing mocked golang tests that call a remote api
I can similate a single call pretty easily with the httptest library but am a
bit stuck handling other functions that call single endpoint calls multiple times.

For example given a simple create function

func createItem(url string, product Product) (int, error) {
    // make request
    return createdId, nil
}

I can write some tests that look like this

func TestCreateItem(t *testing.T) {
    mock_ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`37`))
    }))

    prod := Product{...}

    _, err := createItem(mock_ts.URL, 1, prod)
    if err != nil {
        t.Errorf("Error saving item: %v", err)
    }
}

Now if I have this other wrapper function I won't be able to pass in the
mock test server url.

func someFunctionThatMakesManyItems(...) {
    url = "http://www.realapiendpoint.com" // or some func that gets api url

    // this function might generate a list of items
    for _, item := range items {
        createItem(url, item)
    }

}

I could need to pass in the url to the someFunctionThatMakesManyItems and any
functions that rely on api functions and that just seems like the wrong approach.

Any advice on how to model this better to help with my tests?


问:
How to call function after submit form aspx
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

```<code><div id="HiddenFormTarget" style="display:none;">
    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
<iframe id="frmPrint" name="frmPrint" width="0" height="0" runat="server">
</iframe>

<script language="javascript" type="text/javascript">
    $("#formImpressao").submit(function () {
       alert('Test');
    });
    $("#formImpressao").submit();

</script>
</code>```

答:
I reproduce this situation and all right:</p>

```<code>[https://codepen.io/piotrazsko/pen/mqMrgo][1]
</code>```

Body:
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>

Body:
I reproduce this situation and all right:

[https://codepen.io/piotrazsko/pen/mqMrgo][1]


问:
Cannot create AKS in azure with command "az aks create"
az aks create -n MyServices -g MyKubernetes --generate-ssh-keys

is not working. Error message: az aks create -n Adestis-Services -g Adestis.Kubernetes --generate-ssh-keys
A Cloud Shell credential problem occurred. When you report the issue with the error below, please mention the hostname '679e170bedd7'
Could not retrieve token from local cache.

Steps to reproduce:
az login
az account set --subscription MySubscriptionID
az group create --name "MyKubernetes" --location "westus"
az aks create -n MyServices -g MyKubernetes --generate-ssh-keys

答: AKS has been rolled out to East US new region. Can you please try deploying an AKS cluster in East US region?</p>


问:
Redirect based on file upload
Seems like a no brainer if statement right?  But for some reason.... I cannot get a page to load based on if a file was uploaded properly or not.

This is not the complete page, but this is what I am using atm that somewhat works...

```<code>elseif ($pn == "umov") {
    ?>
    <div class="container" style="margin-top: 20px;">
        <h1>Movie Updated</h1>
    </div>
    <?php

    $umovim = $_FILES["my_field"];
    if ($umovim > '') {
        include 'eupload.php';
    }
    if ($umovim == $umovim) {
        include 'update_movie.php';
    }
} elseif ($pn == "inmov") {
    ?>
    <div class="container" style="margin-top: 20px;">
        <h1>New Movie Added</h1>
    </div>
</code>```

Here is what happens...

If I do not upload a photo, the program will call update_movie.php. If I do upload a photo, I get both eupload.php and update_movie.php.

I tried using else and elseif instead of if and I get a blank page meaning that the script is not calling or loading the update_movie.php.

I am not sure what value is being passed by  $umovim = $_FILES["my_field"];.  When I echo the result to the page all it says is ARRAY.

Any suggestion would be appreciated. Thanks.

答:
Not sure if this is actually correct coding but it works...

```<code>elseif ($pn == "emov") {
        ?>
        <div class="container" style="margin-top: 20px;">
            <h1>Edit Movie</h1>
        </div>
        <?php
            include 'edit_movie.php';
            }
            elseif ($pn == "umov") {
        ?>
        <div class="container" style="margin-top: 20px;">
            <h1>Movie Updated</h1>
        </div>
        <?php

            $umovim = basename($_FILES["my_field"]["name"]);
                if ($umovim > ''){
                    include 'eupload.php';
                    } else {
                    include 'update_movie.php';
                    }
            }
            elseif ($pn == "inmov") {
        ?>
</code>```

Using basename($_FILES["my_field"]["name"]); instead of just $_FILES["my_field"]; seemed to pass a value that was workable for the else statement.  Although I am not sure what that value is. LOL.

Title: Redirect based on file upload

Body:
Seems like a no brainer if statement right?  But for some reason.... I cannot get a page to load based on if a file was uploaded properly or not.

This is not the complete page, but this is what I am using atm that somewhat works...

elseif ($pn == "umov") {
    ?>

Movie Updated

    <?php

    $umovim = $_FILES["my_field"];
    if ($umovim > '') {
        include 'eupload.php';
    }
    if ($umovim == $umovim) {
        include 'update_movie.php';
    }
} elseif ($pn == "inmov") {
    ?>

New Movie Added

Here is what happens...

If I do not upload a photo, the program will call update_movie.php. If I do upload a photo, I get both eupload.php and update_movie.php.

I tried using else and elseif instead of if and I get a blank page meaning that the script is not calling or loading the update_movie.php.

I am not sure what value is being passed by  $umovim = $_FILES["my_field"];.  When I echo the result to the page all it says is ARRAY.

Any suggestion would be appreciated. Thanks.

Body:
Not sure if this is actually correct coding but it works...

elseif ($pn == "emov") {
        ?>
        <div class="container" style="margin-top: 20px;">
            <h1>Edit Movie</h1>
        </div>
        <?php
            include 'edit_movie.php';
            }
            elseif ($pn == "umov") {
        ?>
        <div class="container" style="margin-top: 20px;">
            <h1>Movie Updated</h1>
        </div>
        <?php

            $umovim = basename($_FILES["my_field"]["name"]);
                if ($umovim > ''){
                    include 'eupload.php';
                    } else {
                    include 'update_movie.php';
                    }
            }
            elseif ($pn == "inmov") {
        ?>

Using basename($_FILES["my_field"]["name"]); instead of just $_FILES["my_field"]; seemed to pass a value that was workable for the else statement.  Although I am not sure what that value is. LOL.


问:
How to isolate a query inside a scope from pundit policy scope?
I'm using Rails 5 + Pundit gem and trying to fetch some chats with policy scope and model scope. Model scope has a query inside it and the problem is that policy scope applies to this inner query. The question is how to isolate the query from outer scope? Here's some code:

```<code># model
scope :with_user, ->(user_id=nil) {
  user_id ? where(chats: { id: User.find(user_id).chats.ids }) : all
}

# policy
class Scope < Scope
  def resolve
    if user.admin?
      scope.all
    else
      scope.joins(:chat_users).where(chat_users: { user_id: user.id })
    end
  end
end
</code>```

So I decided to output the inner sql query, which should get user chats' ids from the scope. I updated the model scope:

```<code>scope :with_user, ->(user_id=nil) {
  puts User.find(user_id).chats.to_sql
  where(chats: { id: User.unscoped.find(user_id).chats.ids } )
}
</code>```

and here are results:
when I run ChatPolicy::Scope.new(User.first, Chat).resolve.with_user(358) I get:

SELECT "chats".* FROM "chats" INNER JOIN "chat_users"
  "chat_users_chats" ON "chat_users_chats"."chat_id" = "chats"."id"
  INNER JOIN "chat_users" ON "chats"."id" = "chat_users"."chat_id" WHERE
  (chat_users.user_id = 350) AND "chat_users"."user_id" = 358

When I run Chat.with_user(358) I get:

SELECT "chats".* FROM "chats" INNER JOIN "chat_users" ON "chats"."id"
  = "chat_users"."chat_id" WHERE "chat_users"."user_id" = 358

It generates the correct query if I run it without policy scope. Is there a workaround?

答:
This is a Community Wiki answer replacing the answer having been edited into the original question as recommended by Meta.

This has been solved by the OP with a different unscoped model scope:

```<code>scope :with_user, ->(user_id=nil) {
  user_id ? where(chats: { id: Chat.unscoped.joins(:chat_users).where(chat_users: { user_id: user_id }).ids } ) : all
}
</code>```

Body:
I'm using Rails 5 + Pundit gem and trying to fetch some chats with policy scope and model scope. Model scope has a query inside it and the problem is that policy scope applies to this inner query. The question is how to isolate the query from outer scope? Here's some code:

# model
scope :with_user, ->(user_id=nil) {
  user_id ? where(chats: { id: User.find(user_id).chats.ids }) : all
}

# policy
class Scope < Scope
  def resolve
    if user.admin?
      scope.all
    else
      scope.joins(:chat_users).where(chat_users: { user_id: user.id })
    end
  end
end

So I decided to output the inner sql query, which should get user chats' ids from the scope. I updated the model scope:

scope :with_user, ->(user_id=nil) {
  puts User.find(user_id).chats.to_sql
  where(chats: { id: User.unscoped.find(user_id).chats.ids } )
}

and here are results:
when I run ChatPolicy::Scope.new(User.first, Chat).resolve.with_user(358) I get:

SELECT "chats".* FROM "chats" INNER JOIN "chat_users"
  "chat_users_chats" ON "chat_users_chats"."chat_id" = "chats"."id"
  INNER JOIN "chat_users" ON "chats"."id" = "chat_users"."chat_id" WHERE
  (chat_users.user_id = 350) AND "chat_users"."user_id" = 358

When I run Chat.with_user(358) I get:

SELECT "chats".* FROM "chats" INNER JOIN "chat_users" ON "chats"."id"
  = "chat_users"."chat_id" WHERE "chat_users"."user_id" = 358

It generates the correct query if I run it without policy scope. Is there a workaround?

Body:
This is a Community Wiki answer replacing the answer having been edited into the original question as recommended by Meta.

This has been solved by the OP with a different unscoped model scope:

scope :with_user, ->(user_id=nil) {
  user_id ? where(chats: { id: Chat.unscoped.joins(:chat_users).where(chat_users: { user_id: user_id }).ids } ) : all
}


问:
Tricks to manage the available memory in an R session
What tricks do people use to manage the available memory of an interactive R session?  I use the functions below [based on postings by Petr Pikal and David Hinds to the r-help list in 2004] to list (and/or sort) the largest objects and to occassionally rm() some of them. But by far the most effective solution was ... to run under 64-bit Linux with ample memory.

Any other nice tricks folks want to share?  One per post, please.

```<code># improved list of objects
.ls.objects <- function (pos = 1, pattern, order.by,
                        decreasing=FALSE, head=FALSE, n=5) {
    napply <- function(names, fn) sapply(names, function(x)
                                         fn(get(x, pos = pos)))
    names <- ls(pos = pos, pattern = pattern)
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)
    obj.dim <- t(napply(names, function(x)
                        as.numeric(dim(x))[1:2]))
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by))
        out <- out[order(out[[order.by]], decreasing=decreasing), ]
    if (head)
        out <- head(out, n)
    out
}
# shorthand
lsos <- function(..., n=10) {
    .ls.objects(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}
</code>```

答: If you are working on Linux and want to use several processes and only have to do read operations on one or more large objects use makeForkCluster instead of a makePSOCKcluster. This also saves you the time sending the large object to the other processes.

Body:
What tricks do people use to manage the available memory of an interactive R session?  I use the functions below [based on postings by Petr Pikal and David Hinds to the r-help list in 2004] to list (and/or sort) the largest objects and to occassionally rm() some of them. But by far the most effective solution was ... to run under 64-bit Linux with ample memory.

Any other nice tricks folks want to share?  One per post, please.

# improved list of objects
.ls.objects <- function (pos = 1, pattern, order.by,
                        decreasing=FALSE, head=FALSE, n=5) {
    napply <- function(names, fn) sapply(names, function(x)
                                         fn(get(x, pos = pos)))
    names <- ls(pos = pos, pattern = pattern)
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)
    obj.dim <- t(napply(names, function(x)
                        as.numeric(dim(x))[1:2]))
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by))
        out <- out[order(out[[order.by]], decreasing=decreasing), ]
    if (head)
        out <- head(out, n)
    out
}
# shorthand
lsos <- function(..., n=10) {
    .ls.objects(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}


问:
Configure logging programmatically in Scala/Play
The Play framework requires (by default) that you configure logging through a logback.xml file. I'd like to build my log appenders through code so I can fetch parameters at runtime (e.g. the graylog destination for the logs is fetched from the deployment environment, rather than baking it in statically through an XML file). </p>

<p>This sort of thing is fairly easy to achieve in Java (by overriding logging factories and the like), I wondered if the same were possible in Play. </p>

答:
Yes, you can configure logback programmatically, see: https://akhikhl.wordpress.com/2013/07/11/programmatic-configuration-of-slf4jlogback/

But I wouldn't recommend it. For starters it's a verbose API that isn't pleasant to work with. Beyond that, it generally nice for configuration to be declarative (even if it is in XML in this case).

For your usecase, Logback's XML does support variables which can come from System properties or Environment variables: https://logback.qos.ch/manual/configuration.html#definingProps

However, you probably want a different config across environments (no greylog locally). I think many projects do that by specifying the logback XML location as a system property at startup: https://logback.qos.ch/manual/configuration.html#configFileProperty

Alternatively, I suspect greylog has some method of watching a file to pickup your logging. That's what we do for picking up logs in Splunk in my team. We don't want to make a change to our code when someone reconfigures Splunk/Greylog.

Body:
The Play framework requires (by default) that you configure logging through a logback.xml file. I'd like to build my log appenders through code so I can fetch parameters at runtime (e.g. the graylog destination for the logs is fetched from the deployment environment, rather than baking it in statically through an XML file).

This sort of thing is fairly easy to achieve in Java (by overriding logging factories and the like), I wondered if the same were possible in Play.


问:
PyCharm Console Font changes font only on Python Terminal
I am using a 4k Windows laptop and I configured the compatibily settings for PyCharm(2017.2.3 Community Edition) and the font size of the editor looks fine.

Subsequently,I wanted to fix the font size of the terminal and the python console. Using this post and this from stackoverflow, I went to File -> Settings -> Editor -> Colors Scheme -> Console Font and I changed the font size. This resulted in changing the font size of only the python console and not the terminal. Any suggestion?

Pictures attached:

答: In the end I had to unistall it and install it again from the beginning without importing the settings. Should have a been a problem with the installation.</p>


问:
want to put logo centre of the page between two lines
I want to make a grid-like 5.5-1-5.5. Is it possible because I want to put that logo in the center of the page and two lines on the left & right?
(my English is not good)

答:
Why not using a background like so?

.background{
  display: flex;
  align-content: center;
  justify-content: center;
  background: url('https://i.imgur.com/kBiG6ql.png') center repeat-x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="background">
  <img class="logo" src="https://i.imgur.com/h4J7ZvW.png"/>
</div></code>```

Body:
Why not using a background like so?

.background{
  display: flex;
  align-content: center;
  justify-content: center;
  background: url('https://i.imgur.com/kBiG6ql.png') center repeat-x;
}

<div class="background">
  <img class="logo" src="https://i.imgur.com/h4J7ZvW.png"/>
</div>


问:
can not Enable Migrations
That error show when i run Enable Migration ! iam did the reverse engineering the SQLServer and i want to do some changers on my Data  i see this erroe whoch guide me to the line 10 on config.cs which is the constructor generated by visual studio (iam using Visual 2015) , sql connector 6.9.4

```<code>Checking if the context targets an existing database...
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeLoadException: Inheritance security rules violated by type: 'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either match the security accessibility of the base type or be less accessible.
   at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
   at System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
   at System.RuntimeType.GetCustomAttributes(Type attributeType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type type, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttributes[T](MemberInfo element, Boolean inherit)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationFinder.TryFindConfigurationType(Assembly assemblyHint, Type contextTypeHint, IEnumerable`1 typesToSearch)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType)
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..cctor()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..ctor()
   at Data.Migrations.Configuration..ctor() in C:\Users\saif kouti\Desktop\piski[pi_kouti]\piski\Data\Migrations\Configuration.cs:line 10
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Data.Entity.Migrations.Utilities.MigrationsConfigurationFinder.FindMigrationsConfiguration(Type contextType, String configurationTypeName, Func`2 noType, Func`3 multipleTypes, Func`3 noTypeWithName, Func`3 multipleTypesWithName)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception.
</code>```

here my configuation.cs

```<code>namespace Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<iskiContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(Data.iskiContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    }
}
</code>```

and here my context

```<code>using System.Data.Entity;
using Domain.Models.Mapping;
using Domain.Models;
namespace Data
{
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]

    public partial class iskiContext : DbContext
    {
        static iskiContext()
        {
            Database.SetInitializer<iskiContext>(null);
        }

        public iskiContext()
            : base("Name=iskiContext")
        {
        }

        public DbSet<accomodation> accomodations { get; set; }
        public DbSet<company> companies { get; set; }
        public DbSet<contract> contracts { get; set; }
        public DbSet<Event> events { get; set; }
        public DbSet<event_user> event_user { get; set; }
        public DbSet<organizerrequest> organizerrequests { get; set; }
        public DbSet<product> products { get; set; }
        public DbSet<products_user> products_user { get; set; }
        public DbSet<user> users { get; set; }
        public DbSet<user_company> user_company { get; set; }
        public DbSet<winner> winners { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new accomodationMap());
            modelBuilder.Configurations.Add(new companyMap());
            modelBuilder.Configurations.Add(new contractMap());
            modelBuilder.Configurations.Add(new eventMap());
            modelBuilder.Configurations.Add(new event_userMap());
            modelBuilder.Configurations.Add(new organizerrequestMap());
            modelBuilder.Configurations.Add(new productMap());
            modelBuilder.Configurations.Add(new products_userMap());
            modelBuilder.Configurations.Add(new userMap());
            modelBuilder.Configurations.Add(new user_companyMap());
            modelBuilder.Configurations.Add(new winnerMap());
        }
    }
}
</code>```

答:
check the up() and down() methods in your migration file. Your changes will be submitted after update-databasecommand according to this up and down function.
otherwise make your AutomaticMigrationsEnabled = true

Title: can not Enable Migrations

Body:
That error show when i run Enable Migration ! iam did the reverse engineering the SQLServer and i want to do some changers on my Data  i see this erroe whoch guide me to the line 10 on config.cs which is the constructor generated by visual studio (iam using Visual 2015) , sql connector 6.9.4

Checking if the context targets an existing database...
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeLoadException: Inheritance security rules violated by type: 'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either match the security accessibility of the base type or be less accessible.
   at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
   at System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
   at System.RuntimeType.GetCustomAttributes(Type attributeType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type type, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttributes[T](MemberInfo element, Boolean inherit)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationFinder.TryFindConfigurationType(Assembly assemblyHint, Type contextTypeHint, IEnumerable`1 typesToSearch)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType)
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..cctor()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..ctor()
   at Data.Migrations.Configuration..ctor() in C:\Users\saif kouti\Desktop\piski[pi_kouti]\piski\Data\Migrations\Configuration.cs:line 10
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Data.Entity.Migrations.Utilities.MigrationsConfigurationFinder.FindMigrationsConfiguration(Type contextType, String configurationTypeName, Func`2 noType, Func`3 multipleTypes, Func`3 noTypeWithName, Func`3 multipleTypesWithName)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception.

here my configuation.cs

namespace Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<iskiContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(Data.iskiContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    }
}

and here my context

using System.Data.Entity;
using Domain.Models.Mapping;
using Domain.Models;
namespace Data
{
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]

    public partial class iskiContext : DbContext
    {
        static iskiContext()
        {
            Database.SetInitializer<iskiContext>(null);
        }

        public iskiContext()
            : base("Name=iskiContext")
        {
        }

        public DbSet<accomodation> accomodations { get; set; }
        public DbSet<company> companies { get; set; }
        public DbSet<contract> contracts { get; set; }
        public DbSet<Event> events { get; set; }
        public DbSet<event_user> event_user { get; set; }
        public DbSet<organizerrequest> organizerrequests { get; set; }
        public DbSet<product> products { get; set; }
        public DbSet<products_user> products_user { get; set; }
        public DbSet<user> users { get; set; }
        public DbSet<user_company> user_company { get; set; }
        public DbSet<winner> winners { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new accomodationMap());
            modelBuilder.Configurations.Add(new companyMap());
            modelBuilder.Configurations.Add(new contractMap());
            modelBuilder.Configurations.Add(new eventMap());
            modelBuilder.Configurations.Add(new event_userMap());
            modelBuilder.Configurations.Add(new organizerrequestMap());
            modelBuilder.Configurations.Add(new productMap());
            modelBuilder.Configurations.Add(new products_userMap());
            modelBuilder.Configurations.Add(new userMap());
            modelBuilder.Configurations.Add(new user_companyMap());
            modelBuilder.Configurations.Add(new winnerMap());
        }
    }
}


问:
Ionic Config Service (how to import)
I'm looking at the Ionic Config Service from here: https://ionicframework.com/docs/api/config/Config/

I would like to use the Config functionality to set global configuration variables (in my case API keys). I'm struggling to get it to work however.

Whenever I call:

```<code> config.set('ios', 'green', 'light');
</code>```

It tells me that config is not defined. However I am unable to import Config as

```<code> import { Config } from 'ionic-angular';
</code>```

does not work. I thought it could be imported like the Platform Service but it does not seem like it.
The documentation lacks further information.

Any help appreciated.

答:
You have to add the Config dependency in the constructor of your component

```<code>import {Config } from 'ionic-angular';
</code>```

constructor(public config:Config){
 }

Then, you can access it via

this.config.get('favoriteColor');

Title: Ionic Config Service (how to import)

Body:
I'm looking at the Ionic Config Service from here: https://ionicframework.com/docs/api/config/Config/

I would like to use the Config functionality to set global configuration variables (in my case API keys). I'm struggling to get it to work however.

Whenever I call:

 config.set('ios', 'green', 'light');

It tells me that config is not defined. However I am unable to import Config as

 import { Config } from 'ionic-angular';

does not work. I thought it could be imported like the Platform Service but it does not seem like it.
The documentation lacks further information.

Any help appreciated.

Body:
You have to add the Config dependency in the constructor of your component

import {Config } from 'ionic-angular';

constructor(public config:Config){
 }

Then, you can access it via

this.config.get('favoriteColor');


问:
How do I hide a div in angular based upon document height?
Forgive me if this is elsewhere...

I came into a project abandoned half-way through. I've not worked in angular before and need to hide/show a "back to top" button dependent upon whether the document is taller than the viewport. I've tried several different approaches and cannot get anything to work successfully. This is my latest attempt:

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

    if ($(document).height() > $(window).height()) {
        console.log("document height is greater");
        $('#arrowUp').show();
    } else {
        console.log("window height is lesser");
        $('#arrowUp').show();
    }
});
</code>```

Thanks in advance

答:
First, I highly discourage the mixing of Angular and jQuery - both are DOM manipulation frameworks and they will step on each other causing you endless headaches as you try to troubleshoot various things.

Here is a very contrived example of the "Angular" way of showing or hiding a div based on the height. You should be able to adapt this to suit your needs of showing the arrow based on a difference in window and document heights (it's hard to demonstrate that in the built-in snippet runner).

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.maxHeight = 1200;
    $scope.windowOuterHeight = window.outerHeight;
    $scope.documentHeight = document.documentElement.clientHeight;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>
    Enter max height: <input type="text" ng-model="maxHeight">
  </div>
  <div ng-show="windowOuterHeight < maxHeight">
    Window Outer Height is {{windowOuterHeight}}px <br/><br/>
    Document Height is {{documentHeight}}px
  </div>
</div></code>```

Body:
Forgive me if this is elsewhere...

I came into a project abandoned half-way through. I've not worked in angular before and need to hide/show a "back to top" button dependent upon whether the document is taller than the viewport. I've tried several different approaches and cannot get anything to work successfully. This is my latest attempt:

$(document).ready(function() {

    if ($(document).height() > $(window).height()) {
        console.log("document height is greater");
        $('#arrowUp').show();
    } else {
        console.log("window height is lesser");
        $('#arrowUp').show();
    }
});

Thanks in advance

Body:
First, I highly discourage the mixing of Angular and jQuery - both are DOM manipulation frameworks and they will step on each other causing you endless headaches as you try to troubleshoot various things.

Here is a very contrived example of the "Angular" way of showing or hiding a div based on the height. You should be able to adapt this to suit your needs of showing the arrow based on a difference in window and document heights (it's hard to demonstrate that in the built-in snippet runner).

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.maxHeight = 1200;
    $scope.windowOuterHeight = window.outerHeight;
    $scope.documentHeight = document.documentElement.clientHeight;
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>
    Enter max height: <input type="text" ng-model="maxHeight">
  </div>
  <div ng-show="windowOuterHeight < maxHeight">
    Window Outer Height is {{windowOuterHeight}}px <br/><br/>
    Document Height is {{documentHeight}}px
  </div>
</div>


问:
Persistent Volume claims attached to deployment throws an error when deployment image is updated
i have a deployment configuration that uses a persistent volume claim using a google compute engine disk.

I noticed that when i deploy which updates the image the cluster attempts to pull in the latest image but when doing that it gets stuck with container creating status with this error:

Error from server (BadRequest): container "tita-api" in pod
  "tita-api-7569bd99d7-z44dg" is waiting to start: ContainerCreating.
  Checking further i saw  the disk resource is used by another node .
   AttachVolume.Attach failed for volume "app-pv" : googleapi: Error 400: The disk resource 'projects/tita-canary/zones/us-central1-a/disks/app-disk' is already being used by 'projects/tita-canary/zones/us-central1-a/instances/gke-tita-staging-default-pool-2cae0006-sxgk'

I am using 1.8 kubernetes and currently what i did was to change my deployment strategy to recreate this works but takes a bit of time to update the pods .I would really love this to work using rolling update strategy .

答:
According to Saad-Ali comment on Jul 14th in this Kubernetes issue you must use:   MaxSurge=0 and MaxUnavailable=1

“When doing rolling updates either:

i) Use the "Recreate" strategy, which ensures that old pods are killed before new pods are created (there was a bug #27362 where this doesn't work correctly in some cases that apperently was fixed a long time ago)

ii) Use the "RollingUpdate" strategy with MaxSurge=0 and MaxUnavailable=1.

If a strategy is not specified for a deployment, the default is RollingUpdate. Rolling update strategy has two parameters maxUnavailable and maxSurge; when not specified they default to 1 and 1 respectively. This means that during a rolling update it requires at least one pod from the old deployment to remain and permits an extra new pod (beyond the requested number of replicas) to be created. When this happens, if the new pod lands on a different node, since the old pod has the disk attached as read-write the new pod will fail to start.”


问:
Having problems sorting items in a listbox
I am reading a list of high scores for my game from a text file using StreamReader. I am then sorting it using .Sort()

I converted it to an array and passed it into a list box on a form in the game.
The score is saved to the text file in a string (score+" - "+username)

```<code>public frmHighScores()
    {
        InitializeComponent();

        List<string> scores = new List<string>();
        StreamReader inputFile = File.OpenText("High Scores.txt");
        while (!inputFile.EndOfStream)
        {
            scores.Add(inputFile.ReadLine());
        }
        scores.Sort();
        lstScores.Items.AddRange(scores.ToArray());
    }
</code>```

As it is a string the Sort method is only sorting the first number in the score and I'm not sure how to rectify it.

Here is the image of the sorted list

I want it to read as follows

```<code>200
120
105
65
</code>```

答:
You could use a Dictionary to store these values (score and username). This will eable you to order using a real numeric type. You can build this dictionary by splitting the strings, as follows:</p>

```<code>public void frmHighScores()
    {
        // Pretend we read this from the file
        List<string> fakeFileValues = new List<string>() { "20 steve", "100 john", "25 jane" };
        Dictionary<int, string> scores = new Dictionary<int, string>();

        foreach (string s in fakeFileValues)
        {
            // Better ways to do this, just expanding for clarity
            string[] split = s.Split(' ');
            scores.Add(int.Parse(split[0]), split[1]);
        }

        // You can then order by a real numeric value
        scores.OrderBy(x => x.Key);
    }
</code>```

Body:
I am reading a list of high scores for my game from a text file using StreamReader. I am then sorting it using .Sort()

I converted it to an array and passed it into a list box on a form in the game.
The score is saved to the text file in a string (score+" - "+username)

public frmHighScores()
    {
        InitializeComponent();

        List<string> scores = new List<string>();
        StreamReader inputFile = File.OpenText("High Scores.txt");
        while (!inputFile.EndOfStream)
        {
            scores.Add(inputFile.ReadLine());
        }
        scores.Sort();
        lstScores.Items.AddRange(scores.ToArray());
    }

As it is a string the Sort method is only sorting the first number in the score and I'm not sure how to rectify it.

Here is the image of the sorted list

I want it to read as follows

200
120
105
65

Body:
You could use a Dictionary to store these values (score and username). This will eable you to order using a real numeric type. You can build this dictionary by splitting the strings, as follows:

public void frmHighScores()
    {
        // Pretend we read this from the file
        List<string> fakeFileValues = new List<string>() { "20 steve", "100 john", "25 jane" };
        Dictionary<int, string> scores = new Dictionary<int, string>();

        foreach (string s in fakeFileValues)
        {
            // Better ways to do this, just expanding for clarity
            string[] split = s.Split(' ');
            scores.Add(int.Parse(split[0]), split[1]);
        }

        // You can then order by a real numeric value
        scores.OrderBy(x => x.Key);
    }


问:
within docker run particular ubuntu
I want to use a docker with particular ubuntu version. I have my docker ubuntu images as:

```<code>ubuntu@ubuntu:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              dd6f76d9cc90        10 days ago         122MB
ubuntu              14.04               3aa18c7568fc        10 days ago         188MB
</code>```

Now I want to run a docker with ubuntu 14.04:

```<code>ubuntu@ubuntu:~$ docker run -it ubuntu:14.04
root@0b004c5dc55e:/# uname -a
Linux 0b004c5dc55e 4.10.0-38-generic #42~16.04.1-Ubuntu SMP Tue Oct 10 16:32:20 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

When I check it with uname -a I see there is still Ubuntu-16.04.

How can I run exact version of ubuntu within docker?

答:
It seems that it works well:

```<code> ~/ docker run -it ubuntu:14.04
Unable to find image 'ubuntu:14.04' locally
14.04: Pulling from library/ubuntu
bae382666908: Pull complete
f1ddd5e846a8: Pull complete
90d12f864ab9: Pull complete
a57ea72e3176: Pull complete
783a14252520: Pull complete
Digest: sha256:f6eed4def93a3b54da920737f0abf1a8cae2e480bb368280c898265fcaf910a3
Status: Downloaded newer image for ubuntu:14.04
root@d91b2359e1b8:/# uname -a
Linux d91b2359e1b8 4.9.44-linuxkit-aufs #1 SMP Fri Aug 25 10:00:41 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
root@d91b2359e1b8:/# cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.5 LTS"
NAME="Ubuntu"
VERSION="14.04.5 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.5 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
root@d91b2359e1b8:/#
</code>```

The kernel is shared from the host between all containers. To view the version that is run use: cat /etc/*-release.

Title: within docker run particular ubuntu

Body:
I want to use a docker with particular ubuntu version. I have my docker ubuntu images as:

ubuntu@ubuntu:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              dd6f76d9cc90        10 days ago         122MB
ubuntu              14.04               3aa18c7568fc        10 days ago         188MB

Now I want to run a docker with ubuntu 14.04:

ubuntu@ubuntu:~$ docker run -it ubuntu:14.04
root@0b004c5dc55e:/# uname -a
Linux 0b004c5dc55e 4.10.0-38-generic #42~16.04.1-Ubuntu SMP Tue Oct 10 16:32:20 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

When I check it with uname -a I see there is still Ubuntu-16.04.

How can I run exact version of ubuntu within docker?

Body:
It seems that it works well:

 ~/ docker run -it ubuntu:14.04
Unable to find image 'ubuntu:14.04' locally
14.04: Pulling from library/ubuntu
bae382666908: Pull complete
f1ddd5e846a8: Pull complete
90d12f864ab9: Pull complete
a57ea72e3176: Pull complete
783a14252520: Pull complete
Digest: sha256:f6eed4def93a3b54da920737f0abf1a8cae2e480bb368280c898265fcaf910a3
Status: Downloaded newer image for ubuntu:14.04
root@d91b2359e1b8:/# uname -a
Linux d91b2359e1b8 4.9.44-linuxkit-aufs #1 SMP Fri Aug 25 10:00:41 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
root@d91b2359e1b8:/# cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.5 LTS"
NAME="Ubuntu"
VERSION="14.04.5 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.5 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
root@d91b2359e1b8:/#

The kernel is shared from the host between all containers. To view the version that is run use: cat /etc/*-release.


问:
Customer Search with data from database
we're trying to create a search feature for our site.
The products are in the database and the goal would be to have the search feature use words that are in the title and description of the products inside the database. I was wondering if they where tools out there to build this kind of features. Meaning having some framework that can remove useless words from the description like 'the', 'for', 'and' etc

Without going overboard with big servers like ElastiqSearch.

答: Depending on your DB you can use built in Full Text Index + Full Text Search to efficiently eliminate useless words. </p>

Title: Customer Search with data from database


问:
How would you tidy up this controller logic?
I've got some logic in a controller that sets a status of an object if certain conditions are met:

```<code>if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

答:
That looks to be business logic, so it should be in the model really.

Your model probably needs a couple of attributes: consulted_legal and consulted_marketing, and a method to set the status when either one of them is changed something like this:

```<code>before_update :set_status

def set_status
  if consulted_legal && consulted_marketing
    status = "Pending Approval"
  elif consulted_legal && !consulted_marketing
    status = "Awaiting Marketing Approval"
  elif !consulted_legal && consulted_marketing
    status = "Awaiting Legal Approval"
  elif !consulted_legal && !consulted_marketing
    status "Awaiting Marketing & Legal Approval"
  end

  true # Needs to return true for the update to go through
end
</code>```

OwnerDisplayName: The Pied Pipes

Body:
I've got some logic in a controller that sets a status of an object if certain conditions are met:

if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

Body:
That looks to be business logic, so it should be in the model really.

Your model probably needs a couple of attributes: consulted_legal and consulted_marketing, and a method to set the status when either one of them is changed something like this:

before_update :set_status

def set_status
  if consulted_legal && consulted_marketing
    status = "Pending Approval"
  elif consulted_legal && !consulted_marketing
    status = "Awaiting Marketing Approval"
  elif !consulted_legal && consulted_marketing
    status = "Awaiting Legal Approval"
  elif !consulted_legal && !consulted_marketing
    status "Awaiting Marketing & Legal Approval"
  end

  true # Needs to return true for the update to go through
end


问:
R only specify optional parameters if specified
I have an R function with optional parameters like so:

```<code>myFunc <- function(
    requiredParam,
    optionalParam1 = optionalValue1,
    optionalParam2 = optionalValue2,
    ...
    optionalParamN = optionalValueN) {
    # implementation
}
</code>```

I have another function which calls this function and has the necessary parameters stored in a dataframe:

```<code>  optionalParam1 optionalParam3 optionalParam10
1         "val1"         "val2"          "val3"
</code>```

I only want to pass the optional parameters specified in the dataframe. For the others, I want it to use the default values. How can I accomplish this without typing up all permutations of optionalParameters existing/not existing?

答:
Call the function using do.call (not knowing what your data.frame is called I will just assume you have a list or something of the parameters called myParams):

```<code>do.call(myFunc, as.list(myParams))
</code>```

Body:
I have an R function with optional parameters like so:

myFunc <- function(
    requiredParam,
    optionalParam1 = optionalValue1,
    optionalParam2 = optionalValue2,
    ...
    optionalParamN = optionalValueN) {
    # implementation
}

I have another function which calls this function and has the necessary parameters stored in a dataframe:

  optionalParam1 optionalParam3 optionalParam10
1         "val1"         "val2"          "val3"

I only want to pass the optional parameters specified in the dataframe. For the others, I want it to use the default values. How can I accomplish this without typing up all permutations of optionalParameters existing/not existing?

Body:
Call the function using do.call (not knowing what your data.frame is called I will just assume you have a list or something of the parameters called myParams):

do.call(myFunc, as.list(myParams))