问:
Octave containers.Map() undefined
I need to use containers.Map() to convert some MATLAB code to Octave. I see in the GNU Octave bug tracker #49559 that containers.Map() has been implemented, but I am still getting error: 'containers' undefined when I try to use it. Is this functionality available in the current release builds, and if so how should I access it?

答:
Since the new functionality is written as .m file you can just download the file and insert it into your existing 4.2.x installation.

You are not mentioning if you are using GNU Octave on GNU/Linux or windoze so I assume GNU/Linux here:

create a directory "+containers" in Octaves "m" folder (you have to use sudo if it's a global install)

wget http://hg.savannah.gnu.org/hgweb/octave/raw-file/b04466113212/scripts/%2Bcontainers/Map.m

voilá, Map in OCtave 4.2.1:

```<code>octave:1> ver
GNU Octave Version: 4.2.1
...
octave:2> containers.Map
ans =

  containers.Map object with properties:

    Count     : 0
    KeyType   : char
    ValueType : any
</code>```

Title: Octave containers.Map() undefined

Body:
Since the new functionality is written as .m file you can just download the file and insert it into your existing 4.2.x installation.

You are not mentioning if you are using GNU Octave on GNU/Linux or windoze so I assume GNU/Linux here:

create a directory "+containers" in Octaves "m" folder (you have to use sudo if it's a global install)

wget http://hg.savannah.gnu.org/hgweb/octave/raw-file/b04466113212/scripts/%2Bcontainers/Map.m

voilá, Map in OCtave 4.2.1:

octave:1> ver
GNU Octave Version: 4.2.1
...
octave:2> containers.Map
ans =

  containers.Map object with properties:

    Count     : 0
    KeyType   : char
    ValueType : any


来源: stackexchange

问:
SQL 4 week period in year grouping - Shift Start Number
I'm working on a project in which I need to query an SQL table and return data grouped by 4 week periods. The week grouping is possible using:

```<code>SELECT (order_week_number + 3) DIV 4
</code>```

to turn the week number into a 4 week period however I've just found out I need to shift the first grouping to stat in July, i.e.:

I could do this using a PHP if statement however I'm  trying to do this in SQL so that I can just output and use the data straight after the query.

Is this at all possible, I know I can obviously just minus 6 from the current grouping from period 7 onward but this isn't going to work for grouped periods less than 7?

答:
OK, in case anyone else want to do something similar, I managed to get this going with:

```<code>SELECT CASE
WHEN (order_week_number + 3) DIV 4 >= 7
THEN ((order_week_number + 3) DIV 4) - 6
ELSE ((order_week_number + 3) DIV 4) + 7
END
</code>```

An then limited the query for July of the current year to June of the next year.

Please do correct me if this is wrong/not sensible!

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a project in which I need to query an SQL table and return data grouped by 4 week periods. The week grouping is possible using:

SELECT (order_week_number + 3) DIV 4

to turn the week number into a 4 week period however I've just found out I need to shift the first grouping to stat in July, i.e.:

I could do this using a PHP if statement however I'm  trying to do this in SQL so that I can just output and use the data straight after the query.

Is this at all possible, I know I can obviously just minus 6 from the current grouping from period 7 onward but this isn't going to work for grouped periods less than 7?

Body:
OK, in case anyone else want to do something similar, I managed to get this going with:

SELECT CASE
WHEN (order_week_number + 3) DIV 4 >= 7
THEN ((order_week_number + 3) DIV 4) - 6
ELSE ((order_week_number + 3) DIV 4) + 7
END

An then limited the query for July of the current year to June of the next year.

Please do correct me if this is wrong/not sensible!


问:
mysqli_multi_query not working in while loop php
guys, I am stuck here as I am trying to store all the data into row_cats and then call one by one.

```<code>$get_cats = "select * from categories";

$get_cats .= "select * from products order by rand() LIMIT 0,4"

$run_cats =mysqli_multi_query($con,$get_cats);

while($row_cats=mysqli_fetch_array($run_cats)){

     $cat_id = $row_cats['cat_id'];//from first query

     $cat_title = $row_cats['cat_title'];
     $pro_id=$row_products['products_id'];//from second query
     $pro_title=$row_products['product_title'];
     $pro_cat=$row_products['cat_id'];
     $pro_image=$row_products['product_img1'];
</code>```

答:
You can try </p>

```<code> $get_cats = "select * from categories;";    **// give semicoln inside the double quotes**

 $get_cats .= "select * from products order by rand() LIMIT 0,4"

// Execute multi query
if (mysqli_multi_query($con,$get_cats))
{
 do
 {
  // Store first result set
   if ($result=mysqli_store_result($con)) {
   // Fetch one and one row
   while ($row=mysqli_fetch_row($result))
    {
    printf("%s\n",$row[0]);
    }
   // Free result set
   mysqli_free_result($result);
   }
 }
 while (mysqli_next_result($con));
}
</code>```

Body:
guys, I am stuck here as I am trying to store all the data into row_cats and then call one by one.

$get_cats = "select * from categories";

$get_cats .= "select * from products order by rand() LIMIT 0,4"

$run_cats =mysqli_multi_query($con,$get_cats);

while($row_cats=mysqli_fetch_array($run_cats)){

     $cat_id = $row_cats['cat_id'];//from first query

     $cat_title = $row_cats['cat_title'];
     $pro_id=$row_products['products_id'];//from second query
     $pro_title=$row_products['product_title'];
     $pro_cat=$row_products['cat_id'];
     $pro_image=$row_products['product_img1'];

Body:
You can try

 $get_cats = "select * from categories;";    **// give semicoln inside the double quotes**

 $get_cats .= "select * from products order by rand() LIMIT 0,4"

// Execute multi query
if (mysqli_multi_query($con,$get_cats))
{
 do
 {
  // Store first result set
   if ($result=mysqli_store_result($con)) {
   // Fetch one and one row
   while ($row=mysqli_fetch_row($result))
    {
    printf("%s\n",$row[0]);
    }
   // Free result set
   mysqli_free_result($result);
   }
 }
 while (mysqli_next_result($con));
}


问:
android studio "error: can't find or load main class" in Kotlin file's main method
In my Android Studio project's java module,I used to code java's main method is OK,But when i convert it to Kotlin code ,like this :

```<code>fun main(args: Array<String>) {
    println("i am kotlin")
}
</code>```

When i executed it,
the error happend:"error: can't find or load main class".
I have tried to find some way to solve it ,for example:let the main method outside the class,But it does not work.
I want to know whether it is bebcause that my configuration has some problems.
When i use IntelliJ IDEA i build a kotlin project ,the main method is OK.
so what is my problem in my Android studio's java module in kotlin code.

答:
In kotlin, the main function should be outside of a class which didn't work for you. So when you're trying to use the main function of a class it has to be wrapped up by companion object also be annotated by @JvmStatic. So the code block will look like this.

```<code>class AnythingYouWant {

    companion object {
       @JvmStatic
       fun main(args: Array<String>) {
          println("i am kotlin")
       }
    }
}
</code>```

Another thing to remind you that,

The main method isn't the entry point in Android like in Java

because it uses completely different build configuration in Android Studio project than the IntelliJ project.

Body:
In my Android Studio project's java module,I used to code java's main method is OK,But when i convert it to Kotlin code ,like this :

fun main(args: Array<String>) {
    println("i am kotlin")
}

When i executed it,
the error happend:"error: can't find or load main class".
I have tried to find some way to solve it ,for example:let the main method outside the class,But it does not work.
I want to know whether it is bebcause that my configuration has some problems.
When i use IntelliJ IDEA i build a kotlin project ,the main method is OK.
so what is my problem in my Android studio's java module in kotlin code.

Body:
In kotlin, the main function should be outside of a class which didn't work for you. So when you're trying to use the main function of a class it has to be wrapped up by companion object also be annotated by @JvmStatic. So the code block will look like this.

class AnythingYouWant {

    companion object {
       @JvmStatic
       fun main(args: Array<String>) {
          println("i am kotlin")
       }
    }
}

Another thing to remind you that,

The main method isn't the entry point in Android like in Java

because it uses completely different build configuration in Android Studio project than the IntelliJ project.


问:
How can I perform a generic cast to the correct subclass type?
Currently I have the following code for a method that I have created:

```<code>public boolean overlaps(CollisionBody2D collider)
{
    //other method code
    if (collider instanceof ArcBody2D)
        return this.overlaps((ArcBody2D) collider);
    else if (collider instanceof CircleBody2D)
        return this.overlaps((CircleBody2D) collider);
    else if (collider instanceof PointBody2D)
        return this.overlaps((PointBody2D) collider);
    else if (collider instanceof LineBody2D)
        return this.overlaps((LineBody2D) collider);
    else if (collider instanceof BoxBody2D)
        return this.overlaps((BoxBody2D) collider);
    return false;
}
</code>```

Each of ArcBody2D etc. are subclasses of CollisionBody2D and have defined methods for collisions for each of the other types (ArcBody2D etc.).I want to replace the eyesore if statement (if instanceof)... with a generic cast down to the proper subclass type so that I do not have to continuously grow the if statement as I add more collider types.

Ideally I am trying to achieve something like:

```<code>return this.overlaps((collider.subclassType()) collider);
</code>```

I have tried using generics, but the problem is that it requires you to predefine the class type, which isn't really helpful to me as I need a method which handles collision without needing to predefine the type of CollisionBody2D when called. For example:

```<code>BoxBody2D box = new BoxBody2D(parameters);
CollisionBody2D colliders [];
//populate array
for (CollisionBody2D c: colliders)
{
    if (box.overlaps(c))
        //do something
}
</code>```

I have tried using generics but the problem is they still require you to define the type when the method is called. Is there any other way to achieve this aside from this long if statement?

答:
Here are the steps (mechanism) you have to follow. I have used generic methods to fulfill this. The steps are as following.

Make sure your "overlaps" method is also defined in the super class (CollisionBody2D) and has been overridden accordingly in your subclasses (ArcBody2D etc.) this is if you need to use runtime polymorphism at a later stage

Make "overlaps" method a generic method as following :

public  boolean overlaps(T t){
    //your code
}

Finally, inside a method you can call this as following :

new CollisionBody2D.overlaps(new ArcBody2D());

So, you will not need to cast or anything, and it will call the overlaps method in CollisionBody2D class. However, if you need to run the overlaps method of the object you are passing, I recommend you to use runtime polimorphism and go on accordingly, but as for your question above I don't think you have such a requirement than to call the overlaps method of the class which you are referring.

Body:
Currently I have the following code for a method that I have created:

public boolean overlaps(CollisionBody2D collider)
{
    //other method code
    if (collider instanceof ArcBody2D)
        return this.overlaps((ArcBody2D) collider);
    else if (collider instanceof CircleBody2D)
        return this.overlaps((CircleBody2D) collider);
    else if (collider instanceof PointBody2D)
        return this.overlaps((PointBody2D) collider);
    else if (collider instanceof LineBody2D)
        return this.overlaps((LineBody2D) collider);
    else if (collider instanceof BoxBody2D)
        return this.overlaps((BoxBody2D) collider);
    return false;
}

Each of ArcBody2D etc. are subclasses of CollisionBody2D and have defined methods for collisions for each of the other types (ArcBody2D etc.).I want to replace the eyesore if statement (if instanceof)... with a generic cast down to the proper subclass type so that I do not have to continuously grow the if statement as I add more collider types.

Ideally I am trying to achieve something like:

return this.overlaps((collider.subclassType()) collider);

I have tried using generics, but the problem is that it requires you to predefine the class type, which isn't really helpful to me as I need a method which handles collision without needing to predefine the type of CollisionBody2D when called. For example:

BoxBody2D box = new BoxBody2D(parameters);
CollisionBody2D colliders [];
//populate array
for (CollisionBody2D c: colliders)
{
    if (box.overlaps(c))
        //do something
}

I have tried using generics but the problem is they still require you to define the type when the method is called. Is there any other way to achieve this aside from this long if statement?


问:
ORA-30483: window functions are not allowed here?
I need a list of movies with a certain average rating to show up.  I know that the problem is with the HAVING clause, but I'm not sure as to how to fix it.  Without that clause it works, and it lists all movie/actor combos that follow the specified qualities, but I need them to also have an average rating above 4 (which is what I'm trying to do with the having clause).

With the HAVING clause it says ORA-30483: window functions are not allowed here.  Anybody know how I can fix this?

```<code>SELECT DISTINCT m.title "Movie Title",
   ROUND(AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid),2) "Average Rating",
   a.afname||' '||a.alname "Name",
   m.ryear
FROM netflix.actors a JOIN netflix.movies_actors ma
   ON a.actorid = ma.actorid
JOIN netflix.movies m
   ON ma.movieid = m.movieid
JOIN netflix.ratings100 r
   ON m.movieid = r.movieid
JOIN netflix.movies_genres g
   ON m.movieid = g.movieid
WHERE a.gender LIKE 'F'
   AND g.genrecode LIKE 'DRM'
   AND m.ryear >= TO_CHAR(SYSDATE, 'yyyy')-12
HAVING AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid) >= 4
ORDER BY "Average Rating" desc
</code>```

答:
windowing or analytic function are allowed only in select statements.
so you can filter like this:</p>

```<code>    select * from (
    SELECT DISTINCT m.title "Movie Title",
       ROUND(AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid),2) "Average Rating",
       a.afname||' '||a.alname "Name",
       m.ryear
    FROM netflix.actors a JOIN netflix.movies_actors ma
       ON a.actorid = ma.actorid
    JOIN netflix.movies m
       ON ma.movieid = m.movieid
    JOIN netflix.ratings100 r
       ON m.movieid = r.movieid
    JOIN netflix.movies_genres g
       ON m.movieid = g.movieid
    WHERE a.gender LIKE 'F'
       AND g.genrecode LIKE 'DRM'
       AND m.ryear >= TO_CHAR(SYSDATE, 'yyyy')-12

    ) as f1
    where f1.[Average Rating] >=4
ORDER BY f1.[Average Rating] desc
</code>```

Body:
I need a list of movies with a certain average rating to show up.  I know that the problem is with the HAVING clause, but I'm not sure as to how to fix it.  Without that clause it works, and it lists all movie/actor combos that follow the specified qualities, but I need them to also have an average rating above 4 (which is what I'm trying to do with the having clause).

With the HAVING clause it says ORA-30483: window functions are not allowed here.  Anybody know how I can fix this?

SELECT DISTINCT m.title "Movie Title",
   ROUND(AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid),2) "Average Rating",
   a.afname||' '||a.alname "Name",
   m.ryear
FROM netflix.actors a JOIN netflix.movies_actors ma
   ON a.actorid = ma.actorid
JOIN netflix.movies m
   ON ma.movieid = m.movieid
JOIN netflix.ratings100 r
   ON m.movieid = r.movieid
JOIN netflix.movies_genres g
   ON m.movieid = g.movieid
WHERE a.gender LIKE 'F'
   AND g.genrecode LIKE 'DRM'
   AND m.ryear >= TO_CHAR(SYSDATE, 'yyyy')-12
HAVING AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid) >= 4
ORDER BY "Average Rating" desc

Body:
windowing or analytic function are allowed only in select statements.
so you can filter like this:

    select * from (
    SELECT DISTINCT m.title "Movie Title",
       ROUND(AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid),2) "Average Rating",
       a.afname||' '||a.alname "Name",
       m.ryear
    FROM netflix.actors a JOIN netflix.movies_actors ma
       ON a.actorid = ma.actorid
    JOIN netflix.movies m
       ON ma.movieid = m.movieid
    JOIN netflix.ratings100 r
       ON m.movieid = r.movieid
    JOIN netflix.movies_genres g
       ON m.movieid = g.movieid
    WHERE a.gender LIKE 'F'
       AND g.genrecode LIKE 'DRM'
       AND m.ryear >= TO_CHAR(SYSDATE, 'yyyy')-12

    ) as f1
    where f1.[Average Rating] >=4
ORDER BY f1.[Average Rating] desc


答:
Analytics functions can't use in WHERE or HAVING bloks. They make calculations for the resultset in SELECT-block. And also you use HAVING without GROUP BY it's an error, too.
I think you can use a subquery and WHERE for it.

```<code>SELECT *
FROM
  (
    SELECT DISTINCT m.title "Movie Title",
       ROUND(AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid),2) "Average Rating",
       a.afname||' '||a.alname "Name",
       m.ryear
    FROM netflix.actors a JOIN netflix.movies_actors ma
       ON a.actorid = ma.actorid
    JOIN netflix.movies m
       ON ma.movieid = m.movieid
    JOIN netflix.ratings100 r
       ON m.movieid = r.movieid
    JOIN netflix.movies_genres g
       ON m.movieid = g.movieid
    WHERE a.gender LIKE 'F'
       AND g.genrecode LIKE 'DRM'
       AND m.ryear >= TO_CHAR(SYSDATE, 'yyyy')-12
  )
WHERE "Average Rating" >= 4
ORDER BY "Average Rating" desc
</code>```

Title: ORA-30483: window functions are not allowed here?

Body:
Analytics functions can't use in WHERE or HAVING bloks. They make calculations for the resultset in SELECT-block. And also you use HAVING without GROUP BY it's an error, too.
I think you can use a subquery and WHERE for it.

SELECT *
FROM
  (
    SELECT DISTINCT m.title "Movie Title",
       ROUND(AVG(r.rating) OVER (PARTITION BY m.movieid, a.actorid),2) "Average Rating",
       a.afname||' '||a.alname "Name",
       m.ryear
    FROM netflix.actors a JOIN netflix.movies_actors ma
       ON a.actorid = ma.actorid
    JOIN netflix.movies m
       ON ma.movieid = m.movieid
    JOIN netflix.ratings100 r
       ON m.movieid = r.movieid
    JOIN netflix.movies_genres g
       ON m.movieid = g.movieid
    WHERE a.gender LIKE 'F'
       AND g.genrecode LIKE 'DRM'
       AND m.ryear >= TO_CHAR(SYSDATE, 'yyyy')-12
  )
WHERE "Average Rating" >= 4
ORDER BY "Average Rating" desc


问:
Retry mocha failed test
I was trying to implement code to retry the failed test using "mocha-retry"
Below is the sample .

```<code>describe(retries,' retries-',function () {
var self = this;
    beforeAll(function () {
        global.requireLogin();
    });

this.retries(3);
})
</code>```

I am getting error as
 Error: ReferenceError: retries is not defined

MAy I know where is the wrong

答: Describe only accepts two parameters, one being a String describing the tests scenario and another being a function which may contain either more describes or test cases.

Title: Retry mocha failed test

Body:
I was trying to implement code to retry the failed test using "mocha-retry"
Below is the sample .

describe(retries,' retries-',function () {
var self = this;
    beforeAll(function () {
        global.requireLogin();
    });

this.retries(3);
})

I am getting error as
 Error: ReferenceError: retries is not defined

MAy I know where is the wrong


问:
Smooth scroll anchor links WITHOUT jQuery
Is it possible to use smooth scroll to anchor links but without jQuery? I am creating a new site and I don't want to use jQuery.

答:
Actually, there is more lightweight and simple way to do that:
https://codepen.io/ugg0t/pen/mqBBBY

function scrollTo(element) {
  window.scroll({
    behavior: 'smooth',
    left: 0,
    top: element.offsetTop
  });
}

document.getElementById("button").addEventListener('click', () => {
  scrollTo(document.getElementById("8"));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 100%;
  height: 200px;
  background-color: black;
}

div:nth-child(odd) {
  background-color: white;
}

button {
  position: absolute;
  left: 10px;
  top: 10px;
}</code>```

<button id="button">Button</button>```

Body:
Actually, there is more lightweight and simple way to do that:
https://codepen.io/ugg0t/pen/mqBBBY

function scrollTo(element) {
  window.scroll({
    behavior: 'smooth',
    left: 0,
    top: element.offsetTop
  });
}

document.getElementById("button").addEventListener('click', () => {
  scrollTo(document.getElementById("8"));
});

div {
  width: 100%;
  height: 200px;
  background-color: black;
}

div:nth-child(odd) {
  background-color: white;
}

button {
  position: absolute;
  left: 10px;
  top: 10px;
}

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div>
<button id="button">Button</button>


问:
Event sourcing / CQRS read model - projections
I have a microservice-based application running on AWS Lambda. Two of the microservices, the most crucial ones, use event-sourcing/cqrs.

Background: (this is also for me to organize my thoughts)

I'm using this library  and storing events in DynamoDB and projections in AWS S3.

The write part works like a charm: Each command invocation loads the current state of the aggregate from DynamoDB (by running events through a handler and/or loading an cached aggregate), it decides to accept or reject the command based on some business logic, then writes to DynamoDB with KeyConditionExpression: 'aggregateId = :a AND version >= :v' where the version is a count of events processed for that aggregate. If there's a conflict, the write fails. Seems like a good system to me!

Each event is then broadcast to SNS (topic name is the service name) so other services can react to the event, if they want.

The part that I really struggle with is the read. Projections are stored in S3 and tagged with the last commitId processed for each event source. When a read query comes in, it loads the entire projected state from S3 (for all aggregates), queries the event sources for all newer events, computes the latest state (again, for all aggregates - and writing an updated object to S3 if it's newer), and returns relevant parts of the state based on the query params.

My problem: (or one of them)

I think I'm doing projections wrong.

Most of my projections only group ids by important attribute, so the files stay relatively small. But I also need a way to retrieve an individual aggregate. Using projections for that seems crazy, because I need to load the entire state each time (i.e. every projected aggregate) apply new events to that, then retrieve the record I want (it may not have even changed).

This is what I'm doing now, it's performing fine (<100k records) but I can't imagine it will continue much longer.

The other problem is queries. I need to build a projection mapping value to matching aggregateIds for every attribute I need to query on!! There's got to be a better way!

No matter what way I think about this problem, projections always need the entire current state + any new events before it can return even a single record that hasn't changed.

答:
I'm not familiar with your technical infrastructure but the way I implement projections is as follows:

Each domain event has a global sequence number that spans all aggregate roots.  A projection is a read model that has an arbitrary name and the last processed position represented by that global sequence number.  I can add a new projection at any time, along with its event handlers, and it will start at position 0.  I can clear a projection at any time and set back the position to 0.  I can also use a combination of adding a new projection that will replace an existing one, have that build even if it takes days, and then remove the old one.

There is a service that monitors the projections and uses the event store almost like a queue.  The projection service checks for events with global ids after the current position and hands those off to handlers and then updates the position.  This is where your projection may even filter on event types to improve performance.

That is the basic idea.  Your projections are then what you query.  Once a projection has caught up to the "head" of the event store the events from the event store are going to be trickle fed into the projection.

How that will translate into your technical space I'm not quite sure.  I have a bit of an experiment called Shuttle.Recall going on C# if you'd like to have a look to get some ideas.


问:
DropDown List Validation
I need to perform a validation to check whether a TextBox value is empty on Dropown list selected Index change using validation controls in asp.net </p>

答:
I hope this will work fine.</p>

```<code>    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:DropDownList ID="DropDownList1" runat="server" CausesValidation="true" AutoPostBack="true">
    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Please Enter the Value"></asp:RequiredFieldValidator>
</code>```

ContentLicense: CC BY-SA 2.5

Title: DropDown List Validation

Body:
I hope this will work fine.

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:DropDownList ID="DropDownList1" runat="server" CausesValidation="true" AutoPostBack="true">
    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Please Enter the Value"></asp:RequiredFieldValidator>


问:
STUFF function to concatenate values
The STUFF function & FOR XML PATH has been discussed before. My case is slightly involved as there is a many-to-relationship between T1 and T2

Table T1(t1id, t1name) T2(t2id, t2name)
Lets say there is an intermediate link table also F(t1id, t2id)

The output that I am looking for is as follows:

T1id1 -> t2name1,t2name3,t2name6 for all ids in T1

Can this be done in a single query?

Thanks
Anand

I added some sample data

Table Geography

```<code>Id  Name
---------------
1   All
2   APR
3   EMEA
4   Pan Asia
5   Japan
6   China
7   European
8   US
</code>```

Table Analyst

```<code>Id   Name
-------------
1    Tom
2    Dick
3    Harry
4    Peter
5    Mary
6    Amy
7    Susie
</code>```

These 2 tables are N->M

The output I am looking for is

```<code>Analyst.Id   Analyst.Name  Geography.Name
------------------------------------------
1            Tom           EMEA, China
2            Dick          APR, US, China
....
....
</code>```

答:
Yes. like this</p>

```<code>SELECT T1.t1id, STUFF(t2.name, 1, 1, '')
FROM   T1
       CROSS APPLY
       (
           SELECT ',' + T2.name
           FROM   T2
           WHERE  T2.t2id = T1.t1id
           FOR XML PATH ('')
       ) t2 (name)
</code>```

Title: STUFF function to concatenate values

Body:
The STUFF function & FOR XML PATH has been discussed before. My case is slightly involved as there is a many-to-relationship between T1 and T2

Table T1(t1id, t1name) T2(t2id, t2name)
Lets say there is an intermediate link table also F(t1id, t2id)

The output that I am looking for is as follows:

T1id1 -> t2name1,t2name3,t2name6 for all ids in T1

Can this be done in a single query?

Thanks
Anand

I added some sample data

Table Geography

Id  Name
---------------
1   All
2   APR
3   EMEA
4   Pan Asia
5   Japan
6   China
7   European
8   US

Table Analyst

Id   Name
-------------
1    Tom
2    Dick
3    Harry
4    Peter
5    Mary
6    Amy
7    Susie

These 2 tables are N->M

The output I am looking for is

Analyst.Id   Analyst.Name  Geography.Name
------------------------------------------
1            Tom           EMEA, China
2            Dick          APR, US, China
....
....

Body:
Yes. like this

SELECT T1.t1id, STUFF(t2.name, 1, 1, '')
FROM   T1
       CROSS APPLY
       (
           SELECT ',' + T2.name
           FROM   T2
           WHERE  T2.t2id = T1.t1id
           FOR XML PATH ('')
       ) t2 (name)


问:
Keras: Merge/Concatenate Layer: TypeError: __init__() got multiple values for argument 'axis'
I created the following network. The idea is to combine the outputs of the left and right, then send to a LSTM model.

```<code>EMBED_DIM = 4
look_back = 6
feature_num = 2
ENCODE_DIM = 676

left = Sequential()
left.add(Dense(EMBED_DIM,input_shape=(ENCODE_DIM,)))
left.add(RepeatVector(look_back))
left.add(Reshape((look_back,EMBED_DIM)))

right = Sequential()
right.add(Lambda(lambda x: x,input_shape=(look_back,feature_num)))

# create and fit the LSTM network
model = Sequential()
model.add(Concatenate([left, right], axis = 2,input_shape=(look_back, EMBED_DIM + feature_num) ))
model.add(LSTM(8, input_shape=(look_back,feature_num + EMBED_DIM)))

model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')
</code>```

I am trying to concatenate the output from left and right, then send the new tensor to the LSTM model.

However, I got the following error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-156-275f5597cdad> in <module>()

---> 37 model.add(Concatenate([left, right], axis = 2,input_shape=(look_back, EMBED_DIM + feature_num) ))
     38 model.add(LSTM(8, input_shape=(look_back,feature_num + EMBED_DIM)))
     39

TypeError: __init__() got multiple values for argument 'axis'
</code>```

Any idea what I did wrong? Can I add a Concatenate layer as the first layer of a model? Thanks!

答:
Sequential models are not meant to have branches. Use the functional API model.

Let's get the "tensors" from the left and right side:

```<code>leftOutput = left.output
rightOutput = right.output
</code>```

Now, the Concatenate is a layer that follows the same logic of all other layers. (First you create it, then you call it with the input tensors):

```<code>#first parentheses: create the layer / second parentheses: call the layer with inputs
output = Concatenate(axis=2)([leftOutput,rightOutput])
</code>```

Let's keep the rest of the model as a functional API as well:

```<code>output = LSTM(8)(output)
output = Dense(2)(output)
</code>```

Now we create the model, telling it what the inputs and outputs are:

```<code>inputTensorLeft = left.input
inputTensorRight = right.input

fullModel = Model([inputTensorLeft,inputTensorRight], output)
</code>```

Notice you ended up with three models, but one of them contains the other two. They share the same weights. Training one will train the others if you're training a shared path.

Body:
I created the following network. The idea is to combine the outputs of the left and right, then send to a LSTM model.

EMBED_DIM = 4
look_back = 6
feature_num = 2
ENCODE_DIM = 676

left = Sequential()
left.add(Dense(EMBED_DIM,input_shape=(ENCODE_DIM,)))
left.add(RepeatVector(look_back))
left.add(Reshape((look_back,EMBED_DIM)))

right = Sequential()
right.add(Lambda(lambda x: x,input_shape=(look_back,feature_num)))

# create and fit the LSTM network
model = Sequential()
model.add(Concatenate([left, right], axis = 2,input_shape=(look_back, EMBED_DIM + feature_num) ))
model.add(LSTM(8, input_shape=(look_back,feature_num + EMBED_DIM)))

model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')

I am trying to concatenate the output from left and right, then send the new tensor to the LSTM model.

However, I got the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-156-275f5597cdad> in <module>()

---> 37 model.add(Concatenate([left, right], axis = 2,input_shape=(look_back, EMBED_DIM + feature_num) ))
     38 model.add(LSTM(8, input_shape=(look_back,feature_num + EMBED_DIM)))
     39

TypeError: __init__() got multiple values for argument 'axis'

Any idea what I did wrong? Can I add a Concatenate layer as the first layer of a model? Thanks!

Body:
Sequential models are not meant to have branches. Use the functional API model.

Let's get the "tensors" from the left and right side:

leftOutput = left.output
rightOutput = right.output

Now, the Concatenate is a layer that follows the same logic of all other layers. (First you create it, then you call it with the input tensors):

#first parentheses: create the layer / second parentheses: call the layer with inputs
output = Concatenate(axis=2)([leftOutput,rightOutput])

Let's keep the rest of the model as a functional API as well:

output = LSTM(8)(output)
output = Dense(2)(output)

Now we create the model, telling it what the inputs and outputs are:

inputTensorLeft = left.input
inputTensorRight = right.input

fullModel = Model([inputTensorLeft,inputTensorRight], output)

Notice you ended up with three models, but one of them contains the other two. They share the same weights. Training one will train the others if you're training a shared path.


问:
Ruby/Postgres ActiveRecord without Rails: Undefined Table ERROR: relation "..." does not exist
Working on a small Ruby script to create and store data to a Postgres database. The app works just fine when it comes to creating and dropping the database, or running migrations. However, it fails when I attempt to run rake db:seed. The error message indicates that the table doesn't exist...but meanwhile if I run the same SQL script referenced in the error message, but in pgAdmin, it returns valid results. I'm wondering if there is something going on with the privileges granted to the user named in the database.yml, and if so, how would I address that in the script? Any help understanding this would be appreciated.

Here is the error message I'm getting in the terminal:

```<code>acmecorp$ rake db:seed
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"applications"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'

Caused by:
PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
</code>```

My database.yml file:

```<code># config/database.yml
default: &default
  host: 'localhost'
  adapter: 'postgresql'
  encoding: utf-8

development:
  <<: *default
  database: 'acmecorp_dev'
  username: 'acmecorpapp'
</code>```

The Gemfile is pretty simple:

```<code># Gemfile
source 'https://rubygems.org'

gem 'activerecord'
gem 'require_all'
gem 'pg'
</code>```

I have a rakefile.rb to control the various tasks (edited to remove irrelevant items):

```<code># rakefile.rb
require "active_record"
require "require_all"
require "yaml"

namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({'database' => 'postgres', 'schema_search_path' => 'public'})

  ...

  desc "Seed the database"
  task :seed do
    ActiveRecord::Base.establish_connection(db_config_admin)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
  end

  ...

end
</code>```

As noted, all of the other tasks in the rakefile work without problem--it's just the :seed task that burps. I'm fairly confident it has something to do with the way the script is interacting with the database.

Here is the seed file:

```<code># db/seeds.rb
Application.create({
  ApplicationNumber:  1,
  AccountNumber: 1234,
  ApplVer:  1,
  CreateDateTime:  "1/2/2018",
  ExpirationDateTime:  "1/5/2019",
  ApplicationStatus:  "In process",
  ApprovedAmount:     1992.92,
  AcceptedAmount:     92.92,
  HomeAddressLine1:   "1 Main Street",
  HomeAddressLine2:   "",
  HomeAddressCity:    "Thibodaux",
  HomeAddressState:   "LA",
  HomeAddressZipCode: "12345"
})
</code>```

and finally, I have a simple model for the application, which the seeds.rb file references:

```<code># models/application.rb
class Application < ActiveRecord::Base
end
</code>```

Now the error message noted above is stating that `relation "applications" does not exist"...but when I run the same SQL quoted in the message, directly in pgAdmin, here's what I get (apologies for formatting - couldn't figure out how to get it into a table efficiently):

```<code>attname|format_type|pg_get_expr|attnotnull|atttypid|atttypmod|collname|comment
id|integer|nextval('applications_id_seq'::regclass)|t|23|-1||
ApplicationNumber|integer||f|23|-1||
AccountNumber|integer||f|23|-1||
ApplVer|integer||f|23|-1||
CreateDateTime|timestamp without time zone||f|1114|-1||
ExpirationDateTime|timestamp without time zone||f|1114|-1||
ApplicationStatus|character varying||f|1043|-1||
ApprovedAmount|numeric||f|1700|-1||
AcceptedAmount|numeric||f|1700|-1||
HomeAddressLine1|character varying||f|1043|-1||
HomeAddressLine2|character varying||f|1043|-1||
HomeAddressCity|character varying||f|1043|-1||
HomeAddressState|character varying||f|1043|-1||
HomeAddressZipCode|character varying||f|1043|-1||
FileCreatedDate|timestamp without time zone||f|1114|-1||
created_at|timestamp without time zone||t|1114|-1||
updated_at|timestamp without time zone||t|1114|-1||
</code>```

So the bottom line seems to be:
- the script is properly configured to work with PG - at least as far as creating, dropping, and migrating databases
- the rake db:seed task is failing
- the SQL reported in the error message on the command line works just fine when it is run through pgAdmin

I'm not sure why the issue. Could it have something to do with privileges available to the acmecorpapp user that was assigned to the database in the database.yml..?

答:
Please check file rakefile.rb. It seems to you merge the wrong database. the database for development is acmecorp_dev, and you already have it in db_config. I think you don't have to merge database anymore. Try this:

```<code>require "active_record"
require "require_all"
require "yaml"

namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({ 'schema_search_path' => 'public'})

  ...

  desc "Seed the database"
    task :seed do
    ActiveRecord::Base.establish_connection(db_config_admin)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
 end

 ...

end
</code>```

Body:
Working on a small Ruby script to create and store data to a Postgres database. The app works just fine when it comes to creating and dropping the database, or running migrations. However, it fails when I attempt to run rake db:seed. The error message indicates that the table doesn't exist...but meanwhile if I run the same SQL script referenced in the error message, but in pgAdmin, it returns valid results. I'm wondering if there is something going on with the privileges granted to the user named in the database.yml, and if so, how would I address that in the script? Any help understanding this would be appreciated.

Here is the error message I'm getting in the terminal:

acmecorp$ rake db:seed
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"applications"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'

Caused by:
PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

My database.yml file:

# config/database.yml
default: &default
  host: 'localhost'
  adapter: 'postgresql'
  encoding: utf-8

development:
  <<: *default
  database: 'acmecorp_dev'
  username: 'acmecorpapp'

The Gemfile is pretty simple:

# Gemfile
source 'https://rubygems.org'

gem 'activerecord'
gem 'require_all'
gem 'pg'

I have a rakefile.rb to control the various tasks (edited to remove irrelevant items):

# rakefile.rb
require "active_record"
require "require_all"
require "yaml"

namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({'database' => 'postgres', 'schema_search_path' => 'public'})

  ...

  desc "Seed the database"
  task :seed do
    ActiveRecord::Base.establish_connection(db_config_admin)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
  end

  ...

end

As noted, all of the other tasks in the rakefile work without problem--it's just the :seed task that burps. I'm fairly confident it has something to do with the way the script is interacting with the database.

Here is the seed file:

# db/seeds.rb
Application.create({
  ApplicationNumber:  1,
  AccountNumber: 1234,
  ApplVer:  1,
  CreateDateTime:  "1/2/2018",
  ExpirationDateTime:  "1/5/2019",
  ApplicationStatus:  "In process",
  ApprovedAmount:     1992.92,
  AcceptedAmount:     92.92,
  HomeAddressLine1:   "1 Main Street",
  HomeAddressLine2:   "",
  HomeAddressCity:    "Thibodaux",
  HomeAddressState:   "LA",
  HomeAddressZipCode: "12345"
})

and finally, I have a simple model for the application, which the seeds.rb file references:

# models/application.rb
class Application < ActiveRecord::Base
end

Now the error message noted above is stating that `relation "applications" does not exist"...but when I run the same SQL quoted in the message, directly in pgAdmin, here's what I get (apologies for formatting - couldn't figure out how to get it into a table efficiently):

attname|format_type|pg_get_expr|attnotnull|atttypid|atttypmod|collname|comment
id|integer|nextval('applications_id_seq'::regclass)|t|23|-1||
ApplicationNumber|integer||f|23|-1||
AccountNumber|integer||f|23|-1||
ApplVer|integer||f|23|-1||
CreateDateTime|timestamp without time zone||f|1114|-1||
ExpirationDateTime|timestamp without time zone||f|1114|-1||
ApplicationStatus|character varying||f|1043|-1||
ApprovedAmount|numeric||f|1700|-1||
AcceptedAmount|numeric||f|1700|-1||
HomeAddressLine1|character varying||f|1043|-1||
HomeAddressLine2|character varying||f|1043|-1||
HomeAddressCity|character varying||f|1043|-1||
HomeAddressState|character varying||f|1043|-1||
HomeAddressZipCode|character varying||f|1043|-1||
FileCreatedDate|timestamp without time zone||f|1114|-1||
created_at|timestamp without time zone||t|1114|-1||
updated_at|timestamp without time zone||t|1114|-1||

So the bottom line seems to be:
- the script is properly configured to work with PG - at least as far as creating, dropping, and migrating databases
- the rake db:seed task is failing
- the SQL reported in the error message on the command line works just fine when it is run through pgAdmin

I'm not sure why the issue. Could it have something to do with privileges available to the acmecorpapp user that was assigned to the database in the database.yml..?

Body:
Please check file rakefile.rb. It seems to you merge the wrong database. the database for development is acmecorp_dev, and you already have it in db_config. I think you don't have to merge database anymore. Try this:

require "active_record"
require "require_all"
require "yaml"

namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({ 'schema_search_path' => 'public'})

  ...

  desc "Seed the database"
    task :seed do
    ActiveRecord::Base.establish_connection(db_config_admin)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
 end

 ...

end


问:
C# listView, how do I add items to columns 2, 3 and 4 etc?
To add items to column 1 in my listView control (Winform) I'm using listView1.Items.Add, this works fine but how do I add items to columns 2 and 3 etc?

答:
Here is the msdn documentation on the listview object and the listviewItem object.

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.aspx

I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.

But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:

```<code>ListViewItem i = new ListViewItem("column1");
i.SubItems.Add("column2");
i.SubItems.Add("column3");
</code>```

OwnerDisplayName: Steve

LastEditorDisplayName: buyutec

Body:
Here is the msdn documentation on the listview object and the listviewItem object.

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.aspx

I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.

But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:

ListViewItem i = new ListViewItem("column1");
i.SubItems.Add("column2");
i.SubItems.Add("column3");

OwnerDisplayName: CalvinR


问:
How to print json array from Response<ResponseBody> response in retorift2.0
I developed android application with retorfit 2.0. I tweeter in our application. I am getting json array format data from url when check in browser. I am getting response in my application like code: 200ok and responce is like : repoces@012345 printed as raw data. How can I print response as array format.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://cdn.syndication.twimg.com/")
                .addConverterFactory(GsonConverterFactory.create())

                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        Call<ResponseBody> response = requestInterface.gettwetter("vinodh654");

        response.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Tweeter Respose",response.code()+" "+response.message()+" "+response.body().toString());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("Tweeter Respose","Fail");
            }
        });```

答:
You can print that json response like this - new Gson().toJson(response.body())

```<code>response.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
            String data = new Gson().toJson(response.body()); // It will get the response
            Log.d("Response",response.code()+" "+response.message()+" "+data;
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("Response","Fail");
     }
  });
</code>```

Body:
You can print that json response like this - new Gson().toJson(response.body())

response.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
            String data = new Gson().toJson(response.body()); // It will get the response
            Log.d("Response",response.code()+" "+response.message()+" "+data;
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("Response","Fail");
     }
  });


答:
I don't believe you can create an index on the sum of two columns.

You could add an additional field that contains column5 + column6 and index on that.

You could create a view with an additional column equal to column5 + column6 and index on that.

Title: MySQL create index sum of two columns data in one table

Body:
 >> table1
 -------------------------------------------------------------
 | column1 | column2 | column3 | column4 | column5 | column6 |
 +---------+---------+---------+---------+---------+---------+
 |  data1  |  data2  |  data3  |  data4  |  data5  |  data6  |
 +---------+---------+---------+---------+---------+---------+
 |  data7  |  data8  |  data9  |  data10 |  data11 |  data12 |
 +---------+---------+---------+---------+---------+---------+
                               .
                               .
                               .
 +---------+---------+---------+---------+---------+---------+
 |  data   |  data   |  data   |  data   |  data   |  data   |
 -------------------------------------------------------------

 >> query
 SELECT * FROM table1
     WHERE (column5 + column6) >= 6;

How do I create an index for this query in MySQL?


问:
Asterisk in for loop not working as expected?
I don't understand why this is not working. I am trying to loop through files and folders and delete some of them depending on the name. In the example below delete all folders except the ones in the if statement.

Here's the code:

```<code>#!/bin/bash

workdir=/var/www/
for dir in $workdir/custom/*; do
 if ! [ "$dir" == "$workdir/custom/somefolder" ]; then
   rm -rf $dir
   echo "remove $dir $?"
 fi
 echo "$dir"
done
</code>```

The problem is that there are several files and folders in /custom/ but echo "$dir" outputs /var/www/custom/* once
instead of running through every file and folder in that directory. I know this means that * didn't match anything, but this is impossible.

The folder exists, has several files and folders in it and the path is correct, also the user has all needed permissions to rm files, I checked that twice.

What am I missing?

答:
```<code>find /var/www/custom/ -name "*" -type d -mindepth 1 -exec rm -rf {} \;
</code>```

this will remove all the directories inside your custom directory. If this is what is required.

Body:
I don't understand why this is not working. I am trying to loop through files and folders and delete some of them depending on the name. In the example below delete all folders except the ones in the if statement.

Here's the code:

#!/bin/bash

workdir=/var/www/
for dir in $workdir/custom/*; do
 if ! [ "$dir" == "$workdir/custom/somefolder" ]; then
   rm -rf $dir
   echo "remove $dir $?"
 fi
 echo "$dir"
done

The problem is that there are several files and folders in /custom/ but echo "$dir" outputs /var/www/custom/* once
instead of running through every file and folder in that directory. I know this means that * didn't match anything, but this is impossible.

The folder exists, has several files and folders in it and the path is correct, also the user has all needed permissions to rm files, I checked that twice.

What am I missing?

Body:
find /var/www/custom/ -name "*" -type d -mindepth 1 -exec rm -rf {} \;

this will remove all the directories inside your custom directory. If this is what is required.


问:
WebHttpBinding not reaching the client
I created a web service for which I am trying to provide 3 endpoints with different bindings.
1. basicHttpBinding,
2. wsHttpBinding,
3. webHttpBinding

When I make the service reference, I get only the endpoints with the basicHttpBinding and wsHttpBinding bindings created. I don't get webHttpBinding. What could possibly wrong.

Here's the structure of the serviceModel node in web.config.

```<code>  <system.serviceModel>
<diagnostics>
  <messageLogging logEntireMessage="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"/>
</diagnostics>
<services>
  <service behaviorConfiguration="VersionTolerance.Service1Behavior" name="BookShop.BookShopService">
    <endpoint address="sadha" binding="basicHttpBinding" contract="BookShop.IBookShopService" />
    <endpoint address="ws" binding="wsHttpBinding" contract="BookShop.IBookShopService" >
    </endpoint>
    <endpoint address="web" binding="webHttpBinding" behaviorConfiguration="webHttpBehavior"
      contract="BookShop.IBookShopService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:49654/" />
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="VersionTolerance.Service1Behavior">
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="webHttpBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
</code>```

答:
There's nothing wrong - that's just the way it works!

basicHttpBinding and wsHttpBinding are SOAP bindings that expose metadata about their service - your Visual Studio Add Service Reference can interrogate their endpoints, find out what they're called, what methods they offer, what data types they expect as parameters and what they return.

webHttpBinding is REST - and REST by default doesn't have a concept of metadata - you won't get a service description, list of methods etc. - REST is all about resources - not methods.

So therefore, when you do a  Add Service Reference, you get proxy clients for the SOAP endpoints - but not for the REST / webHttpBinding endpoint. Works as designed.

The WCF Data Services - built on top of REST - offer a similar experience to the SOAP bindings, in that you can do an Add Service Reference and get a nice client side proxy and all - and this is done since the OData protocol defines a metadata exchange on top of REST. So if you can turn your REST service into a WCF Data Service, you'd be fine again.

Otherwise, with REST, you just have to "know" (from a documentation page or something) what the resource URI's for your REST service are, and what the HTTP verbs do in your REST context.

Title: WebHttpBinding not reaching the client

Body:
I created a web service for which I am trying to provide 3 endpoints with different bindings.
1. basicHttpBinding,
2. wsHttpBinding,
3. webHttpBinding

When I make the service reference, I get only the endpoints with the basicHttpBinding and wsHttpBinding bindings created. I don't get webHttpBinding. What could possibly wrong.

Here's the structure of the serviceModel node in web.config.

  <system.serviceModel>
<diagnostics>
  <messageLogging logEntireMessage="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"/>
</diagnostics>
<services>
  <service behaviorConfiguration="VersionTolerance.Service1Behavior" name="BookShop.BookShopService">
    <endpoint address="sadha" binding="basicHttpBinding" contract="BookShop.IBookShopService" />
    <endpoint address="ws" binding="wsHttpBinding" contract="BookShop.IBookShopService" >
    </endpoint>
    <endpoint address="web" binding="webHttpBinding" behaviorConfiguration="webHttpBehavior"
      contract="BookShop.IBookShopService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:49654/" />
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="VersionTolerance.Service1Behavior">

      <serviceMetadata httpGetEnabled="true"/>

      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="webHttpBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>


问:
Not load res.partner in POS Odoo 8
How to not load data res.partner in POS Odoo? Because row on the res.partner table is a lot and makes load POS so long. Thanks</p>

答: You can do one thing if res.partners are not that much necessary then do not load that in POS. Another way is apart from doing what you said you can create a check box in res.partner for allowing to load only checked partners in POS. Like in product.template there is a check box "Available in POS" which only allows to load product in POS which are checked from that box. Same you can do in res.partners. Only load that partners whoes checkbox is cheked.

Title: Not load res.partner in POS Odoo 8


问:
How to make Firebase Authentication for Android working with Phone number?
This is my activity that displays edit text fields for verification code and phone number. On click of start button I am not getting any response.
Thanks in advance.

EditText mPhoneNumberField, mVerificationField;
    Button mStartButton, mVerifyButton, mResendButton;

```<code>private FirebaseAuth mAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId;

private static final String TAG = "PhoneAuthActivity";

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

    mPhoneNumberField = (EditText) findViewById(R.id.field_phone_number);
    mVerificationField = (EditText) findViewById(R.id.field_verification_code);

    mStartButton = (Button) findViewById(R.id.button_start_verification);
    mVerifyButton = (Button) findViewById(R.id.button_verify_phone);
    mResendButton = (Button) findViewById(R.id.button_resend);

    mStartButton.setOnClickListener(this);
    mVerifyButton.setOnClickListener(this);
    mResendButton.setOnClickListener(this);

    mAuth = FirebaseAuth.getInstance();
    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential credential) {
            Log.d(TAG, "onVerificationCompleted:" + credential);
            signInWithPhoneAuthCredential(credential);
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Log.w(TAG, "onVerificationFailed", e);
            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                mPhoneNumberField.setError("Invalid phone number.");
            } else if (e instanceof FirebaseTooManyRequestsException) {
                Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
                        Snackbar.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
            Log.d(TAG, "onCodeSent:" + verificationId);
            mVerificationId = verificationId;
            mResendToken = token;
        }
    };
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = task.getResult().getUser();
                        startActivity(new Intent(PhoneNumberActivity.this, MainActivity.class));
                        finish();
                    } else {
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            mVerificationField.setError("Invalid code.");
                        }
                    }
                }
            });
}

private void startPhoneNumberVerification(String phoneNumber) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks
}

private void verifyPhoneNumberWithCode(String verificationId, String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    signInWithPhoneAuthCredential(credential);
}

private void resendVerificationCode(String phoneNumber,
                                    PhoneAuthProvider.ForceResendingToken token) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks,         // OnVerificationStateChangedCallbacks
            token);             // ForceResendingToken from callbacks
}

private boolean validatePhoneNumber() {
    String phoneNumber = mPhoneNumberField.getText().toString();
    if (TextUtils.isEmpty(phoneNumber)) {
        mPhoneNumberField.setError("Invalid phone number.");
        return false;
    }
    return true;
}
@Override
public void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser != null) {
        startActivity(new Intent(PhoneNumberActivity.this, MainActivity.class));
        finish();
    }
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button_start_verification:
            if (!validatePhoneNumber()) {
                return;
            }
            startPhoneNumberVerification(mPhoneNumberField.getText().toString());
            break;
        case R.id.button_verify_phone:
            String code = mVerificationField.getText().toString();
            if (TextUtils.isEmpty(code)) {
                mVerificationField.setError("Cannot be empty.");
                return;
            }

            verifyPhoneNumberWithCode(mVerificationId, code);
            break;
        case R.id.button_resend:
            resendVerificationCode(mPhoneNumberField.getText().toString(), mResendToken);
            break;
    }

}
</code>```

This is my code. But it is giving the following exception:
com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.

答:
Try
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser()

instead of
FirebaseUser currentUser = mAuth.getCurrentUser();

Body:
This is my activity that displays edit text fields for verification code and phone number. On click of start button I am not getting any response.
Thanks in advance.

EditText mPhoneNumberField, mVerificationField;
    Button mStartButton, mVerifyButton, mResendButton;

private FirebaseAuth mAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId;

private static final String TAG = "PhoneAuthActivity";

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

    mPhoneNumberField = (EditText) findViewById(R.id.field_phone_number);
    mVerificationField = (EditText) findViewById(R.id.field_verification_code);

    mStartButton = (Button) findViewById(R.id.button_start_verification);
    mVerifyButton = (Button) findViewById(R.id.button_verify_phone);
    mResendButton = (Button) findViewById(R.id.button_resend);

    mStartButton.setOnClickListener(this);
    mVerifyButton.setOnClickListener(this);
    mResendButton.setOnClickListener(this);

    mAuth = FirebaseAuth.getInstance();
    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential credential) {
            Log.d(TAG, "onVerificationCompleted:" + credential);
            signInWithPhoneAuthCredential(credential);
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Log.w(TAG, "onVerificationFailed", e);
            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                mPhoneNumberField.setError("Invalid phone number.");
            } else if (e instanceof FirebaseTooManyRequestsException) {
                Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
                        Snackbar.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
            Log.d(TAG, "onCodeSent:" + verificationId);
            mVerificationId = verificationId;
            mResendToken = token;
        }
    };
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = task.getResult().getUser();
                        startActivity(new Intent(PhoneNumberActivity.this, MainActivity.class));
                        finish();
                    } else {
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            mVerificationField.setError("Invalid code.");
                        }
                    }
                }
            });
}

private void startPhoneNumberVerification(String phoneNumber) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks
}

private void verifyPhoneNumberWithCode(String verificationId, String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    signInWithPhoneAuthCredential(credential);
}

private void resendVerificationCode(String phoneNumber,
                                    PhoneAuthProvider.ForceResendingToken token) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks,         // OnVerificationStateChangedCallbacks
            token);             // ForceResendingToken from callbacks
}

private boolean validatePhoneNumber() {
    String phoneNumber = mPhoneNumberField.getText().toString();
    if (TextUtils.isEmpty(phoneNumber)) {
        mPhoneNumberField.setError("Invalid phone number.");
        return false;
    }
    return true;
}
@Override
public void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser != null) {
        startActivity(new Intent(PhoneNumberActivity.this, MainActivity.class));
        finish();
    }
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button_start_verification:
            if (!validatePhoneNumber()) {
                return;
            }
            startPhoneNumberVerification(mPhoneNumberField.getText().toString());
            break;
        case R.id.button_verify_phone:
            String code = mVerificationField.getText().toString();
            if (TextUtils.isEmpty(code)) {
                mVerificationField.setError("Cannot be empty.");
                return;
            }

            verifyPhoneNumberWithCode(mVerificationId, code);
            break;
        case R.id.button_resend:
            resendVerificationCode(mPhoneNumberField.getText().toString(), mResendToken);
            break;
    }

}

This is my code. But it is giving the following exception:
com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.


问:
Symfony override third party entity repository
I'm using a third party bundle with a custom doctrine entity repository. It includes a function which I'd like to override to customize it for my needs.
Has anyone ever done this? I couldn't find any documentation on overriding an entity repository.
Why I need to do this: a Service from that third party bundle calls this repository function and executes it. But I'd like to change one part of it.

What I tried:
create an own Entity repository class:

```<code>namespace NotificationBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Citrax\Bundle\DatabaseSwiftMailerBundle\Entity\Email;
use Citrax\Bundle\DatabaseSwiftMailerBundle\Entity\EmailRepository as BaseRepository;

class EmailRepository extends BaseRepository
{

    public function markCompleteSending(Email $email)
    {
        $email->setStatus(Email::STATUS_COMPLETE);
        $email->setSentAt(new \DateTime());
        $email->setErrorMessage('');
        $em = $this->getEntityManager();
        $em->remove($email);
        $em->flush();
    }
}
</code>```

it extends the parent repository and overrides only this function, the rest I didn't touch. I then registered that repository as a service.
Anyway it's not working!
Anything else needed? Please let me know! I'd be glad about some help.

where the functino is called:

```<code>public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
{
    if (!$transport->isStarted())
    {
        $transport->start();
    }

    $count = 0;
    $emails = $this->repository->getEmailQueue($this->getMessageLimit());

    foreach($emails as $email){
        /*@var $message \Swift_Mime_Message */
        $message = $email->getMessage();
        try{
            $count_= $transport->send($message, $failedRecipients);
            if($count_ > 0){
                $this->repository->markCompleteSending($email);
                $count += $count_;
            }else{
                throw new \Swift_SwiftException('The email was not sent.');
            }
        }catch(\Swift_SwiftException $ex){
            $this->repository->markFailedSending($email, $ex);
        }
    }

    return $count;
}
</code>```

that's the class DatabaseSpool that is the registered as the service which spools for my swiftmailer.

答:
To override repo of DatabaseSwiftMailerBundle i can see (on git) that vendor has defined Citrax\Bundle\DatabaseSwiftMailerBundle\Entity\EmailRepository as a service named as repository.email and you can override services using symfony's CompilerPassInterface. In your bundle under DependencyInjection folder create your compiler pass and override repository.email service by defining your repo which should extend vendor's repo.

```<code>namespace Your\Bundle\DependencyInjection\Compiler;

use NotificationBundle\Entity\EmailRepository;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OverrideServiceCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('repository.email');
        $definition->setClass(EmailRepository::class);
    }
}
</code>```

As per official docs

If you want to modify service definitions of another bundle, you can use a compiler pass to change the class of the service or to modify method calls. In the following example, the implementing class for the original-service-id is changed to Acme\DemoBundle\YourService.

For more information have a look at Services & Configuration

Body:
I'm using a third party bundle with a custom doctrine entity repository. It includes a function which I'd like to override to customize it for my needs.
Has anyone ever done this? I couldn't find any documentation on overriding an entity repository.
Why I need to do this: a Service from that third party bundle calls this repository function and executes it. But I'd like to change one part of it.

What I tried:
create an own Entity repository class:

namespace NotificationBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Citrax\Bundle\DatabaseSwiftMailerBundle\Entity\Email;
use Citrax\Bundle\DatabaseSwiftMailerBundle\Entity\EmailRepository as BaseRepository;

class EmailRepository extends BaseRepository
{

    public function markCompleteSending(Email $email)
    {
        $email->setStatus(Email::STATUS_COMPLETE);
        $email->setSentAt(new \DateTime());
        $email->setErrorMessage('');
        $em = $this->getEntityManager();
        $em->remove($email);
        $em->flush();
    }
}

it extends the parent repository and overrides only this function, the rest I didn't touch. I then registered that repository as a service.
Anyway it's not working!
Anything else needed? Please let me know! I'd be glad about some help.

where the functino is called:

public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
{
    if (!$transport->isStarted())
    {
        $transport->start();
    }

    $count = 0;
    $emails = $this->repository->getEmailQueue($this->getMessageLimit());

    foreach($emails as $email){
        /*@var $message \Swift_Mime_Message */
        $message = $email->getMessage();
        try{
            $count_= $transport->send($message, $failedRecipients);
            if($count_ > 0){
                $this->repository->markCompleteSending($email);
                $count += $count_;
            }else{
                throw new \Swift_SwiftException('The email was not sent.');
            }
        }catch(\Swift_SwiftException $ex){
            $this->repository->markFailedSending($email, $ex);
        }
    }

    return $count;
}

that's the class DatabaseSpool that is the registered as the service which spools for my swiftmailer.

Body:
To override repo of DatabaseSwiftMailerBundle i can see (on git) that vendor has defined Citrax\Bundle\DatabaseSwiftMailerBundle\Entity\EmailRepository as a service named as repository.email and you can override services using symfony's CompilerPassInterface. In your bundle under DependencyInjection folder create your compiler pass and override repository.email service by defining your repo which should extend vendor's repo.

namespace Your\Bundle\DependencyInjection\Compiler;

use NotificationBundle\Entity\EmailRepository;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OverrideServiceCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('repository.email');
        $definition->setClass(EmailRepository::class);
    }
}

As per official docs

If you want to modify service definitions of another bundle, you can use a compiler pass to change the class of the service or to modify method calls. In the following example, the implementing class for the original-service-id is changed to Acme\DemoBundle\YourService.

For more information have a look at Services & Configuration


问:
Firebase storage downloadURL partial apply forwarder for @nonobjc message
I am testing a upload image to Firebase storage, but i got the message:

```<code>partial apply forwarder for @nonobjc  at xxxViewController.swift
</code>```

Here is the code:

```<code>let storage = Storage.storage()
storage.reference().child("abc").putData(d, metadata: nil) { (metadata, error) in
    guard let metadata = metadata else {
         print("error")
         return
    }
    let downloadURL = metadata.downloadURL
    print(downloadURL)
}
</code>```

The output is just (Function) and with the message above.

答:
```<code>       let metadata = FIRStorageMetadata()
        metadata.contentType = "image/png"

let storage = Storage.storage()
storage.reference().child("abc").putData(d, metadata: metadata) { (metadata, error) in
    guard let metadata = metadata else {
         print("error")
         return
    }
    let downloadURL = metadata.downloadURL
    print(downloadURL)
}
</code>```

This will solves your problem

Body:
I am testing a upload image to Firebase storage, but i got the message:

partial apply forwarder for @nonobjc  at xxxViewController.swift

Here is the code:

let storage = Storage.storage()
storage.reference().child("abc").putData(d, metadata: nil) { (metadata, error) in
    guard let metadata = metadata else {
         print("error")
         return
    }
    let downloadURL = metadata.downloadURL
    print(downloadURL)
}

The output is just (Function) and with the message above.

Body:
       let metadata = FIRStorageMetadata()
        metadata.contentType = "image/png"

let storage = Storage.storage()
storage.reference().child("abc").putData(d, metadata: metadata) { (metadata, error) in
    guard let metadata = metadata else {
         print("error")
         return
    }
    let downloadURL = metadata.downloadURL
    print(downloadURL)
}

This will solves your problem


问:
ATM Account Homework (Classes, Textfiles, Objects)

I am completely lost. Our homework assignment is to:

Create an ATM Program that asks a user for their name and pin

Program will loop through asking user if they want to check balance, withdraw, deposit, or exit. You exit the loop when user selects exit. The initial balance is $10,000

Create a text file that records all transactions. First 2 lines of the file should be the User's name and Pin

Create a class called which includes the init and str functions to display info from the user(deposit, check balance, withdraw)

Program needs to read from the file and create an object. The fields for the object are the name, pin, and balance.
6.If the pin number and the name they provide to not match the name and pin number for the BAcc object the program will end.  Otherwise you can proceeded to make as many transactions as you want updating the file
7.Errors must by handled using try: blocks!  This includes both invalid data entry and insufficient funds on a withdraw.

This is the code I have right now, it doesn't do much but I just need a way to connect it.

```<code>accountfile=open("ATMACC.txt", "a")
name=input("What is your name? ")
pin=input("What is your Pin #? ")
accountfile.write("Name: " + name + "\n" + "PIN: " + pin + "\n")
USER_BALANCE = 10000
class BankAcc(object):
    def __init__(self,name,pin,balance):
        name = self.name
        pin = self.pin
        10000 = self.balance
    def __str__(self):
        return "Bank Account with Balance {}".format(self.name,self.balance)
    def checkbalance(self):
        print(self)
    def deposit(self,amount):
        self.amount += amount
    def withdraw(self,amount):
        if self.balance > amount:
            self.balance -= amount
        else:
            raise ValueError
while True:
    answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
    if answer=="deposit" or answer== "Deposit":
        x= input("How much would you like to deposit? ")
        USER_BALANCE += float(x)
        print ("Your new balance is: $" + str(USER_BALANCE))
        accountfile.write("\n" + "Deposit of $" + x + "." + " " + "Current balance is $" + str(USER_BALANCE))
        continue
    elif answer== "withdraw" or answer== "Withdraw":
        y= input("How much would you like to withdraw? ")
        if float (y)<=USER_BALANCE:
            USER_BALANCE -= float(y)
            print ("Your new balance is: $" + str(USER_BALANCE))
            accountfile.write("\n" + "Withdraw of $" + y + "." + " " + "Current balance is $" + str(USER_BALANCE))
            continue
        else:
            print ("Cannot be done. You have insufficient funds.")
    elif answer== "check balance" or answer== "Check Balance":
        print ("$" + str(USER_BALANCE))
    elif answer== "exit" or answer== "Exit":
        print ("Goodbye!")
        accountfile.close()
        break
    else:
        print ("I'm sorry, that is not an option")
</code>```

Please help. I know this is a complete mess but any help would be greatly appreciated.

答:
I have added comments to explain what your mistakes are, I did what was asked.

```<code>class BankAcc(object):
    def __init__(self, name, pin, balance=10000.0): #If you want to give default balance if not provided explicitly do this
        self.name = name                    #variable where value is stored = expression
        self.pin = pin
        self.balance = balance
    def CheckUser(self, name, pin):       #A function to check wheather the user is valid or not
        try:
            if name != self.name or pin != self.pin:
                raise ValueError
            print("Name and Pin Matches")
        except ValueError:
            print("Name or Password is not correct")
            exit(0)

    def __str__(self):
        return "{}'s Bank Account with Balance {}".format(self.name, self.balance) #using only one substition in the string but providing 2 variables

    def checkbalance(self):
        return '$' + str(self.balance) #self is the instance of the class for printing balance use self.balance

    def deposit(self, amount):
        self.balance += amount        #self.ammount will create a new property but i think you want to increase your balance

    def withdraw(self, amount):
        try:                          #use try catct if raising an excpetion
            if self.balance >= amount:    #balance should be greater than and equal to the ammount
                self.balance -= amount
            else:
                raise ValueError
        except ValueError:                #Handle your exception
                print("Cannot be done. You have insufficient funds.")

    def filedata(self):              #An extra function for writing in the file.
        return "{},{},{}".format(self.name,self.pin,self.balance)

accountfile = open("ATMACC.txt", "r+") #"r+" should be used becuase you are reading and writing
accountfiledata=accountfile.read().split(",")  #Can be done in the class it self
BankUser = BankAcc(accountfiledata[0],accountfiledata[1],float(accountfiledata[2])) #For simplicity i used comma seperated data and created an instance of it
name=input("What is your name? ")
pin=input("What is your Pin #? ")
BankUser.CheckUser(name, pin)
#accountfile.write("Name: " + name + "\n" + "PIN: " + pin + "\n") #You did not specify that you want to write in file as well
#USER_BALANCE = 10000          it is not needed

while True:    #For multiple options use numbers instead of words such as 1 for deposit etc
    answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
    if answer=="deposit" or answer== "Deposit":
        x= input("How much would you like to deposit? ")
        BankUser.deposit(float(x))   #use your deposit function
        print ("Your new balance is: " + BankUser.checkbalance())
        #continue  #Why using continue, no need for it
    elif answer== "withdraw" or answer== "Withdraw":
        y= input("How much would you like to withdraw? ")
        BankUser.withdraw(float(y))         #Use Your withdraw function why reapeating your self
    elif answer== "check balance" or answer== "Check Balance":
        print(BankUser.checkbalance())
    elif answer== "exit" or answer== "Exit":
        print ("Goodbye!")
        accountfile.close()
        exit(0)
    else:
        print ("I'm sorry, that is not an option")
    accountfile.seek(0)               #I dont know whether you want to record all tranction or a single one
    accountfile.truncate()            #perform write function at the last
    accountfile.write(BankUser.filedata())
</code>```

And text file format is ATMACC.txt

```<code>Himanshu,1111,65612.0
</code>```

Body:
I am completely lost. Our homework assignment is to:

Create an ATM Program that asks a user for their name and pin

Program will loop through asking user if they want to check balance, withdraw, deposit, or exit. You exit the loop when user selects exit. The initial balance is $10,000

Create a text file that records all transactions. First 2 lines of the file should be the User's name and Pin

Create a class called which includes the init and str functions to display info from the user(deposit, check balance, withdraw)

Program needs to read from the file and create an object. The fields for the object are the name, pin, and balance.
6.If the pin number and the name they provide to not match the name and pin number for the BAcc object the program will end.  Otherwise you can proceeded to make as many transactions as you want updating the file
7.Errors must by handled using try: blocks!  This includes both invalid data entry and insufficient funds on a withdraw.

This is the code I have right now, it doesn't do much but I just need a way to connect it.

accountfile=open("ATMACC.txt", "a")
name=input("What is your name? ")
pin=input("What is your Pin #? ")
accountfile.write("Name: " + name + "\n" + "PIN: " + pin + "\n")
USER_BALANCE = 10000
class BankAcc(object):
    def __init__(self,name,pin,balance):
        name = self.name
        pin = self.pin
        10000 = self.balance
    def __str__(self):
        return "Bank Account with Balance {}".format(self.name,self.balance)
    def checkbalance(self):
        print(self)
    def deposit(self,amount):
        self.amount += amount
    def withdraw(self,amount):
        if self.balance > amount:
            self.balance -= amount
        else:
            raise ValueError
while True:
    answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
    if answer=="deposit" or answer== "Deposit":
        x= input("How much would you like to deposit? ")
        USER_BALANCE += float(x)
        print ("Your new balance is: $" + str(USER_BALANCE))
        accountfile.write("\n" + "Deposit of $" + x + "." + " " + "Current balance is $" + str(USER_BALANCE))
        continue
    elif answer== "withdraw" or answer== "Withdraw":
        y= input("How much would you like to withdraw? ")
        if float (y)<=USER_BALANCE:
            USER_BALANCE -= float(y)
            print ("Your new balance is: $" + str(USER_BALANCE))
            accountfile.write("\n" + "Withdraw of $" + y + "." + " " + "Current balance is $" + str(USER_BALANCE))
            continue
        else:
            print ("Cannot be done. You have insufficient funds.")
    elif answer== "check balance" or answer== "Check Balance":
        print ("$" + str(USER_BALANCE))
    elif answer== "exit" or answer== "Exit":
        print ("Goodbye!")
        accountfile.close()
        break
    else:
        print ("I'm sorry, that is not an option")

Please help. I know this is a complete mess but any help would be greatly appreciated.

Body:
I have added comments to explain what your mistakes are, I did what was asked.

class BankAcc(object):
    def __init__(self, name, pin, balance=10000.0): #If you want to give default balance if not provided explicitly do this
        self.name = name                    #variable where value is stored = expression
        self.pin = pin
        self.balance = balance
    def CheckUser(self, name, pin):       #A function to check wheather the user is valid or not
        try:
            if name != self.name or pin != self.pin:
                raise ValueError
            print("Name and Pin Matches")
        except ValueError:
            print("Name or Password is not correct")
            exit(0)

    def __str__(self):
        return "{}'s Bank Account with Balance {}".format(self.name, self.balance) #using only one substition in the string but providing 2 variables

    def checkbalance(self):
        return '$' + str(self.balance) #self is the instance of the class for printing balance use self.balance

    def deposit(self, amount):
        self.balance += amount        #self.ammount will create a new property but i think you want to increase your balance

    def withdraw(self, amount):
        try:                          #use try catct if raising an excpetion
            if self.balance >= amount:    #balance should be greater than and equal to the ammount
                self.balance -= amount
            else:
                raise ValueError
        except ValueError:                #Handle your exception
                print("Cannot be done. You have insufficient funds.")

    def filedata(self):              #An extra function for writing in the file.
        return "{},{},{}".format(self.name,self.pin,self.balance)

accountfile = open("ATMACC.txt", "r+") #"r+" should be used becuase you are reading and writing
accountfiledata=accountfile.read().split(",")  #Can be done in the class it self
BankUser = BankAcc(accountfiledata[0],accountfiledata[1],float(accountfiledata[2])) #For simplicity i used comma seperated data and created an instance of it
name=input("What is your name? ")
pin=input("What is your Pin #? ")
BankUser.CheckUser(name, pin)
#accountfile.write("Name: " + name + "\n" + "PIN: " + pin + "\n") #You did not specify that you want to write in file as well
#USER_BALANCE = 10000          it is not needed

while True:    #For multiple options use numbers instead of words such as 1 for deposit etc
    answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
    if answer=="deposit" or answer== "Deposit":
        x= input("How much would you like to deposit? ")
        BankUser.deposit(float(x))   #use your deposit function
        print ("Your new balance is: " + BankUser.checkbalance())
        #continue  #Why using continue, no need for it
    elif answer== "withdraw" or answer== "Withdraw":
        y= input("How much would you like to withdraw? ")
        BankUser.withdraw(float(y))         #Use Your withdraw function why reapeating your self
    elif answer== "check balance" or answer== "Check Balance":
        print(BankUser.checkbalance())
    elif answer== "exit" or answer== "Exit":
        print ("Goodbye!")
        accountfile.close()
        exit(0)
    else:
        print ("I'm sorry, that is not an option")
    accountfile.seek(0)               #I dont know whether you want to record all tranction or a single one
    accountfile.truncate()            #perform write function at the last
    accountfile.write(BankUser.filedata())

And text file format is ATMACC.txt

Himanshu,1111,65612.0


问:
Retaining n duplicate entries in a file
This feels like a Stack Overflow question that folks have already answered but I can't find an appropriate thread.

there are tools to sort a file to retain unique entries.

there are tools to sort a file to retain only duplicate entries.

But... what if I want to specify to keep the first Nth entries of duplicate values, and then discard the rest?

For example, in the list below, I'd like to be able to print out  up to the Nth number of duplicates for the first field. Here's the original list:

```<code>apple    toledo
apple    omaha
apple    butte
apple    freeport
peach    saginaw
peach    frakenmuth
pears    wichita
</code>```

So, for example, the standard uniq way of doing things could generate (on an unsorted list):

```<code>apple toledo
peach saginaw
pears wichita
</code>```

But I might want to keep up to 2 duplicate entries:

```<code>apple toledo
apple omaha
peach saginaw
peach frakenmuth
pears wichita
</code>```

Or if I was feeling crazy, even 3 duplicate entries:

```<code>apple toledo
apple omaha
apple butte
peach saginaw
peach frakenmuth
pears wichita
</code>```

Is there a sensible way to go about doing this in bash?

答:
How about:

```<code>cat list | awk 'count[$1]++ < 2'
</code>```

You can change the number 2 to 3 or whatever.

Title: Retaining n duplicate entries in a file

Body:
This feels like a Stack Overflow question that folks have already answered but I can't find an appropriate thread.

there are tools to sort a file to retain unique entries.

there are tools to sort a file to retain only duplicate entries.

But... what if I want to specify to keep the first Nth entries of duplicate values, and then discard the rest?

For example, in the list below, I'd like to be able to print out  up to the Nth number of duplicates for the first field. Here's the original list:

apple    toledo
apple    omaha
apple    butte
apple    freeport
peach    saginaw
peach    frakenmuth
pears    wichita

So, for example, the standard uniq way of doing things could generate (on an unsorted list):

apple toledo
peach saginaw
pears wichita

But I might want to keep up to 2 duplicate entries:

apple toledo
apple omaha
peach saginaw
peach frakenmuth
pears wichita

Or if I was feeling crazy, even 3 duplicate entries:

apple toledo
apple omaha
apple butte
peach saginaw
peach frakenmuth
pears wichita

Is there a sensible way to go about doing this in bash?

Body:
How about:

cat list | awk 'count[$1]++ < 2'

You can change the number 2 to 3 or whatever.


问:
"Undefined mixin 'box-sizing'", in rails, using compass-rails
This is the error message:

```<code>Undefined mixin 'box-sizing'.
(in /var/www/site/spree/app/assets/stylesheets/store/neat/_neat.scss:3)
</code>```

Conditions:

I'm using rails 4.0.2

I've installed the compass-rails gem, and run 'bundle'. I've also installed the gems "bourbon" and "neat".

Within 'site/spree/app/assets/stylesheets/mystylesheet.css.scss', I have this:

```<code>@import "bourbon/bourbon";
@import "neat/neat";
</code>```

neat requires the mixin "box-sizing", provided by compass. However, the mixin just isn't being picked up.

I've tried adding @import "box-sizing", @import "compass/box-sizing"., @import "compass/css3/box-sizing"

None of those lines works: rails remains completely unable to access compass mixins.

This is my entire gemfile:

```<code>source 'https://rubygems.org'
ruby '2.1.0'
gem 'rails', '4.0.2'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails', '~> 3.0.0'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'mysql2'

group :development do
   gem 'better_errors'
   gem 'binding_of_caller', :platforms=>[:mri_21, :rbx]
   gem 'rails_layout'
end

group :development, :test do
   gem 'factory_girl_rails'
end

gem 'compass-rails'
gem 'bourbon'
gem 'neat'

gem 'spree', '2.1.4'
gem 'spree_gateway', :git => 'https://github.com/spree/spree_gateway.git', :branch => '2-1-stable'
gem 'spree_auth_devise', :git => 'https://github.com/spree/spree_auth_devise.git', :branch => '2-1-stable'
</code>```

答:
You need to modify your syntax a little as the old style of calling box-sizing is deprecated now.
If you were calling it in old style @include box-sizing(border-box) then change it to box-sizing: border-box;It worked for me.

Body:
This is the error message:

Undefined mixin 'box-sizing'.
(in /var/www/site/spree/app/assets/stylesheets/store/neat/_neat.scss:3)

Conditions:

I'm using rails 4.0.2

I've installed the compass-rails gem, and run 'bundle'. I've also installed the gems "bourbon" and "neat".

Within 'site/spree/app/assets/stylesheets/mystylesheet.css.scss', I have this:

@import "bourbon/bourbon";
@import "neat/neat";

neat requires the mixin "box-sizing", provided by compass. However, the mixin just isn't being picked up.

I've tried adding @import "box-sizing", @import "compass/box-sizing"., @import "compass/css3/box-sizing"

None of those lines works: rails remains completely unable to access compass mixins.

This is my entire gemfile:

source 'https://rubygems.org'
ruby '2.1.0'
gem 'rails', '4.0.2'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails', '~> 3.0.0'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'mysql2'

group :development do
   gem 'better_errors'
   gem 'binding_of_caller', :platforms=>[:mri_21, :rbx]
   gem 'rails_layout'
end

group :development, :test do
   gem 'factory_girl_rails'
end

gem 'compass-rails'
gem 'bourbon'
gem 'neat'

gem 'spree', '2.1.4'
gem 'spree_gateway', :git => 'https://github.com/spree/spree_gateway.git', :branch => '2-1-stable'
gem 'spree_auth_devise', :git => 'https://github.com/spree/spree_auth_devise.git', :branch => '2-1-stable'