问:
JPA/Hibernate seems to convert a query with an in clause into multiple queries with = clauses
A solution we implemented in order to collect a large amount of heavy objects in reasonable time and without memory overflow (I'm speaking of objects with multiple fetchType.eager relations, to entities that themselves have eager fetched relations), was to first select ids of those objects, and then select the objects themselves based on these ids.

Coming the time to optimise our code, we noticed (using hibernate.show_sql=true) that the query we used to gather those objects  (select a from A a where a.id in :ids) is translated by JPA/Hibernate into thousands of queries of the form select a from ...endless join list... where a.id = ?

The question is the following:

Why JPA/Hibernate transforms our initial query with an "in" clause into so many queries with "=" clauses. Isn't it inefficent ? If so, is there a way to prevent that ?

Here's how the query is called in our code:

```<code>    Query q = this.getContext().createQuery("select a from A a where a.id in :ids");
    q.setParameter("ids", idList);
    return (List<A>) q.getResultList();
</code>```

答:
Though I still can't explain why a query is generated for each ID provided in the in clause (provided in my original question), I found a solution to this problem on this blog (https://thoughts-on-java.org/fetch-multiple-entities-id-hibernate/).
The solution consists in using Hibernate's session API as follows:</p>

```<code>//get session object from entity manager
Session session = em.unwrap(Session.

MultiIdentifierLoadAccess<A> multiLoadAccess = session.byMultipleIds(A.class);
List<A> aObjects= multiLoadAccess.withBatchSize(1000).multiLoad(idList);
return aObjects;
</code>```

Body:
A solution we implemented in order to collect a large amount of heavy objects in reasonable time and without memory overflow (I'm speaking of objects with multiple fetchType.eager relations, to entities that themselves have eager fetched relations), was to first select ids of those objects, and then select the objects themselves based on these ids.

Coming the time to optimise our code, we noticed (using hibernate.show_sql=true) that the query we used to gather those objects  (select a from A a where a.id in :ids) is translated by JPA/Hibernate into thousands of queries of the form select a from ...endless join list... where a.id = ?

The question is the following:

Why JPA/Hibernate transforms our initial query with an "in" clause into so many queries with "=" clauses. Isn't it inefficent ? If so, is there a way to prevent that ?

Here's how the query is called in our code:

    Query q = this.getContext().createQuery("select a from A a where a.id in :ids");
    q.setParameter("ids", idList);
    return (List) q.getResultList();

Body:
Though I still can't explain why a query is generated for each ID provided in the in clause (provided in my original question), I found a solution to this problem on this blog (https://thoughts-on-java.org/fetch-multiple-entities-id-hibernate/).
The solution consists in using Hibernate's session API as follows:

//get session object from entity manager
Session session = em.unwrap(Session.

MultiIdentifierLoadAccess<A> multiLoadAccess = session.byMultipleIds(A.class);
List<A> aObjects= multiLoadAccess.withBatchSize(1000).multiLoad(idList);
return aObjects;


来源: stackexchange

问:
Error 1004 application defined or object defined error
Here the code:

```<code>Sub deleterow2()
Dim a As Integer
Dim n As Integer
Dim c As Integer

LastRow = Range("F" & Rows.Count).End(xlUp).Row
For n = 0 To LastRow
a = 1
c = 0
Do Until c = 1
Cells(n + a, 6).Select
If Selection.value = Cells(n, 6) And Selection.value > 30 Then
Selection.EntireRow.Delete
Else
c = 1
End If
a = a + 1
Loop
Next n
End Sub
</code>```

What s wrong with that?

答:
Some Tips:

You could not use n = 0 because you will create an error. Rows start from 1.

When you loop in order to delete you start from the end.
For n = LastRow To 1 Step -1

If there are a lot of lines and you will use For Loop declare you variable As Long.

If you have a lot of rows it s better to use an Array.

Try to avoid .Select by creating a With Statement with the sheet name
With ThisWorkbook.Worksheets("Sheet1") and refer to cell using .Cells(n + A, 6).Value

Do Until should start also from high to low due to the fact that you go from bottom to top.

ContentLicense: CC BY-SA 4.0

Body:
Here the code:

Sub deleterow2()
Dim a As Integer
Dim n As Integer
Dim c As Integer

LastRow = Range("F" & Rows.Count).End(xlUp).Row
For n = 0 To LastRow
a = 1
c = 0
Do Until c = 1
Cells(n + a, 6).Select
If Selection.value = Cells(n, 6) And Selection.value > 30 Then
Selection.EntireRow.Delete
Else
c = 1
End If
a = a + 1
Loop
Next n
End Sub

What s wrong with that?


问:
How to make Super/Base/Parent class in microservices in spring-boot - to extend that class in child class
1)
I have 3 microservices project (Country-micro, State-micro and City-micro) with 3 entities Country, State and City in each microservices define respectively. Please note that all 3 microservices has same group id in pom.xml

All the entity has common 4 fields

id

created_date

modified_date

is_active

How can I make base entity class for above fields and use it in different microservices. Like, in monolithic architecture we can use easily by extending class as define here :

My base Class

```<code>@MappedSuperclass
@Data
public class BaseEntity {
    private Long id;
    private Date created_date;
    private Date modified_date;
    private Boolean is_active;

}
</code>```

My child class

```<code>@Entity
@Data
@EqualsAndHashCode(callSuper=false)
@Table(name="tbl_country")
public class Country extends BaseEntity {
    private String countryName;
    private String countryCode;
}
</code>```

But, in microservices architecture, all entities are separated. Then, how can I define service to make as Super class.

2) With the same question above, I also want to use my constant class in each microservices. Like, in monolithic structure, we can :

```<code>public interface Constants {
    static String HTTP = "http";
    static String COMMA_AND_SPACE = ", ";
}
</code>```

And can use this constants in any class like:

```<code>public String myMethod(MyDto myDto) {
    StringBuilder sb = new StringBuilder();

    sb.append("My First String").append(Constants.COMMA_AND_SPACE);
    sb.append("My Second String").append(Constants.COMMA_AND_SPACE);
}
</code>```

In which service I can define constants, Should I create separate service? or I have to define same constants in every microservice (like code redundant). I am also using Utility class in monolithic structure same way.

Please explain structure or guide me to define base classes or Utils.

Thank you in advance.

答:
You can create one new module as Common and put all your common code in it.

Just add it's dependency in whichever project needed in pom.xml.

So even if you run Microservice1 separately you will have to bind Common module as well in it.

eg in Microservice1 pom.xml add common dependency

```<code><dependency>
    <groupId>com.sample.common</groupId>
    <artifactId>Common</artifactId>
    <version>${project.version}</version>
</dependency>
</code>```

Can read this as well

Body:
1)
I have 3 microservices project (Country-micro, State-micro and City-micro) with 3 entities Country, State and City in each microservices define respectively. Please note that all 3 microservices has same group id in pom.xml

All the entity has common 4 fields

id

created_date

modified_date

is_active

How can I make base entity class for above fields and use it in different microservices. Like, in monolithic architecture we can use easily by extending class as define here :

My base Class

@MappedSuperclass
@Data
public class BaseEntity {
    private Long id;
    private Date created_date;
    private Date modified_date;
    private Boolean is_active;

}

My child class

@Entity
@Data
@EqualsAndHashCode(callSuper=false)
@Table(name="tbl_country")
public class Country extends BaseEntity {
    private String countryName;
    private String countryCode;
}

But, in microservices architecture, all entities are separated. Then, how can I define service to make as Super class.

2) With the same question above, I also want to use my constant class in each microservices. Like, in monolithic structure, we can :

public interface Constants {
    static String HTTP = "http";
    static String COMMA_AND_SPACE = ", ";
}

And can use this constants in any class like:

public String myMethod(MyDto myDto) {
    StringBuilder sb = new StringBuilder();

    sb.append("My First String").append(Constants.COMMA_AND_SPACE);
    sb.append("My Second String").append(Constants.COMMA_AND_SPACE);
}

In which service I can define constants, Should I create separate service? or I have to define same constants in every microservice (like code redundant). I am also using Utility class in monolithic structure same way.

Please explain structure or guide me to define base classes or Utils.

Thank you in advance.

Body:
You can create one new module as Common and put all your common code in it.

Just add it's dependency in whichever project needed in pom.xml.

So even if you run Microservice1 separately you will have to bind Common module as well in it.

eg in Microservice1 pom.xml add common dependency

<dependency>
    <groupId>com.sample.common</groupId>
    <artifactId>Common</artifactId>
    <version>${project.version}</version>
</dependency>

Can read this as well


问:
The following code always fails with 400 bad request
```<code>    function SendEditCommand()
    {
        jQuery.ajax({
            url: 'http://localhost:15478/Service.svc/GetTest',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert('success');
            },
            error: function(request, status, error) {
                alert(error);
            }
        });
    }

    jQuery(document).ready(function () {
        SendEditCommand();
    });
</code>```

```<code><configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <connectionStrings>
        <add name="Entities" connectionString="metadata=res://*/Data.TechieCMS.csdl|res://*/Data.TechieCMS.ssdl|res://*/Data.TechieCMS.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost\mssql2008;Initial Catalog=TechieCMS;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
    </connectionStrings>
    <system.serviceModel>
        <services>
            <service name="DefaultService" behaviorConfiguration="DefaultServiceBehavior">
                <endpoint address="" binding="webHttpBinding" contract="Techie.CMS.Business.ContentProvider" behaviorConfiguration="DefaultEndpointBehavior" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="DefaultEndpointBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="DefaultServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
</configuration>
</code>```

```<code>    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ContentProvider
    {
        [OperationContract]
        [WebGet()]
        public string GetTest()
        {
            return "Test";
        }
    }
</code>```

答: Thank you all for your answers, they were surely relevant and a piece to the of the puzzle. The key problem was <service name="DefaultService"... I thought this was just supposed to be a name that I choose. Found out that it has to be the fully qualified name of the class that implements the contract. </p>

ContentLicense: CC BY-SA 3.0

Body:
    function SendEditCommand()
    {
        jQuery.ajax({
            url: 'http://localhost:15478/Service.svc/GetTest',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert('success');
            },
            error: function(request, status, error) {
                alert(error);
            }
        });
    }

    jQuery(document).ready(function () {
        SendEditCommand();
    });

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <connectionStrings>
        <add name="Entities" connectionString="metadata=res://*/Data.TechieCMS.csdl|res://*/Data.TechieCMS.ssdl|res://*/Data.TechieCMS.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost\mssql2008;Initial Catalog=TechieCMS;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
    </connectionStrings>
    <system.serviceModel>
        <services>
            <service name="DefaultService" behaviorConfiguration="DefaultServiceBehavior">
                <endpoint address="" binding="webHttpBinding" contract="Techie.CMS.Business.ContentProvider" behaviorConfiguration="DefaultEndpointBehavior" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="DefaultEndpointBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="DefaultServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
</configuration>

    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ContentProvider
    {
        [OperationContract]
        [WebGet()]
        public string GetTest()
        {
            return "Test";
        }
    }


问:
Upload multiple files using Python Selenium WebDriver
I have a html element

```<code><input type=file multiple="">
</code>```

How can I use send_keys to upload multiple files?

Currently this works with uploading single file. I want to use this to upload multiple files

I tried Comma separated paths but no luck.

答:
path = “/home/downloads/”
send_keys(path + “file1.csv \n” + path + “file2.csv”)

I found it working in my code. Do try this and give me update on the error you got.

Body:
I have a html element

<input type=file multiple="">

How can I use send_keys to upload multiple files?

Currently this works with uploading single file. I want to use this to upload multiple files

I tried Comma separated paths but no luck.


问:
Hadoop data visualization
I am a new hadoop developer and I have been able to install and run hadoop services in a single-node cluster. The problem comes during data visualization. What purpose does MapReduce jar file play when I need to use a data visualization tool like Tableau. I have a structured data source in which I need to add a layer of logic so that the data could make sense during visualization. Do I need to write MapReduce programs if I am going to visualize with other tools? Please shed some light on how I could go about on this issue.</p>

答:
Check out some end to end solutions for data visualization.

For example like Metatron Discovery, it uses druid as their OLAP engine. So you just link your hadoop with Druid and then you can manage and visualize your hadoop data accordingly. This is an open source so that you also can see the code inside it.

Title: Hadoop data visualization


问:
How to count amenities per admin_level n in a foreach loop over admin_level n+2 with overpy
I would like to count amenities (bars and pubs) per admin_level 6 (departement) with overpy.

I succeeded to make a csv file with overpass turbo :

```<code>[out:csv(id, total )];
//All French départements (level 6) from FR-01 to FR-95 plus FR-2A and FR-2B
area[admin_level=6]["ISO3166-2"~"^FR-[0-9]|[1-8][0-9]|9[0-5]|2[A-B]"];

// Counts  bars and pubs in each dpt (level 6)
foreach->.dpt(
  // search for bars and pubs
  (
    way(area.dpt)[amenity=pub];
    way(area.dpt)[amenity=bar];
    node(area.dpt)[amenity=pub];
    node(area.dpt)[amenity=bar];
  );

  make count id = dpt.set(t["ref"]),
             total = count(ways) + count(nodes);
  out;
);
</code>```

but since I understood that overpy doesn't deal with csv files, I would like to get a list of couples (area ref, number of bars and pubs).

This :

```<code>import overpy

api = overpy.Overpass()

dpts = api.query("""
// All french departements (level 6)
area[admin_level=6]["ISO3166-2"~"^FR-[0-9]|[1-8][0-9]|9[0-5]|2[A-B]"];

// Find bars and pubs in each dpt
foreach->.dpt(
  // looks for bars and pubs
  (
    way(area.dpt)[amenity=pub];
    way(area.dpt)[amenity=bar];
    node(area.dpt)[amenity=pub];
    node(area.dpt)[amenity=bar];
  );
  out;
);
""")
</code>```

gives me all the nodes and ways but not sorted by area.dept.

I got all the bars and pubs :

```<code>In [102]: len(dpts.ways + dpts.nodes)
Out[102]: 3895
</code>```

How could I get a list of type [(area ref, number of pubs and bars)] ?

答:
Well, I guess it is easy to use Python to loop :

```<code>Bars = []
api = overpy.Overpass()
for d in range(21,96):
    dpt = api.query("""
    area[admin_level=6]["ISO3166-2" = "FR-{}"];
    (way(area)[amenity=bar];
    node(area)[amenity=bar];);
    (._;>;);
    out;""".format(d))
    Bars.append((d, len(dpt.ways + dpt.nodes)))
Bars
</code>```

But that creates a query each time. Is it less efficient than looping inside the query ?

Body:
I would like to count amenities (bars and pubs) per admin_level 6 (departement) with overpy.

I succeeded to make a csv file with overpass turbo :

[out:csv(id, total )];
//All French départements (level 6) from FR-01 to FR-95 plus FR-2A and FR-2B
area[admin_level=6]["ISO3166-2"~"^FR-[0-9]|[1-8][0-9]|9[0-5]|2[A-B]"];

// Counts  bars and pubs in each dpt (level 6)
foreach->.dpt(
  // search for bars and pubs
  (
    way(area.dpt)[amenity=pub];
    way(area.dpt)[amenity=bar];
    node(area.dpt)[amenity=pub];
    node(area.dpt)[amenity=bar];
  );

  make count id = dpt.set(t["ref"]),
             total = count(ways) + count(nodes);
  out;
);

but since I understood that overpy doesn't deal with csv files, I would like to get a list of couples (area ref, number of bars and pubs).

This :

import overpy

api = overpy.Overpass()

dpts = api.query("""
// All french departements (level 6)
area[admin_level=6]["ISO3166-2"~"^FR-[0-9]|[1-8][0-9]|9[0-5]|2[A-B]"];

// Find bars and pubs in each dpt
foreach->.dpt(
  // looks for bars and pubs
  (
    way(area.dpt)[amenity=pub];
    way(area.dpt)[amenity=bar];
    node(area.dpt)[amenity=pub];
    node(area.dpt)[amenity=bar];
  );
  out;
);
""")

gives me all the nodes and ways but not sorted by area.dept.

I got all the bars and pubs :

In [102]: len(dpts.ways + dpts.nodes)
Out[102]: 3895

How could I get a list of type [(area ref, number of pubs and bars)] ?

Body:
Well, I guess it is easy to use Python to loop :

Bars = []
api = overpy.Overpass()
for d in range(21,96):
    dpt = api.query("""
    area[admin_level=6]["ISO3166-2" = "FR-{}"];
    (way(area)[amenity=bar];
    node(area)[amenity=bar];);
    (._;>;);
    out;""".format(d))
    Bars.append((d, len(dpt.ways + dpt.nodes)))
Bars

But that creates a query each time. Is it less efficient than looping inside the query ?


问:
How to get and play iPhone Default sound files?

Possible Duplicate:

  Play alert sound (same as default message ringtone)

Hi,

How to get and play iPhone default Sound files in iPhone.

答: You can do this, but it's undocumented. You wouldn't be able to do this in an App Store app. See here: Play alert sound (same as default message ringtone)</p>


问:
Not getting the first value when using "array_search"
Here, I have two multi-dimensional array. As I want to find the value from first array if the value is there in second array or not.

First array:

```<code>$abc = array(
    array("fld_channel_selected_item_track_id" => 627905217),
    array("fld_channel_selected_item_track_id" => 616557954)
);
</code>```

Second array:

```<code>$pqr = array(
    array(
        "fld_channel_item_track" => 627905217,
        "fld_channel_item_title" => "Tropical Fantasy"
    ),
    array(
        "fld_channel_item_track" => 616557954,
        "fld_channel_item_title" => "Bday Boys"
    )
);
</code>```

So, I am searching if the first array value is there in second array value or not:

```<code>for($i = 0;$i < count($abc); $i++)
{
    $pos = array_search($abc[$i]["fld_channel_selected_item_track_id"], array_column($pqr, 'fld_channel_item_track'));
    if($pos)
    {
        echo "```";print_r($pqr[$pos]);
    }
}
exit;
```

<p>The outout is:</p>

``````Array
(
    [fld_channel_item_track] => 616557954
    [fld_channel_item_title] => Bday Boys
)
</code>```

Here, I am not getting the first value in my output.

Where I am wrong in that?

答:
The problem is array_search (doc) return index -> in your case index 0 so if ($pos) fails...

Returns the key for needle if it is found in the array, FALSE otherwise.

Need to compare result to FALSE

By the way, this will be better way t achieve what you need:

```<code>$a = array_column($abc, 'fld_channel_selected_item_track_id');
$b = array_column($pqr, "fld_channel_item_title", "fld_channel_item_track");
foreach($a as $searchId)
    if (isset($b[$searchId])) echo $b[$searchId] . PHP_EOL;
</code>```

Body:
Here, I have two multi-dimensional array. As I want to find the value from first array if the value is there in second array or not.

First array:

$abc = array(
    array("fld_channel_selected_item_track_id" => 627905217),
    array("fld_channel_selected_item_track_id" => 616557954)
);

Second array:

$pqr = array(
    array(
        "fld_channel_item_track" => 627905217,
        "fld_channel_item_title" => "Tropical Fantasy"
    ),
    array(
        "fld_channel_item_track" => 616557954,
        "fld_channel_item_title" => "Bday Boys"
    )
);

So, I am searching if the first array value is there in second array value or not:

for($i = 0;$i < count($abc); $i++)
{
    $pos = array_search($abc[$i]["fld_channel_selected_item_track_id"], array_column($pqr, 'fld_channel_item_track'));
    if($pos)
    {
        echo "
";print_r($pqr[$pos]);
    }
}
exit;

The outout is:

Array
(
    [fld_channel_item_track] => 616557954
    [fld_channel_item_title] => Bday Boys
)

Here, I am not getting the first value in my output.

Where I am wrong in that?

Body:
The problem is array_search (doc) return index -> in your case index 0 so if ($pos) fails...

Returns the key for needle if it is found in the array, FALSE otherwise.

Need to compare result to FALSE

By the way, this will be better way t achieve what you need:

$a = array_column($abc, 'fld_channel_selected_item_track_id');
$b = array_column($pqr, "fld_channel_item_title", "fld_channel_item_track");
foreach($a as $searchId)
    if (isset($b[$searchId])) echo $b[$searchId] . PHP_EOL;


问:
How can I position my progress bar at the bottom of a button?
I am facing a bit of an issue and I can't seem to figure it out.

I am trying to create a button and add a bootstrap progress bar at the bottom of it, but I cant seem to figure out how to get it to do just that.

Here's my current setup. https://jsfiddle.net/bob_mosh/7qeazm9w/3/

HTML:

```<code><button id="sample_button" type="button" class="soundButton">
<label class="buttonTitle">Bird Song</label>
<label class="buttonDescription">A nice bird song.</label>
<div class="progress volume-slider">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</button>
</code>```

CSS:

```<code>.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}
</code>```

This is the current state on the right and the way I am envisioning it on the left.

For some reason I cant get the absolute positioning to work. Every time I try to set the position of the progress bar to absolute, it completely disappears. Can anyone help me figure this out?

答:
Long story short:

Absolute positioning works only inside of a relative container. I created a container in your html that only does that. I basically only set it to position:relative and then I used position:absolute; on the element inside of it. It disappears because absolute positioning removes the element from the flow. So other elements don't know it exists and basically gets stuck inside the first relative element it finds up the dom. If it doesn't, it goes 'poof'.

Read about positioning here

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}

.progress-bar {
  background-color: green;
  height: 50px;
  position: absolute;
}

.progress-container {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="sample_button" type="button" class="soundButton">
<label class="buttonTitle">Bird Song</label>
<label class="buttonDescription">A nice bird song.</label>
<div class="progress-container">
  <div class="progress volume-slider">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</button></code>```

Body:
I am facing a bit of an issue and I can't seem to figure it out.

I am trying to create a button and add a bootstrap progress bar at the bottom of it, but I cant seem to figure out how to get it to do just that.

Here's my current setup. https://jsfiddle.net/bob_mosh/7qeazm9w/3/

HTML:

<button id="sample_button" type="button" class="soundButton">
Bird Song
A nice bird song.

</button>

CSS:

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}

This is the current state on the right and the way I am envisioning it on the left.

For some reason I cant get the absolute positioning to work. Every time I try to set the position of the progress bar to absolute, it completely disappears. Can anyone help me figure this out?

Body:
Long story short:

Absolute positioning works only inside of a relative container. I created a container in your html that only does that. I basically only set it to position:relative and then I used position:absolute; on the element inside of it. It disappears because absolute positioning removes the element from the flow. So other elements don't know it exists and basically gets stuck inside the first relative element it finds up the dom. If it doesn't, it goes 'poof'.

Read about positioning here

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}

.progress-bar {
  background-color: green;
  height: 50px;
  position: absolute;
}

.progress-container {
  position: relative;
}

<button id="sample_button" type="button" class="soundButton">
<label class="buttonTitle">Bird Song</label>
<label class="buttonDescription">A nice bird song.</label>
<div class="progress-container">
  <div class="progress volume-slider">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</button>


问:
sed: Argument list too long when running sed -n
I am running this command from Why is my git repository so big? on a very big git repository as https://github.com/python/cpython

git rev-list --all --objects | sed -n $(git rev-list --objects --all | cut -f1 -d' ' | git cat-file --batch-check | grep blob | sort -n -k 3 | tail -n800 | while read hash type size; do size_in_kibibytes=$(echo $size | awk '{ foo = $1 / 1024 ; print foo "KiB" }'); echo -n "-e s/$hash/$size_in_kibibytes/p "; done) | sort -n -k1;

It works fine if I replace tail -n800 by tail -n40:

```<code>1160.94KiB Lib/ensurepip/_bundled/pip-8.0.2-py2.py3-none-any.whl
1169.59KiB Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl
1170.86KiB Lib/ensurepip/_bundled/pip-8.1.2-py2.py3-none-any.whl
1225.24KiB Lib/ensurepip/_bundled/pip-9.0.0-py2.py3-none-any.whl
...
</code>```

I found this question Bash : sed -n arguments saying I could use awk instead of sed.

Do you know how do fix this sed: Argument list too long when tail is -n800 instead of -n40?

答:
It seems you have used this anwer in the linked question: Some scripts I use:.... There is a telling comment in that answer:

This function is great, but it's unimaginably slow. It can't even finish on my computer if I remove the 40 line limit. FYI, I just added an answer with a more efficient version of this function. Check it out if you want to use this logic on a big repository, or if you want to see the sizes summed per file or per folder. – piojo Jul 28 '17 at 7:59

And luckily piojo has written another answer  addressing this. Just use his code.

Body:
I am running this command from Why is my git repository so big? on a very big git repository as https://github.com/python/cpython

git rev-list --all --objects | sed -n $(git rev-list --objects --all | cut -f1 -d' ' | git cat-file --batch-check | grep blob | sort -n -k 3 | tail -n800 | while read hash type size; do size_in_kibibytes=$(echo $size | awk '{ foo = $1 / 1024 ; print foo "KiB" }'); echo -n "-e s/$hash/$size_in_kibibytes/p "; done) | sort -n -k1;

It works fine if I replace tail -n800 by tail -n40:

1160.94KiB Lib/ensurepip/_bundled/pip-8.0.2-py2.py3-none-any.whl
1169.59KiB Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl
1170.86KiB Lib/ensurepip/_bundled/pip-8.1.2-py2.py3-none-any.whl
1225.24KiB Lib/ensurepip/_bundled/pip-9.0.0-py2.py3-none-any.whl
...

I found this question Bash : sed -n arguments saying I could use awk instead of sed.

Do you know how do fix this sed: Argument list too long when tail is -n800 instead of -n40?


问:
How do I extend gradle's clean task to delete a file?
So far I've added the following to my build.gradle

```<code>apply plugin: 'base'
clean << {
    delete '${rootDir}/api-library/auto-generated-classes/'
    println '${rootDir}/api-library/auto-generated-classes/'
}
</code>```

However, not only is my file not deleted, but the print statement shows that ${rootDir} is not being converted to the root directory of my project.

Why won't this work, what concepts am I missing?

答:
Gradle Kotlin Script analogue:</p>

```<code>tasks {
    getByName<Delete>("clean") {
        delete.add("logs") // add accepts argument with Any type
    }
}
</code>```

Body:
So far I've added the following to my build.gradle

apply plugin: 'base'
clean << {
    delete '${rootDir}/api-library/auto-generated-classes/'
    println '${rootDir}/api-library/auto-generated-classes/'
}

However, not only is my file not deleted, but the print statement shows that ${rootDir} is not being converted to the root directory of my project.

Why won't this work, what concepts am I missing?

Body:
Gradle Kotlin Script analogue:

tasks {
    getByName<Delete>("clean") {
        delete.add("logs") // add accepts argument with Any type
    }
}


问:
Query a single table with relationship database Flask-SQLAlchemy
I've got three tables: User, Role, Department

I want to query all the user with selected following filters:
Department.name , Role.name and User.degree

I can't find a solution to this problem, any suggestion would be great!

Here's my models simplified:

```<code>class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    degree = db.Column(db.String(20),default=None)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

class Department(db.Model):

    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    user = db.relationship('User', backref='department',
                                lazy='dynamic')

class Role(db.Model):

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    users = db.relationship('User', backref='role',
                                lazy='dynamic')
</code>```

答:
It's a simple query with joins. You can modify "department" with your department filter and "role" with the same. You should modify the select part (session.query(User.id)) with the fields you want.

```<code>users = (session.query(User.id).join(Department, Department.user == User.id).join(Role, Role.user == User.id).filter(Department.name=="department").filter(Role.name=="role").group_by(User.id))
</code>```

Body:
I've got three tables: User, Role, Department

I want to query all the user with selected following filters:
Department.name , Role.name and User.degree

I can't find a solution to this problem, any suggestion would be great!

Here's my models simplified:

class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    degree = db.Column(db.String(20),default=None)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

class Department(db.Model):

    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    user = db.relationship('User', backref='department',
                                lazy='dynamic')

class Role(db.Model):

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    users = db.relationship('User', backref='role',
                                lazy='dynamic')

Body:
It's a simple query with joins. You can modify "department" with your department filter and "role" with the same. You should modify the select part (session.query(User.id)) with the fields you want.

users = (session.query(User.id).join(Department, Department.user == User.id).join(Role, Role.user == User.id).filter(Department.name=="department").filter(Role.name=="role").group_by(User.id))


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
I have inherited a web app which was created with NHib and MyGeneration, unfortunately didn't get the svn repo, and no longer have the initial templates (arrggg).

Have kept nhibernate for the Create/Update/Delete back end stuff, but the front end (read only) was somewhat witlessly implemented, and runs like a 2 legged dog, and is now being rewritten in plain old ADO.NET, and goes up to 10 times faster.

Am not saying that this is due to NHibernate, it is due to developers not knowing how much crap they were sending along the wire, and assuming that blindly using a tool would mean they didn't have to think about it.

For the purpose of readonly queries, you can often make them much more efficient writing it by hand.

For things that have to write to the DB, is generally easier, and not that much slower, to let a decent ORM do it.

My personal preference is for SubSonic, which I have found performs pretty well for medium sized projects, and if you find a bottleneck, you can work around it by hand.

Tools are great, and anything that gives me more weekend is doubly great, but there is no substitute for the tool between your ears.

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: seanb


问:
How to Print the selected rows from the Datagridview in VB.NET
If i select the checkbox that particular data only Printed to the Paper

I have tried a lot of code but the entire DataGridView was printed. I just want to print the selected rows only

I expect the output like this

答:
Thank you so much Guys!!!
Finally i find a new way to print my datagridview

1) First i save the DataGridview like this below

Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
        Try

```<code>        For i As Integer = 0 To dgvData.Rows.Count - 1
            If CBool(dgvData.Rows(i).Cells("Column4").Value) Then
                str = " insert into tbl_dummy(opd,name,testname,category,cost) values (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & dgvData.Rows(i).Cells(0).Value & "','" + dgvData.Rows(i).Cells(1).Value & "','" + dgvData.Rows(i).Cells(2).Value & "') "
                cmd = New SqlCommand(str, cn)
                openconnection()
                da.InsertCommand = cmd
                da.InsertCommand.ExecuteNonQuery()
            End If
        Next
        MessageBox.Show("Data Added Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
        closeconnection()

    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub
</code>```

2) Then i take print from the database , By this way it gives the exact result what i need.

Body:
Thank you so much Guys!!!
Finally i find a new way to print my datagridview

1) First i save the DataGridview like this below

Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
        Try

        For i As Integer = 0 To dgvData.Rows.Count - 1
            If CBool(dgvData.Rows(i).Cells("Column4").Value) Then
                str = " insert into tbl_dummy(opd,name,testname,category,cost) values (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & dgvData.Rows(i).Cells(0).Value & "','" + dgvData.Rows(i).Cells(1).Value & "','" + dgvData.Rows(i).Cells(2).Value & "') "
                cmd = New SqlCommand(str, cn)
                openconnection()
                da.InsertCommand = cmd
                da.InsertCommand.ExecuteNonQuery()
            End If
        Next
        MessageBox.Show("Data Added Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
        closeconnection()

    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub

2) Then i take print from the database , By this way it gives the exact result what i need.


问:
CollapsingToolbar layout not scrolling
I have a collapsingtoolbarLayout i have included that in my linear layout after i designed the page i noticed that the collapsing toolbar layout is not scrolling.i am not able to scroll the layout

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fitsSystemWindows="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginBottom="32dp"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/changedImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/dinesh"
                    app:layout_collapseMode="parallax" />
                <android.support.v7.widget.Toolbar
                    android:id="@+id/anim_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                   app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

How to make it scrollable??

答:
You just need to remove LinearLayouts inside CoordinatorLayout to make it scrollable.

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:fitsSystemWindows="true">

    <!--<LinearLayout-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent"-->
        <!--android:orientation="vertical">-->

        <!--<LinearLayout-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:orientation="vertical">-->

            <android.support.design.widget.AppBarLayout
                android:id="@+id/appbar"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:fitsSystemWindows="true"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
                <android.support.design.widget.CollapsingToolbarLayout
                    android:id="@+id/collapsing_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    app:contentScrim="?attr/colorPrimary"
                    app:expandedTitleMarginBottom="32dp"
                    app:expandedTitleMarginEnd="64dp"
                    app:expandedTitleMarginStart="48dp"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed">
                    <ImageView
                        android:id="@+id/changedImage"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:fitsSystemWindows="true"
                        android:scaleType="centerCrop"
                        android:src="@drawable/dinesh"
                        app:layout_collapseMode="parallax" />
                    <android.support.v7.widget.Toolbar
                        android:id="@+id/anim_toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        app:layout_collapseMode="pin"
                        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                </android.support.design.widget.CollapsingToolbarLayout>
            </android.support.design.widget.AppBarLayout>
        <!--</LinearLayout>-->
    <!--</LinearLayout>-->
</android.support.design.widget.CoordinatorLayout>
</code>```

And if you want to show the Toolbar instead of ActionBar, you need to set a NoActionBar theme to your activity in AndroidManifest.xml such as:

```<code>android:theme="@style/AppTheme.NoActionBar"
</code>```

and add below code to onCreate of the activity:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.anim_toolbar);
setSupportActionBar(toolbar);
</code>```

Title: CollapsingToolbar layout not scrolling

Body:
I have a collapsingtoolbarLayout i have included that in my linear layout after i designed the page i noticed that the collapsing toolbar layout is not scrolling.i am not able to scroll the layout

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fitsSystemWindows="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginBottom="32dp"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/changedImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/dinesh"
                    app:layout_collapseMode="parallax" />
                <android.support.v7.widget.Toolbar
                    android:id="@+id/anim_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                   app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>

How to make it scrollable??

Body:
You just need to remove LinearLayouts inside CoordinatorLayout to make it scrollable.

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:fitsSystemWindows="true">

    <!--<LinearLayout-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent"-->
        <!--android:orientation="vertical">-->

        <!--<LinearLayout-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:orientation="vertical">-->

            <android.support.design.widget.AppBarLayout
                android:id="@+id/appbar"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:fitsSystemWindows="true"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
                <android.support.design.widget.CollapsingToolbarLayout
                    android:id="@+id/collapsing_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    app:contentScrim="?attr/colorPrimary"
                    app:expandedTitleMarginBottom="32dp"
                    app:expandedTitleMarginEnd="64dp"
                    app:expandedTitleMarginStart="48dp"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed">
                    <ImageView
                        android:id="@+id/changedImage"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:fitsSystemWindows="true"
                        android:scaleType="centerCrop"
                        android:src="@drawable/dinesh"
                        app:layout_collapseMode="parallax" />
                    <android.support.v7.widget.Toolbar
                        android:id="@+id/anim_toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        app:layout_collapseMode="pin"
                        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                </android.support.design.widget.CollapsingToolbarLayout>
            </android.support.design.widget.AppBarLayout>
        <!--</LinearLayout>-->
    <!--</LinearLayout>-->
</android.support.design.widget.CoordinatorLayout>

And if you want to show the Toolbar instead of ActionBar, you need to set a NoActionBar theme to your activity in AndroidManifest.xml such as:

android:theme="@style/AppTheme.NoActionBar"

and add below code to onCreate of the activity:

Toolbar toolbar = (Toolbar) findViewById(R.id.anim_toolbar);
setSupportActionBar(toolbar);


问:
CoordinatorLayout + AppBarLayout + Transparent Status Bar
My Scenario

I have an Activity(min SDK 19) with Coordinator and AppBar with Image and Scroll Behaviors, everything works fine except my status bar is not transparent nor translucent. Below is my

And I set that style to that Activity in manifest. Below is my xml layout.

These are images what I really want and what I got.

Image 1. I got like that, no transparent status bar.

Image 2. I want like that, with transparent status bar.

Image 3. Result after scroll, this is ok.

```<code>`<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

<com.google.android.material.appbar.AppBarLayout
        android:fitsSystemWindows="true"
        android:id="@+id/app_bar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <com.google.android.material.appbar.CollapsingToolbarLayout
            android:fitsSystemWindows="true"
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <androidx.appcompat.widget.AppCompatImageView
                app:srcCompat="@drawable/splash"
                android:id="@+id/expandedImage"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"/>

        <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

<androidx.core.widget.NestedScrollView
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <include layout="@layout/include_match_detail"/>

</androidx.core.widget.NestedScrollView>

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@drawable/ic_logo"/>
</code>```

`

答:
Change all android:fitsSystemWindows attribute from "true" to "false", this may help you get a translucent status bar,

but after you do this, your collapsingbarlayout is collapsed and the title in your toolbar may be shown in the status bar,

then you can try add android:layout_marginTop attribute in your toolbar and set its value to "20dp".

Body:
My Scenario

I have an Activity(min SDK 19) with Coordinator and AppBar with Image and Scroll Behaviors, everything works fine except my status bar is not transparent nor translucent. Below is my

And I set that style to that Activity in manifest. Below is my xml layout.

These are images what I really want and what I got.

Image 1. I got like that, no transparent status bar.

Image 2. I want like that, with transparent status bar.

Image 3. Result after scroll, this is ok.

`<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

<com.google.android.material.appbar.AppBarLayout
        android:fitsSystemWindows="true"
        android:id="@+id/app_bar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <com.google.android.material.appbar.CollapsingToolbarLayout
            android:fitsSystemWindows="true"
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <androidx.appcompat.widget.AppCompatImageView
                app:srcCompat="@drawable/splash"
                android:id="@+id/expandedImage"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"/>

        <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

<androidx.core.widget.NestedScrollView
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <include layout="@layout/include_match_detail"/>

</androidx.core.widget.NestedScrollView>

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@drawable/ic_logo"/>

`


答:
array_search() returns the position if it found, else will return FALSE

https://www.php.net/manual/en/function.array-search.php

Returns the key for needle if it is found in the array, FALSE otherwise.

Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

For the first value, it is actually found, but the result is 0

```<code>$pos = 0
</code>```

So it will fail the if...else check

```<code>if ($pos) {
   // $pos = 0 is falsy
}
</code>```

You need to perform a more explicit comparison

```<code>if ($pos !== FALSE) {
    // code here
}
</code>```

Title: Not getting the first value when using "array_search"

Body:
array_search() returns the position if it found, else will return FALSE

https://www.php.net/manual/en/function.array-search.php

Returns the key for needle if it is found in the array, FALSE otherwise.

Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

For the first value, it is actually found, but the result is 0

$pos = 0

So it will fail the if...else check

if ($pos) {
   // $pos = 0 is falsy
}

You need to perform a more explicit comparison

if ($pos !== FALSE) {
    // code here
}


问:
Conversion of string to integer, then again to string
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

```<code>      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });
</code>```

spinner1:

```<code>public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}
</code>```

spinner 2:

```<code>public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}
</code>```

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

答:
Try this :

```<code>result=String.valueOf(calc3);
</code>```

Instead of

```<code>result=Integer.toString(calc3);
</code>```

Body:
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });

spinner1:

public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}

spinner 2:

public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

Body:
Try this :

result=String.valueOf(calc3);

Instead of

result=Integer.toString(calc3);


问:
How to install Symfony framework on shared hosting account?
I have a questions while install Symfony framework on my shared hosting account.(hostmonster)

I can access SSH now, but I can not access httpd file.

so, I do not know how to set below setting using command line.

**

```<code><Directory "/$data_dir/symfony/web/sf">

 AllowOverride All

 Allow from All

</Directory>

<VirtualHost *:80>

  ServerName myapp.example.com

  DocumentRoot "/home/steve/myproject/web"

  DirectoryIndex index.php

  Alias /sf /$data_dir/symfony/web/sf

  <Directory "/home/steve/myproject/web">

   AllowOverride All

   Allow from All

  </Directory>

</VirtualHost>
</code>```

**

,

I tried this,

**

```<code>chmod 777 /home1/myaccount/php/data/symfony/web

chmod 777 /home1/myaccount/public_html/symfony/web
</code>```

**

But nothing changed.

when access mydomain.com, it show like this

```<code>#!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

chdir(dirname(__FILE__));
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
include(sfCoreAutoload::getInstance()->getBaseDir().'/command/cli.php');
</code>```

Please advice me how should I do .?

Thanks!

答:
You need to enable mod_rewrite on your apache instance.  If you cannot access the httpd configuration file, then you should create a .htaccess file in your web root.

Here is an example .htaccess file typical with symfony installs:

```<code>Options +FollowSymLinks +ExecCGI

<IfModule mod_rewrite.c>
  RewriteEngine On

  # uncomment the following line, if you are having trouble
  # getting no_script_name to work
  #RewriteBase /

  # we skip all files with .something
  #RewriteCond %{REQUEST_URI} \..+$
  #RewriteCond %{REQUEST_URI} !\.html$
  #RewriteRule .* - [L]

  # we check if the .html version is here (caching)
  RewriteRule ^$ index.html [QSA]
  RewriteRule ^([^.]+)$ $1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f

  # no, so we redirect to our front web controller
  RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
</code>```

Body:
I have a questions while install Symfony framework on my shared hosting account.(hostmonster)

I can access SSH now, but I can not access httpd file.

so, I do not know how to set below setting using command line.

**

<Directory "/$data_dir/symfony/web/sf">

 AllowOverride All

 Allow from All

</Directory>

<VirtualHost *:80>

  ServerName myapp.example.com

  DocumentRoot "/home/steve/myproject/web"

  DirectoryIndex index.php

  Alias /sf /$data_dir/symfony/web/sf

  <Directory "/home/steve/myproject/web">

   AllowOverride All

   Allow from All

  </Directory>

</VirtualHost>

**

,

I tried this,

**

chmod 777 /home1/myaccount/php/data/symfony/web

chmod 777 /home1/myaccount/public_html/symfony/web

**

But nothing changed.

when access mydomain.com, it show like this

#!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

chdir(dirname(__FILE__));
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
include(sfCoreAutoload::getInstance()->getBaseDir().'/command/cli.php');

Please advice me how should I do .?

Thanks!

Body:
You need to enable mod_rewrite on your apache instance.  If you cannot access the httpd configuration file, then you should create a .htaccess file in your web root.

Here is an example .htaccess file typical with symfony installs:

Options +FollowSymLinks +ExecCGI

<IfModule mod_rewrite.c>
  RewriteEngine On

  # uncomment the following line, if you are having trouble
  # getting no_script_name to work
  #RewriteBase /

  # we skip all files with .something
  #RewriteCond %{REQUEST_URI} \..+$
  #RewriteCond %{REQUEST_URI} !\.html$
  #RewriteRule .* - [L]

  # we check if the .html version is here (caching)
  RewriteRule ^$ index.html [QSA]
  RewriteRule ^([^.]+)$ $1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f

  # no, so we redirect to our front web controller
  RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>


问:
Java 8 - collecting into a map from a list of objects with nested list
I have a class with nested static class like:

```<code>public class User {
    private final Long userId;
    private final List<UserData> userData;

    {...}

    @Getter
    public static class UserData {
        private final Long customerId;
        private final String customerName;

    {...}
    }
}
</code>```

Then I have a List<User> users.
I would like to map users to Map<User.userId, UserData.customerId>.

So the map would look like this:

1. userId1, customerId1

2. userId1, customerId2

3. userId1, customerId3

4. userId2, customerId4

5. userId2, customerId5

6. userId3, customerId6

etc.

Any chance to do that via Java 8 streams? I've tried flatmapping the nested list, but having a problem with collecting the results.

答:
Assuming you want a Map<User.userId, List<UserData.customerId>> you can use this:

```<code> Map<Long, List<Long>> result = users.stream()
    .collect(Collectors.toMap(
        User::getUserId,
        u -> u.getUserData().stream()
            .map(UserData::getCustomerId)
            .collect(Collectors.toList())
    ));
</code>```

Body:
I have a class with nested static class like:

public class User {
    private final Long userId;
    private final List<UserData> userData;

    {...}

    @Getter
    public static class UserData {
        private final Long customerId;
        private final String customerName;

    {...}
    }
}

Then I have a List<User> users.
I would like to map users to Map<User.userId, UserData.customerId>.

So the map would look like this:

1. userId1, customerId1

2. userId1, customerId2

3. userId1, customerId3

4. userId2, customerId4

5. userId2, customerId5

6. userId3, customerId6

etc.

Any chance to do that via Java 8 streams? I've tried flatmapping the nested list, but having a problem with collecting the results.

Body:
Assuming you want a Map<User.userId, List<UserData.customerId>> you can use this:

 Map<Long, List<Long>> result = users.stream()
    .collect(Collectors.toMap(
        User::getUserId,
        u -> u.getUserData().stream()
            .map(UserData::getCustomerId)
            .collect(Collectors.toList())
    ));


问:
Is it possible to remove a property from a java object at run time?
I have a pojo with jpa anntations.  One of the string properties is marked as not nullable.  There is some code downstream which sets the value if it is not set. In certain cases this code needs to be triggered but if set the value to empty string this is treaded as a value and its not triggered.  I can't set the non null value to null and so I can't edit theobject to trigger the code in a conventional way.

To be honest this bit of code needs a refactoring anyway and I do have a work around but I'm sure I've seen a way to 'remove' the peroperty somewhere before (perhaps reflection ?)

So the class looks something like this...

```<code>@Entity
@Table(name="Example")
@SequenceGenerator(name = "seq1", sequenceName = "seq1")
public class Example implements Serializable {

    @Column(name="name", nullable=true, length = 100)
    private java.lang.String name;

    @Column(name="id", nullable=false)      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ1_Type_SEQ")
    @Id
    private long oID;

    @Column(name="extraval", nullable=false, length = 100)
    private java.lang.String entityVersion;4

...
</code>```

And extraVal gets set by various jpa/db constraints if it isn't set in the pojo.  Sometimes I would like to trigger this, even though it has already been set, but setting the value to empty string sets it to a value and setting to null triggers an error.

I can actually simulate the value in advance and I hope to refactor the code at some point so that I can do all my checks before I create the object in the first place so I'm not look to copy/recreate the object etc.  Like I say I'm just sure there is an elegant way to remove the property as a short term solution ?

答:
I'm just sure there is an elegant way to remove the property as a short term solution ?

There isn't.  It is not possible to modify a class using reflection.

In theory it is possible to modify a compiled class before or while it is being loaded.  However, the chances are that the annotation processor for your JPA framework is already doing that.  So I don't think that would be practical.  (Let alone desirable!)

Body:
I have a pojo with jpa anntations.  One of the string properties is marked as not nullable.  There is some code downstream which sets the value if it is not set. In certain cases this code needs to be triggered but if set the value to empty string this is treaded as a value and its not triggered.  I can't set the non null value to null and so I can't edit theobject to trigger the code in a conventional way.

To be honest this bit of code needs a refactoring anyway and I do have a work around but I'm sure I've seen a way to 'remove' the peroperty somewhere before (perhaps reflection ?)

So the class looks something like this...

@Entity
@Table(name="Example")
@SequenceGenerator(name = "seq1", sequenceName = "seq1")
public class Example implements Serializable {

    @Column(name="name", nullable=true, length = 100)
    private java.lang.String name;

    @Column(name="id", nullable=false)      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ1_Type_SEQ")
    @Id
    private long oID;

    @Column(name="extraval", nullable=false, length = 100)
    private java.lang.String entityVersion;4

...

And extraVal gets set by various jpa/db constraints if it isn't set in the pojo.  Sometimes I would like to trigger this, even though it has already been set, but setting the value to empty string sets it to a value and setting to null triggers an error.

I can actually simulate the value in advance and I hope to refactor the code at some point so that I can do all my checks before I create the object in the first place so I'm not look to copy/recreate the object etc.  Like I say I'm just sure there is an elegant way to remove the property as a short term solution ?


问:
Issue with parsing of Rascal DSL
I am unable to parse a language instance.

The parser complains about the first line (test_exe).

```<code>#
# example
#
set(TARGET_NAME test_exe)

set(${TARGET_NAME}_IDE_FOLDER "path/path")

set(${TARGET_NAME}_DIRS
    ${PATH}/a/inc
    ${PATH}/b/inc
)

set(${TARGET_NAME}_SOURCES
    example.c
)

set(${TARGET_NAME}_DEPS
    ${COMMON_DEPS}
)

configureTestExecutable(${TARGET_NAME} OBJ_TEST)
</code>```

The above is a recurring section in language instances.

If I replace the last line with

```<code>configureLibrary(${TARGET_NAME} OBJ_TEST)
</code>```

it does work.

I tried

```<code>syntax Configure = configure: ConfigureTestExecutable;
syntax Configure = configure: ConfigureTestExecutable+;
syntax Configure = configure: ConfigureTestExecutable*;
</code>```

all do not work.

This

```<code>syntax Configure = configure: ConfigureLibrary;
syntax Configure = configure: ConfigureLibrary+;
syntax Configure = configure: ConfigureLibrary*;
</code>```

does work somehow.

```<code>start syntax Build = build: Section+ sections;

layout Layout = Comment*;

lexical Comment = @category="Comment" "#" ![\n]* [\n];

syntax Section = section: Target target Options+ options;

syntax Target = target: "set" "(" Id targetMacro Id targetName ")";

syntax Options = options: IdeFolder Dirs Sources Deps Configure;

syntax IdeFolder = ideFolder: "set" "(" "$" "{" Id targetMacro "}" "_IDE_FOLDER" "\"" Id ideFolderPath "\"" ")";

syntax Dirs = dirs: "set" "(" "$" "{" Id targetMacro "}" "_DIRS" DirsPath+ dirPaths ")";

syntax DirsPath = dirPaths: "$" "{" Id pathMacro "}" Id? path;

syntax Sources = sources: "set" "(" "$" "{" Id targetMacro "}" "_SOURCES" SourceList+ sourceList ")";

syntax Configure = configure:

//ConfigureLibrary*

ConfigureTestExecutable;

//syntax ConfigureLibrary = configureLibrary: "configureLibrary" "(" "$" "{" Id targetMacro "}" Id buildTarget ")";

syntax ConfigureTestExecutable = configureTestExecutable: "configureTestExecutable" "(" "$" "{" Id targetMacro "}" Id buildTarget ")";

</code>```

The parse error I get is:

```<code>rascal>x = parse(|project://Instrumentation/src/CMakeLists.cmake|);
|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>): ParseError(|project://Instrumentation/src/CMakeLists.cmake|(32,1,<4,15>,<4,16>))
        at parse(|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>))
        at $root$(|prompt:///|(4,56,<1,4>,<1,60>))
        at *** somewhere ***(|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>))
        at parse(|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>))
        at $root$(|prompt:///|(4,56,<1,4>,<1,60>))
</code>```

答:
Two observations:

The layout definition does not include whitespace, but since part of the grammar is missing, I can't figure out if this is intentional (like layout sensitive parsing) or part of the problem.

Did you parse with #Build or #start[Build]? You need the second one to handle layout at beginning or end of the file.

So maybe you have to extend the question a bit?

Also, check if your parse tree is correct after it succeeded, because it might be parsing everything as a big string?

Title: Issue with parsing of Rascal DSL

Body:
I am unable to parse a language instance.

The parser complains about the first line (test_exe).

#
# example
#
set(TARGET_NAME test_exe)

set(${TARGET_NAME}_IDE_FOLDER "path/path")

set(${TARGET_NAME}_DIRS
    ${PATH}/a/inc
    ${PATH}/b/inc
)

set(${TARGET_NAME}_SOURCES
    example.c
)

set(${TARGET_NAME}_DEPS
    ${COMMON_DEPS}
)

configureTestExecutable(${TARGET_NAME} OBJ_TEST)

The above is a recurring section in language instances.

If I replace the last line with

configureLibrary(${TARGET_NAME} OBJ_TEST)

it does work.

I tried

syntax Configure = configure: ConfigureTestExecutable;
syntax Configure = configure: ConfigureTestExecutable+;
syntax Configure = configure: ConfigureTestExecutable*;

all do not work.

This

syntax Configure = configure: ConfigureLibrary;
syntax Configure = configure: ConfigureLibrary+;
syntax Configure = configure: ConfigureLibrary*;

does work somehow.

start syntax Build = build: Section+ sections;

layout Layout = Comment*;

lexical Comment = @category="Comment" "#" ![\n]* [\n];

syntax Section = section: Target target Options+ options;

syntax Target = target: "set" "(" Id targetMacro Id targetName ")";

syntax Options = options: IdeFolder Dirs Sources Deps Configure;

syntax IdeFolder = ideFolder: "set" "(" "$" "{" Id targetMacro "}" "_IDE_FOLDER" "\"" Id ideFolderPath "\"" ")";

syntax Dirs = dirs: "set" "(" "$" "{" Id targetMacro "}" "_DIRS" DirsPath+ dirPaths ")";

syntax DirsPath = dirPaths: "$" "{" Id pathMacro "}" Id? path;

syntax Sources = sources: "set" "(" "$" "{" Id targetMacro "}" "_SOURCES" SourceList+ sourceList ")";

syntax Configure = configure:

//ConfigureLibrary*

ConfigureTestExecutable;

//syntax ConfigureLibrary = configureLibrary: "configureLibrary" "(" "$" "{" Id targetMacro "}" Id buildTarget ")";

syntax ConfigureTestExecutable = configureTestExecutable: "configureTestExecutable" "(" "$" "{" Id targetMacro "}" Id buildTarget ")";

The parse error I get is:

rascal>x = parse(|project://Instrumentation/src/CMakeLists.cmake|);
|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>): ParseError(|project://Instrumentation/src/CMakeLists.cmake|(32,1,<4,15>,<4,16>))
        at parse(|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>))
        at $root$(|prompt:///|(4,56,<1,4>,<1,60>))
        at *** somewhere ***(|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>))
        at parse(|std:///ParseTree.rsc|(15449,5,<447,107>,<447,112>))
        at $root$(|prompt:///|(4,56,<1,4>,<1,60>))


问:
Numbering row in order by ID
Sorry if this post is not well organized, first time stack overflower...

I am trying to create a column to create a order within each IDs, but the twist is that if there is a gap year, order needs to start from the beginning.
Please check example and expected result below.

I wasn't able to find appropriate code for it.. I cannot think of anything :( Please help me! I appreciate alot!

答:
A data.table option:

```<code>library(data.table)
setDT(df)
df[, jump := Year - shift(Year) - 1, by = ID
   ][is.na(jump), jump := 0
     ][, order := seq_len(.N), by = .(ID, cumsum(jump))]

#     ID Year jump order
#  1:  A 2007    0     1
#  2:  A 2008    0     2
#  3:  A 2009    0     3
#  4:  A 2013    3     1
#  5:  A 2014    0     2
#  6:  A 2015    0     3
#  7:  A 2016    0     4
#  8:  B 2010    0     1
#  9:  B 2012    1     1
# 10:  B 2013    0     2
</code>```

Or using data.table::nafill() available in data.table v1.12.3 (still in development):

```<code>df[, jump := nafill(Year - shift(Year) - 1, fill = 0), by = ID
   ][, order := seq_len(.N), by = .(ID, cumsum(jump))]
</code>```

Title: Numbering row in order by ID

Body:
A data.table option:

library(data.table)
setDT(df)
df[, jump := Year - shift(Year) - 1, by = ID
   ][is.na(jump), jump := 0
     ][, order := seq_len(.N), by = .(ID, cumsum(jump))]

#     ID Year jump order
#  1:  A 2007    0     1
#  2:  A 2008    0     2
#  3:  A 2009    0     3
#  4:  A 2013    3     1
#  5:  A 2014    0     2
#  6:  A 2015    0     3
#  7:  A 2016    0     4
#  8:  B 2010    0     1
#  9:  B 2012    1     1
# 10:  B 2013    0     2

Or using data.table::nafill() available in data.table v1.12.3 (still in development):

df[, jump := nafill(Year - shift(Year) - 1, fill = 0), by = ID
   ][, order := seq_len(.N), by = .(ID, cumsum(jump))]


问:
Get File Size On An FTP in C#
I want to get the size of a file on an FTP.

```<code>        //Get File Size
        reqSize = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + filePath));
        reqSize.Credentials = new NetworkCredential(Username, Password);
        reqSize.Method = WebRequestMethods.Ftp.GetFileSize;
        reqSize.UseBinary = true;
        FtpWebResponse respSize = (FtpWebResponse)reqSize.GetResponse();
        long size = respSize.ContentLength;
        respSize.Close();
</code>```

I have tried the following but get a 550 error.  File not found / no access.  However, the following code works...

```<code>                reqTime = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + filePath));
                reqTime.Credentials = new NetworkCredential(Username, Password);
                reqTime.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                reqTime.UseBinary = true;
                FtpWebResponse respTime = (FtpWebResponse)reqTime.GetResponse();
                DateTime LastModified = respTime.LastModified;
                respTime.Close();
</code>```

EDIT: The reason this isn't working for me is that my FTP Server does not support the SIZE method.

答:
I tried to get file size while downloading it.
Both, given answers doesn't work for me, so I made this, using StatusDescription property of FtpWebResponse with DownloadFile method:

```<code>int openingBracket = response.StatusDescription.IndexOf("(");
int closingBracket = response.StatusDescription.IndexOf(")");
var temporarySubstring = response.StatusDescription.Substring(openingBracket+1, closingBracket - openingBracket);
var fileSize = temporarySubstring.Substring(0, temporarySubstring.IndexOf(" "));
</code>```

I suppose there is better way to do this with RegEx.

Title: Get File Size On An FTP in C#

Body:
I want to get the size of a file on an FTP.

        //Get File Size
        reqSize = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + filePath));
        reqSize.Credentials = new NetworkCredential(Username, Password);
        reqSize.Method = WebRequestMethods.Ftp.GetFileSize;
        reqSize.UseBinary = true;
        FtpWebResponse respSize = (FtpWebResponse)reqSize.GetResponse();
        long size = respSize.ContentLength;
        respSize.Close();

I have tried the following but get a 550 error.  File not found / no access.  However, the following code works...

                reqTime = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + filePath));
                reqTime.Credentials = new NetworkCredential(Username, Password);
                reqTime.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                reqTime.UseBinary = true;
                FtpWebResponse respTime = (FtpWebResponse)reqTime.GetResponse();
                DateTime LastModified = respTime.LastModified;
                respTime.Close();

EDIT: The reason this isn't working for me is that my FTP Server does not support the SIZE method.

Body:
I tried to get file size while downloading it.
Both, given answers doesn't work for me, so I made this, using StatusDescription property of FtpWebResponse with DownloadFile method:

int openingBracket = response.StatusDescription.IndexOf("(");
int closingBracket = response.StatusDescription.IndexOf(")");
var temporarySubstring = response.StatusDescription.Substring(openingBracket+1, closingBracket - openingBracket);
var fileSize = temporarySubstring.Substring(0, temporarySubstring.IndexOf(" "));

I suppose there is better way to do this with RegEx.


问:
Unable to run xml test suite from command prompt
I have TestNG suite with 2 tests included into an XML file. Test Suite works just fine if launching via IDE ( Eclipse ). However, I do need to run via command prompt.  I try launching it using the following command:

```<code>java -cp C:\eclipse\plugins\org.testng.eclipse_6.9.5.201505251947\lib\*;C:\myworkspace\myproject\bin org.testng.TestNG MyTestSuite.xml
</code>```

The error that occurs is:

```<code>[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test1

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest1 - unable to resolve class reference org/openqa/selenium/WebDriver

[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test2

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest2 - unable to resolve class reference org/openqa/selenium/WebDriver
</code>```

TestNG also reports 0 test runs with 0 failures and 0 skips if that's relevant.

答:
As the Test Suite works just fine if launching via IDE ( Eclipse ) you can follow the below mentioned steps to execute the Test Suite through command prompt:

Steps

Get the absolute Project Location from your IDE (i.e. Eclipse), browse to the sub-directory and create a directory lib

Copy all the relevant jars and libraries (Selenium and TestNG jars) in the lib directory.

selenium-server-standalone-3.13.0.jar

org.testng_6.14.2.r201802161450.jar

com.beust.jcommander_1.72.0.jar

org.apache-extras.beanshell.bsh_2.0.0.b6.jar

org.yaml.snakeyaml_1.17.0.jar

Through CLI browse to the Project Directory and provide the following classpath:

```<code>>set classpath=<Project Directory>\bin;<Project Directory>\lib\*;
</code>```

Through CLI execute testng.xml as follows:

```<code>Project_Directory>java org.testng.TestNG testng.xml
</code>```

On successful execution, within the Project Directory create a new text document and add the following code:

```<code>java -cp bin;lib/* org.testng.TestNG testng.xml
</code>```

Save the file as run.bat

Execute the Windows batch file run.bat and verify it executes the Test Suite as expected.

You can find a detailed relevant discussion in Need correct step for Bat file creation using (TestNG.xml + Maven)

Body:
I have TestNG suite with 2 tests included into an XML file. Test Suite works just fine if launching via IDE ( Eclipse ). However, I do need to run via command prompt.  I try launching it using the following command:

java -cp C:\eclipse\plugins\org.testng.eclipse_6.9.5.201505251947\lib\*;C:\myworkspace\myproject\bin org.testng.TestNG MyTestSuite.xml

The error that occurs is:

[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test1

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest1 - unable to resolve class reference org/openqa/selenium/WebDriver

[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test2

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest2 - unable to resolve class reference org/openqa/selenium/WebDriver

TestNG also reports 0 test runs with 0 failures and 0 skips if that's relevant.

Body:
As the Test Suite works just fine if launching via IDE ( Eclipse ) you can follow the below mentioned steps to execute the Test Suite through command prompt:

Steps

Get the absolute Project Location from your IDE (i.e. Eclipse), browse to the sub-directory and create a directory lib

Copy all the relevant jars and libraries (Selenium and TestNG jars) in the lib directory.

selenium-server-standalone-3.13.0.jar

org.testng_6.14.2.r201802161450.jar

com.beust.jcommander_1.72.0.jar

org.apache-extras.beanshell.bsh_2.0.0.b6.jar

org.yaml.snakeyaml_1.17.0.jar

Through CLI browse to the Project Directory and provide the following classpath:

>set classpath=<Project Directory>\bin;<Project Directory>\lib\*;

Through CLI execute testng.xml as follows:

Project_Directory>java org.testng.TestNG testng.xml

On successful execution, within the Project Directory create a new text document and add the following code:

java -cp bin;lib/* org.testng.TestNG testng.xml

Save the file as run.bat

Execute the Windows batch file run.bat and verify it executes the Test Suite as expected.

You can find a detailed relevant discussion in Need correct step for Bat file creation using (TestNG.xml + Maven)


问:
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

```<code>bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}
</code>```

答:
Tokens are the output of lexical analysis and the input to parsing. Typically they are things like

numbers

variable names

parentheses

arithmetic operators

statement terminators

That is, roughly, the biggest things that can be unambiguously identified by code that just looks at its input one character at a time.

One note, which you should feel free to ignore if it confuses you: The boundary between lexical analysis and parsing is a little fuzzy. For instance:

Some programming languages have complex-number literals that look, say, like 2+3i or 3.2e8-17e6i. If you were parsing such a language, you could make the lexer gobble up a whole complex number and make it into a token; or you could have a simpler lexer and a more complicated parser, and make (say) 3.2e8, -, 17e6i be separate tokens; it would then be the parser's job (or even the code generator's) to notice that what it's got is really a single literal.

In some programming languages, the lexer may not be able to tell whether a given token is a variable name or a type name. (This happens in C, for instance.) But the grammar of the language may distinguish between the two, so that you'd like "variable foo" and "type name foo" to be different tokens. (This also happens in C.) In this case, it may be necessary for some information to be fed back from the parser to the lexer so that it can produce the right sort of token in each case.

So "what exactly is a token?" may not always have a perfectly well defined answer.

Body:
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}