问:
Most performant way to filter a huge List in C#?
We have an ASP.NET MVC web application that is hooked up to a SQL Server DB via Entity Framework. One of the main tasks of this application is to allow users to quickly search and filter a huge database table that holds archive values.

The table structure is quite simple: Timestamp (DateTime), StationId (int), DatapointId (int), Value (double). This table holds somewhat between 10 to 100 million rows. I optimized the DB table with a covering index etc., but the user experience was still quite laggy when filtering by DatapointId, StationId, Time and Skipping and Taking only the portion I want to show on the page.

So I tried a different approach: as our server has a lot of RAM, I thought that we could simply load the whole archive table into a List<ArchiveRow> when the web app starts up, then simply get the data directly from this List instead of doing a round-trip to the database. This works quite well, it takes about 9 seconds to load the whole archive table (with currently about 10 million entries) into the List. The ArchiveRow is a simple object that looks like this:

```<code>public class ArchiveResponse {
    public  int Length { get; set; }
    public int numShown { get; set; }
    public  int numFound { get; set; }
    public  int numTotal { get; set; }
    public  List<ArchiveRow> Rows { get; set; }
}
</code>```

and accordingly:

```<code>public class ArchiveRow {
    public  int s { get; set; }
    public  int d { get; set; }
    public  DateTime t { get; set; }
    public  double v { get; set; }
}
</code>```

When I now try to get the desired data from the List with a Linq query, it is already faster the querying the DB, but it is still quite slow when filtering by multiple criteria. For example, when I filter by one StationId and 12 DatapointIds, it takes about 5 seconds to retrieve a window of 25 rows. I already switched from filtering with Where to using joins, but I think there is still room for improvement. Are there maybe better ways to implement such a caching mechanism while keeping memory consumption as low as possible? Are there other collection types that are better suited for this purpose?

So here is the code that filters and fetches the relevant data from the ArchiveCache list:

```<code>// Total number of entries in archive cache
var numTotal = ArchiveCache.Count();

// Initial Linq query
ParallelQuery<ArchiveCacheValue> query = ArchiveCache.AsParallel();

// The request may contain StationIds that the user is interested in,
// so here's the filtering by StationIds with a join:
if (request.StationIds.Count > 0)
{
    query = from a in ArchiveCache.AsParallel()
             join b in request.StationIds.AsParallel()
             on a.StationId equals b
             select a;
}

// The request may contain DatapointIds that the user is interested in,
// so here's the filtering by DatapointIds with a join:
if (request.DatapointIds.Count > 0)
{
    query = from a in query.AsParallel()
             join b in request.DatapointIds.AsParallel()
             on a.DataPointId equals b
             select a;
}

// Number of matching entries after filtering and before windowing
int numFound = query.Count();

// Pagination: Select only the current window that needs to be shown on the page
var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// Number of entries on the current page that will be shown
int numShown = result.Count();

// Build a response object, serialize it to Json and return to client
// Note: The projection with the Rows is not a bottleneck, it is only done to
// shorten 'StationId' to 's' etc. At this point there are only 25 to 50 rows,
// so that is no problem and happens in way less than 1 ms
ArchiveResponse myResponse = new ArchiveResponse();
myResponse.Length = request.Length;
myResponse.numShown = numShown;
myResponse.numFound = numFound;
myResponse.numTotal = numTotal;
myResponse.Rows = result.Select(x => new archRow() { s = x.StationId, d = x.DataPointId, t = x.DateValue, v = x.Value }).ToList();

return JsonSerializer.ToJsonString(myResponse);
</code>```

Some more details: the number of stations is usually something between 5 to 50, rarely more than 50. The number of datapoints is <7000. The web application is set to 64 bit with <gcAllowVeryLargeObjects enabled="true" /> set in the web.config.

I'm really looking forward for further improvements and recommendations. Maybe there's a completely different approach based on arrays or similar, that performs way better without linq?

答:
Another optimization. Using linq join in memory is not that efficient.

So instead of joining the request.StationIds and request.DatapointIds i would create hashsets from them and use simple contains over the hashset. Something like this.

```<code>if (request.StationIds.Count > 0)
{
    var stationIdSet = new HashSet<int>(request.StationIds);
    query =  (from a in ArchiveCache
             stationIdSet.Contains(a.StationId)
             select a);
               // .AsParallel()
               // .MaxDegreeOfParallelism(...);
}
</code>```

Running it in sequental manner for 9m records and 30 station ids, out performed the join with roughly 150 - 250 ms

For the parallel version with MaxDegreeOfParallelism = 2, both (the join and hashset) were performing worse.

NOTE: AsParallel is putting overhead which for simple operations like those it may not be the best option.

Body:
We have an ASP.NET MVC web application that is hooked up to a SQL Server DB via Entity Framework. One of the main tasks of this application is to allow users to quickly search and filter a huge database table that holds archive values.

The table structure is quite simple: Timestamp (DateTime), StationId (int), DatapointId (int), Value (double). This table holds somewhat between 10 to 100 million rows. I optimized the DB table with a covering index etc., but the user experience was still quite laggy when filtering by DatapointId, StationId, Time and Skipping and Taking only the portion I want to show on the page.

So I tried a different approach: as our server has a lot of RAM, I thought that we could simply load the whole archive table into a List<ArchiveRow> when the web app starts up, then simply get the data directly from this List instead of doing a round-trip to the database. This works quite well, it takes about 9 seconds to load the whole archive table (with currently about 10 million entries) into the List. The ArchiveRow is a simple object that looks like this:

public class ArchiveResponse {
    public  int Length { get; set; }
    public int numShown { get; set; }
    public  int numFound { get; set; }
    public  int numTotal { get; set; }
    public  List<ArchiveRow> Rows { get; set; }
}

and accordingly:

public class ArchiveRow {
    public  int s { get; set; }
    public  int d { get; set; }
    public  DateTime t { get; set; }
    public  double v { get; set; }
}

When I now try to get the desired data from the List with a Linq query, it is already faster the querying the DB, but it is still quite slow when filtering by multiple criteria. For example, when I filter by one StationId and 12 DatapointIds, it takes about 5 seconds to retrieve a window of 25 rows. I already switched from filtering with Where to using joins, but I think there is still room for improvement. Are there maybe better ways to implement such a caching mechanism while keeping memory consumption as low as possible? Are there other collection types that are better suited for this purpose?

So here is the code that filters and fetches the relevant data from the ArchiveCache list:

// Total number of entries in archive cache
var numTotal = ArchiveCache.Count();

// Initial Linq query
ParallelQuery<ArchiveCacheValue> query = ArchiveCache.AsParallel();

// The request may contain StationIds that the user is interested in,
// so here's the filtering by StationIds with a join:
if (request.StationIds.Count > 0)
{
    query = from a in ArchiveCache.AsParallel()
             join b in request.StationIds.AsParallel()
             on a.StationId equals b
             select a;
}

// The request may contain DatapointIds that the user is interested in,
// so here's the filtering by DatapointIds with a join:
if (request.DatapointIds.Count > 0)
{
    query = from a in query.AsParallel()
             join b in request.DatapointIds.AsParallel()
             on a.DataPointId equals b
             select a;
}

// Number of matching entries after filtering and before windowing
int numFound = query.Count();

// Pagination: Select only the current window that needs to be shown on the page
var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// Number of entries on the current page that will be shown
int numShown = result.Count();

// Build a response object, serialize it to Json and return to client
// Note: The projection with the Rows is not a bottleneck, it is only done to
// shorten 'StationId' to 's' etc. At this point there are only 25 to 50 rows,
// so that is no problem and happens in way less than 1 ms
ArchiveResponse myResponse = new ArchiveResponse();
myResponse.Length = request.Length;
myResponse.numShown = numShown;
myResponse.numFound = numFound;
myResponse.numTotal = numTotal;
myResponse.Rows = result.Select(x => new archRow() { s = x.StationId, d = x.DataPointId, t = x.DateValue, v = x.Value }).ToList();

return JsonSerializer.ToJsonString(myResponse);

Some more details: the number of stations is usually something between 5 to 50, rarely more than 50. The number of datapoints is <7000. The web application is set to 64 bit with <gcAllowVeryLargeObjects enabled="true" /> set in the web.config.

I'm really looking forward for further improvements and recommendations. Maybe there's a completely different approach based on arrays or similar, that performs way better without linq?

Body:
Another optimization. Using linq join in memory is not that efficient.

So instead of joining the request.StationIds and request.DatapointIds i would create hashsets from them and use simple contains over the hashset. Something like this.

if (request.StationIds.Count > 0)
{
    var stationIdSet = new HashSet<int>(request.StationIds);
    query =  (from a in ArchiveCache
             stationIdSet.Contains(a.StationId)
             select a);
               // .AsParallel()
               // .MaxDegreeOfParallelism(...);
}

Running it in sequental manner for 9m records and 30 station ids, out performed the join with roughly 150 - 250 ms

For the parallel version with MaxDegreeOfParallelism = 2, both (the join and hashset) were performing worse.

NOTE: AsParallel is putting overhead which for simple operations like those it may not be the best option.


来源: stackexchange

问:
c# Correct way to convert string value to decimal
I need convert the any value in format "101.46" to decimal.

```<code>string s = "101.46";
decimal value = Convert.ToDecimal(s);
</code>```

But the decimal final value is always 10146. I need the format of the output value to be 101.46 as decimal

答:
Convert.ToDecimal will use the currently executing thread's culture - and my guess is that in your case, that's a culture that uses , as the decimal separator rather than .. You just need to specify the right culture - which is often the invariant culture - that's almost always the right culture to use for any strings that are intended to be machine-readable. (You should use the invariant culture for creating such strings too.)

I'd generally recommend using the static Parse methods over Convert.ToXyz (as they're often more capable, and have TryParse options too), so while you could pass the invariant culture to Convert.ToDecimal, I'd use:

```<code>decimal value = decimal.Parse(text, CultureInfo.InvariantCulture);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need convert the any value in format "101.46" to decimal.

string s = "101.46";
decimal value = Convert.ToDecimal(s);

But the decimal final value is always 10146. I need the format of the output value to be 101.46 as decimal

Body:
Convert.ToDecimal will use the currently executing thread's culture - and my guess is that in your case, that's a culture that uses , as the decimal separator rather than .. You just need to specify the right culture - which is often the invariant culture - that's almost always the right culture to use for any strings that are intended to be machine-readable. (You should use the invariant culture for creating such strings too.)

I'd generally recommend using the static Parse methods over Convert.ToXyz (as they're often more capable, and have TryParse options too), so while you could pass the invariant culture to Convert.ToDecimal, I'd use:

decimal value = decimal.Parse(text, CultureInfo.InvariantCulture);


问:
Can Julia run on SPARC Solaris?
I like Linux but I have spare capacity on an enterprise class SPARC Solaris platform.  I'm just wondering if anyone has tried running Julia there before as it doesn't seem to be a supported OS.</p>

答: No Julia does not run SPARC Solaris. Supported platforms are x86 (Linux+windows+mac+FreeBSD), ARM and Power8-LE. A SPARC port would not be too difficult, but would need to be done by someone who cares about that platform, and has access to relevant hardware. Unfortunately, that does not describe most of the current developers and contributors.

Title: Can Julia run on SPARC Solaris?


问:
ASP.NET MVC, One Role for two user, and little different behavior for each user
We have implemented custom roleprovider. This provide us to restricts access to parts of our site using roles. Now we have situation when two users have role Administrator. But one user1 can add comments, and user2 can not add comments(user1 and user2 have role Administrator).

What the best way to solve this problem?

Can we add roles like it Administrator.AddComment and put it in controller action?

答: Add a 'SuperUser' role. The purpose of the roles are to group common access/privileges. I think you need to add a new role.</p>

ContentLicense: CC BY-SA 2.5


问:
How to convert this String to Timestamp
i have a column with the Data like this "08.06.2017/10:20:46". Data Type is string. i want to convert it into timestamp.
i tried CAST("08.06.2017/10:20:46" AS TIMESTAMP) but it doesn't work
Can you please help me to convert it??
Thanks</p>

答:
Hive and Impala deals with dates in a similar manner. You need to use the function unix_timestamp to accept non standard date formats, then use from_unixtime function to convert to a timestamp. Below code should work for your example. </p>

```<code>SELECT from_unixtime(unix_timestamp('08.06.2017/10:20:46','dd.MM.yyyy/hh:mm:ss'));
</code>```

Title: How to convert this String to Timestamp

Body:
Hive and Impala deals with dates in a similar manner. You need to use the function unix_timestamp to accept non standard date formats, then use from_unixtime function to convert to a timestamp. Below code should work for your example.

SELECT from_unixtime(unix_timestamp('08.06.2017/10:20:46','dd.MM.yyyy/hh:mm:ss'));


问:
Get Previous and day before Previous date in batch file(cmd)
I have the following to determine the date and grab a file based on date. I need to modify this grab a file that has a date of yesterday and day before yesterday, i.e. date-1 and date-2. What do I need to change? Thanks!</p>

```<code>echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit
</code>```

答:
You can also call out to powershell very easily to grab the date and subtract a day from it.</p>

```<code>For /F "delims=" %%G In ('PowerShell -Command "&{((Get-Date).AddDays(-1)).ToString('MMddyyyy')}"') Do Set "yesterday=%%G"
</code>```

Body:
I have the following to determine the date and grab a file based on date. I need to modify this grab a file that has a date of yesterday and day before yesterday, i.e. date-1 and date-2. What do I need to change? Thanks!

echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit

Body:
You can also call out to powershell very easily to grab the date and subtract a day from it.

For /F "delims=" %%G In ('PowerShell -Command "&{((Get-Date).AddDays(-1)).ToString('MMddyyyy')}"') Do Set "yesterday=%%G"


问:
UML Class diagram - how do I represent different 'report' classes?
If I am sitting down with a business stakeholder and creating a conceptual class diagram for the purpose of domain modelling, after asking the client what are all of the "things"  that the domain entails and he includes some comments along the lines of:

"We need 'Report 1' for abc and 'Report 2' for xyz and so on....."

How would I go about modelling these on the conceptual class diagram? Do I just represent reports the same as any other class/entity?  What if the client comes up with many different reports? Should reports be included on the conceptual class diagram at all?

Thanks

答: You should model the classes that will create or contain the information used in classes. IMHO Report looks like how they want to view it and should be modeled as part of GUI. </p>


问:
postgresql jdbc: FATAL: database does not exist
I'm trying to connect to a database using the following code:

```<code>import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class Model {

        Connection connection;

        Model() {

                try {
                        connection = DriverManager.getConnection("jdbc:postgresql:localhost:5432/deliverp", "kais", "0000");
                }
                catch (SQLException e) {
                        e.printStackTrace();
                }
        }

        static {

                try {
                        Class.forName("org.postgresql.Driver");
                }
                catch (ClassNotFoundException e) {
                        e.printStackTrace();
                }
        }

        public boolean addClient(Object data[]) {

                return true;
        }
}
</code>```

But after running the Java program I receive the following stack trace:

```<code>Nov 17, 2017 8:58:24 AM org.postgresql.Driver connect
SEVERE: Connection error:
org.postgresql.util.PSQLException: FATAL: database "localhost:5432/deliverp" does not exist
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
        at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2603)
        at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:125)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:227)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
        at org.postgresql.Driver.makeConnection(Driver.java:450)
        at org.postgresql.Driver.connect(Driver.java:252)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at Model.<init>(Model.java:16)
        at DelivERP.<init>(DelivERP.java:42)
        at DelivERP.main(DelivERP.java:104)

org.postgresql.util.PSQLException: FATAL: database "localhost:5432/deliverp" does not exist
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
        at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2603)
        at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:125)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:227)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
        at org.postgresql.Driver.makeConnection(Driver.java:450)
        at org.postgresql.Driver.connect(Driver.java:252)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at Model.<init>(Model.java:16)
        at DelivERP.<init>(DelivERP.java:42)
        at DelivERP.main(DelivERP.java:104)
</code>```

Therefore I wanted to make sure that the database exists by running the test below:

```<code>kais@debian:~/Documents/DelivERP$ psql deliverp
psql (9.6.4)
Type "help" for help.

deliverp=> \d
             List of relations
 Schema |      Name      | Type  |  Owner
--------+----------------+-------+----------
 public | BusinessEntity | table | postgres
 public | Client         | table | postgres
 public | Company        | table | postgres
 public | Order          | table | postgres
 public | Product        | table | postgres
(5 rows)

deliverp=>
</code>```

It sounds to me weird that the server didn't find the database although it exists ..

Any thoughts?

答:
You can try:

```<code>connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/deliverp", "kais", "0000");
</code>```

or

```<code>connection = DriverManager.getConnection("jdbc:postgresql:deliverp", "kais", "0000");
</code>```

Body:
I'm trying to connect to a database using the following code:

import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class Model {

        Connection connection;

        Model() {

                try {
                        connection = DriverManager.getConnection("jdbc:postgresql:localhost:5432/deliverp", "kais", "0000");
                }
                catch (SQLException e) {
                        e.printStackTrace();
                }
        }

        static {

                try {
                        Class.forName("org.postgresql.Driver");
                }
                catch (ClassNotFoundException e) {
                        e.printStackTrace();
                }
        }

        public boolean addClient(Object data[]) {

                return true;
        }
}

But after running the Java program I receive the following stack trace:

Nov 17, 2017 8:58:24 AM org.postgresql.Driver connect
SEVERE: Connection error:
org.postgresql.util.PSQLException: FATAL: database "localhost:5432/deliverp" does not exist
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
        at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2603)
        at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:125)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:227)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
        at org.postgresql.Driver.makeConnection(Driver.java:450)
        at org.postgresql.Driver.connect(Driver.java:252)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at Model.<init>(Model.java:16)
        at DelivERP.<init>(DelivERP.java:42)
        at DelivERP.main(DelivERP.java:104)

org.postgresql.util.PSQLException: FATAL: database "localhost:5432/deliverp" does not exist
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
        at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2603)
        at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:125)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:227)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
        at org.postgresql.Driver.makeConnection(Driver.java:450)
        at org.postgresql.Driver.connect(Driver.java:252)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at Model.<init>(Model.java:16)
        at DelivERP.<init>(DelivERP.java:42)
        at DelivERP.main(DelivERP.java:104)

Therefore I wanted to make sure that the database exists by running the test below:

kais@debian:~/Documents/DelivERP$ psql deliverp
psql (9.6.4)
Type "help" for help.

deliverp=> \d
             List of relations
 Schema |      Name      | Type  |  Owner
--------+----------------+-------+----------
 public | BusinessEntity | table | postgres
 public | Client         | table | postgres
 public | Company        | table | postgres
 public | Order          | table | postgres
 public | Product        | table | postgres
(5 rows)

deliverp=>

It sounds to me weird that the server didn't find the database although it exists ..

Any thoughts?

Body:
You can try:

connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/deliverp", "kais", "0000");

or

connection = DriverManager.getConnection("jdbc:postgresql:deliverp", "kais", "0000");


问:
Show/hide user controls with menu items in WPF
I've created a stack panel on my main window with a dock panel holding the menu and menu items. In the same stack panel I have my 3 user controls. I need to display only one of these 3 user controls when a user clicks a menu item, but my hidden user controls still take up space when they are not shown.

Between the menu and my visible user control at the bottom, there is another hidden user control that takes up space.

The stack panel in question:

```<code><StackPanel>
        <DockPanel>
            <Menu DockPanel.Dock="Top">
                <MenuItem Header="Equipment">
                    <MenuItem Header="_List" Click="mnuEquipList_Click" />
                    <MenuItem Header="_Create" Click="mnuEquipCreate_Click" />
                    <MenuItem Header="_Update" Click="mnuEquipUpdate_Click" />
                </MenuItem>
                <MenuItem Header="_Exit" Click="mnuExit_Click" />
            </Menu>
        </DockPanel>
        <equipment:EquipmentCreateView Visibility="Hidden" x:Name="equipCreateView"></equipment:EquipmentCreateView>
        <equipment:EquipmentListView DataContext="{Binding EquipmentListViewModel}" Visibility="Hidden" x:Name="equipListView"></equipment:EquipmentListView>
        <equipment:EquipmentUpdateView Visibility="Hidden" x:Name="equipUpdateView"></equipment:EquipmentUpdateView>
    </StackPanel>
</code>```

When a user clicks a menu item, the Visibility property is set to true and the others to false. Is there another way to achieve this functionality?

答:
Simple way: Use "Collapsed" instead "Hidden"

Better way:

ViewModels of your Equipment Views must inhertance from common interface.

```<code>public class EquipmentCreateViewModel : IEquipment
{
     //...
}

public class EquipmentListViewModel : IEquipment
{
     //...
}
</code>```

You should assign this ViewModels in Property on Main viewmodel when users click buttons by RelayCommands.

```<code>public class MainViewModel
{
     public IEquipment SelectedEquipment {get;set;}
}
</code>```

On main View you should declare DataTemplate.

Parts of MainView.xaml:

```<code><UserControl.Resources>
        <ResourceDictionary>
            <DataTemplate DataType="{x:Type equipment:EquipmentCreateViewModel}">
                <equipment:EquipmentCreateView />
            </DataTemplate>
            <DataTemplate DataType="{x:Type equipment:EquipmentListViewModel}">
                <equipment:EquipmentListView />
            </DataTemplate>
            <!--And so on-->
        </ResourceDictionary>
    </UserControl.Resources>
</code>```

Body:
I've created a stack panel on my main window with a dock panel holding the menu and menu items. In the same stack panel I have my 3 user controls. I need to display only one of these 3 user controls when a user clicks a menu item, but my hidden user controls still take up space when they are not shown.

Between the menu and my visible user control at the bottom, there is another hidden user control that takes up space.

The stack panel in question:

<StackPanel>
        <DockPanel>
            <Menu DockPanel.Dock="Top">
                <MenuItem Header="Equipment">
                    <MenuItem Header="_List" Click="mnuEquipList_Click" />
                    <MenuItem Header="_Create" Click="mnuEquipCreate_Click" />
                    <MenuItem Header="_Update" Click="mnuEquipUpdate_Click" />
                </MenuItem>
                <MenuItem Header="_Exit" Click="mnuExit_Click" />
            </Menu>
        </DockPanel>
        <equipment:EquipmentCreateView Visibility="Hidden" x:Name="equipCreateView"></equipment:EquipmentCreateView>
        <equipment:EquipmentListView DataContext="{Binding EquipmentListViewModel}" Visibility="Hidden" x:Name="equipListView"></equipment:EquipmentListView>
        <equipment:EquipmentUpdateView Visibility="Hidden" x:Name="equipUpdateView"></equipment:EquipmentUpdateView>
    </StackPanel>

When a user clicks a menu item, the Visibility property is set to true and the others to false. Is there another way to achieve this functionality?

Body:
Simple way: Use "Collapsed" instead "Hidden"

Better way:

ViewModels of your Equipment Views must inhertance from common interface.

public class EquipmentCreateViewModel : IEquipment
{
     //...
}

public class EquipmentListViewModel : IEquipment
{
     //...
}

You should assign this ViewModels in Property on Main viewmodel when users click buttons by RelayCommands.

public class MainViewModel
{
     public IEquipment SelectedEquipment {get;set;}
}

On main View you should declare DataTemplate.

Parts of MainView.xaml:

<UserControl.Resources>
        <ResourceDictionary>
            <DataTemplate DataType="{x:Type equipment:EquipmentCreateViewModel}">
                <equipment:EquipmentCreateView />
            </DataTemplate>
            <DataTemplate DataType="{x:Type equipment:EquipmentListViewModel}">
                <equipment:EquipmentListView />
            </DataTemplate>
            <!--And so on-->
        </ResourceDictionary>
    </UserControl.Resources>


问:
How do I set LINESIZE and PAGESIZE with a substitution variable?
I am trying to use a PL/SQL script in SQL*Plus to set the linesize and pagesize based on a developer input on whether a report should print in landscape or portrait orientation. If it is landscape, I want linesize 132 and pagesize 60. If it is portrait, I want 88 and 80 respectively.

I am trying to use substitution variables to do so like this:

```<code>DEFINE PRINT_ORIENTATION 'PORTRAIT'

COLUMN LINESIZE_VALUE NOPRINT new_value LINE
COLUMN PAGESIZE_VALUE NOPRINT new_value PAGE

SELECT DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 88, 'LANDSCAPE', 132) AS LINE,
       DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 80, 'LANDSCAPE', 60) AS PAGE
FROM DUAL
/

SET LINESIZE &LINE
SET PAGESIZE &PAGE
</code>```

However, the system then just prompts me to manually enter values for line and page. What do I need to do to use a substitution variable in the SET command?

答:
With a "shell" substitution variable: What we do here to handle a similar issue, is we generate the correct sizing settings in a temporary sql file.

Not sure it'll help, but here's a hint on how to set the number of columns from the size of your terminal, with this in @$HOME/sqlmlogin.sql:

```<code>def_editor=emacs
set null °
set arraysize 1
set pagesize 0
set serveroutput on
host > $HOME/sqltmp_size.sql ; tty -s && ( eval $( resize ) ; echo "set lines $COLUMNS\n set pages 0" >> $HOME/sql/tmp_size.sql )
-- then call the temp script
@$HOME/sqltmp_size.sql
-- remove afterwards
host rm -f $HOME/sqltmp_size.sql
</code>```

And call sqlplus like this:

```<code>sqlplus / @$HOME/sqlmlogin.sql
</code>```

So you can also generate the static values you want for your users from a script like that.

Body:
I am trying to use a PL/SQL script in SQL*Plus to set the linesize and pagesize based on a developer input on whether a report should print in landscape or portrait orientation. If it is landscape, I want linesize 132 and pagesize 60. If it is portrait, I want 88 and 80 respectively.

I am trying to use substitution variables to do so like this:

DEFINE PRINT_ORIENTATION 'PORTRAIT'

COLUMN LINESIZE_VALUE NOPRINT new_value LINE
COLUMN PAGESIZE_VALUE NOPRINT new_value PAGE

SELECT DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 88, 'LANDSCAPE', 132) AS LINE,
       DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 80, 'LANDSCAPE', 60) AS PAGE
FROM DUAL
/

SET LINESIZE &LINE
SET PAGESIZE &PAGE

However, the system then just prompts me to manually enter values for line and page. What do I need to do to use a substitution variable in the SET command?

Body:
With a "shell" substitution variable: What we do here to handle a similar issue, is we generate the correct sizing settings in a temporary sql file.

Not sure it'll help, but here's a hint on how to set the number of columns from the size of your terminal, with this in @$HOME/sqlmlogin.sql:

def_editor=emacs
set null °
set arraysize 1
set pagesize 0
set serveroutput on
host > $HOME/sqltmp_size.sql ; tty -s && ( eval $( resize ) ; echo "set lines $COLUMNS\n set pages 0" >> $HOME/sql/tmp_size.sql )
-- then call the temp script
@$HOME/sqltmp_size.sql
-- remove afterwards
host rm -f $HOME/sqltmp_size.sql

And call sqlplus like this:

sqlplus / @$HOME/sqlmlogin.sql

So you can also generate the static values you want for your users from a script like that.


问:
why does group_by() affect out-of-scope data frames?
If I pass a grouped data frame to a function, then change the name of the grouped variable, the grouping of the original data frame gets changed to the new name.  When the function returns (I am not returning the altered data frame), the names of the original data frame are unchanged but the grouping is changed to the non-existent name.

```<code># test scoping of group_by() which appears to change groups
library(dplyr)

muck_up_group<-function(mydf){
  mydf<-mydf %>% rename(UhOh=Species)
}

dont_muck_up_group<-function(mydf){
  mydf<-mydf %>% ungroup()
  mydf<-mydf %>% rename(UhOh=Species)
}

data("iris")
iris<-as_tibble(iris) %>% group_by(Species)
iris
# A tibble: 150 x 5
# Groups:   Species [3]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
# 1          5.1         3.5          1.4         0.2  setosa

muck_up_group(iris) # original grouping changed to column name that doesn't exist
iris
# A tibble: 150 x 5
# Groups:   UhOh [3]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
# 1          5.1         3.5          1.4         0.2  setosa

#restore original state
iris<-as_tibble(iris) %>% group_by(Species)
dont_muck_up_group(iris) # original grouping preserved
iris
# A tibble: 150 x 5
# Groups:   Species [3]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
# 1          5.1         3.5          1.4         0.2  setosa
</code>```

I can understand why it might be bad practice to change the name of a grouping variable but it is permissible.  This seems to be an example of an attribute of a variable being passed by reference when the content is being passed by value (as we understand R does normally).

```<code>> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] graphics  grDevices utils     datasets  stats     methods   base

other attached packages:
 [1] lubridate_1.6.0               bindrcpp_0.2                  mFilter_0.1-3
 [4] ggrepel_0.6.5                 reshape2_1.4.2                scales_0.4.1
 [7] purrr_0.2.3                   readr_1.1.1                   tidyr_0.7.0
[10] tibble_1.3.4                  tidyverse_1.1.1               knitr_1.17
[13] Rblpapi_0.3.6                 stringr_1.2.0                 rvest_0.3.2
[16] xml2_1.1.1                    devtools_1.13.3               dplyr_0.7.2
[19] plyr_1.8.4                    ggplot2_2.2.1                 PerformanceAnalytics_1.4.3541
[22] xts_0.10-0                    zoo_1.8-0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.12       lattice_0.20-35    assertthat_0.2.0   rprojroot_1.2      digest_0.6.12
 [6] psych_1.7.5        R6_2.2.2           cellranger_1.1.0   backports_1.1.0    evaluate_0.10.1
[11] httr_1.3.1         highr_0.6          rlang_0.1.2        curl_2.8.1         lazyeval_0.2.0
[16] readxl_1.0.0       TTR_0.23-2         tidyquant_0.5.3    rmarkdown_1.6      labeling_0.3
[21] foreign_0.8-67     munsell_0.4.3      broom_0.4.2        compiler_3.4.0     modelr_0.1.1
[26] pkgconfig_2.0.1    base64enc_0.1-3    mnormt_1.5-5       htmltools_0.3.6    tidyselect_0.1.1
[31] withr_2.0.0        Quandl_2.8.0       grid_3.4.0         nlme_3.1-131       jsonlite_1.5
[36] gtable_0.2.0       magrittr_1.5       quantmod_0.4-10    stringi_1.1.5      RColorBrewer_1.1-2
[41] tools_3.4.0        forcats_0.2.0      glue_1.1.1         hms_0.3            rsconnect_0.8.5
[46] parallel_3.4.0     yaml_2.1.14        colorspace_1.3-2   memoise_1.1.0      bindr_0.1
[51] haven_1.1.0
>
</code>```

Bug?  Thanks.

答: See @aosmith’s comment above.  Dplyr closed issue.</p>

Body:
If I pass a grouped data frame to a function, then change the name of the grouped variable, the grouping of the original data frame gets changed to the new name.  When the function returns (I am not returning the altered data frame), the names of the original data frame are unchanged but the grouping is changed to the non-existent name.

# test scoping of group_by() which appears to change groups
library(dplyr)

muck_up_group<-function(mydf){
  mydf<-mydf %>% rename(UhOh=Species)
}

dont_muck_up_group<-function(mydf){
  mydf<-mydf %>% ungroup()
  mydf<-mydf %>% rename(UhOh=Species)
}

data("iris")
iris<-as_tibble(iris) %>% group_by(Species)
iris
# A tibble: 150 x 5
# Groups:   Species [3]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
# 1          5.1         3.5          1.4         0.2  setosa

muck_up_group(iris) # original grouping changed to column name that doesn't exist
iris
# A tibble: 150 x 5
# Groups:   UhOh [3]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
# 1          5.1         3.5          1.4         0.2  setosa

#restore original state
iris<-as_tibble(iris) %>% group_by(Species)
dont_muck_up_group(iris) # original grouping preserved
iris
# A tibble: 150 x 5
# Groups:   Species [3]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
# 1          5.1         3.5          1.4         0.2  setosa

I can understand why it might be bad practice to change the name of a grouping variable but it is permissible.  This seems to be an example of an attribute of a variable being passed by reference when the content is being passed by value (as we understand R does normally).

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] graphics  grDevices utils     datasets  stats     methods   base

other attached packages:
 [1] lubridate_1.6.0               bindrcpp_0.2                  mFilter_0.1-3
 [4] ggrepel_0.6.5                 reshape2_1.4.2                scales_0.4.1
 [7] purrr_0.2.3                   readr_1.1.1                   tidyr_0.7.0
[10] tibble_1.3.4                  tidyverse_1.1.1               knitr_1.17
[13] Rblpapi_0.3.6                 stringr_1.2.0                 rvest_0.3.2
[16] xml2_1.1.1                    devtools_1.13.3               dplyr_0.7.2
[19] plyr_1.8.4                    ggplot2_2.2.1                 PerformanceAnalytics_1.4.3541
[22] xts_0.10-0                    zoo_1.8-0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.12       lattice_0.20-35    assertthat_0.2.0   rprojroot_1.2      digest_0.6.12
 [6] psych_1.7.5        R6_2.2.2           cellranger_1.1.0   backports_1.1.0    evaluate_0.10.1
[11] httr_1.3.1         highr_0.6          rlang_0.1.2        curl_2.8.1         lazyeval_0.2.0
[16] readxl_1.0.0       TTR_0.23-2         tidyquant_0.5.3    rmarkdown_1.6      labeling_0.3
[21] foreign_0.8-67     munsell_0.4.3      broom_0.4.2        compiler_3.4.0     modelr_0.1.1
[26] pkgconfig_2.0.1    base64enc_0.1-3    mnormt_1.5-5       htmltools_0.3.6    tidyselect_0.1.1
[31] withr_2.0.0        Quandl_2.8.0       grid_3.4.0         nlme_3.1-131       jsonlite_1.5
[36] gtable_0.2.0       magrittr_1.5       quantmod_0.4-10    stringi_1.1.5      RColorBrewer_1.1-2
[41] tools_3.4.0        forcats_0.2.0      glue_1.1.1         hms_0.3            rsconnect_0.8.5
[46] parallel_3.4.0     yaml_2.1.14        colorspace_1.3-2   memoise_1.1.0      bindr_0.1
[51] haven_1.1.0
>

Bug?  Thanks.


问:
How do I upgrade React from 0.13 to 15.0.1?
Please tell me step by step process of upgrading React from version .13 to 15.0.1 .</p>

答:
By experience I can say that each version of react-native has breaking changes, for example from version 17 on, you need to remove @override on

```<code> public List<Class<? extends JavaScriptModule>> createJSModules()
</code>```

So my advice is update progressively along with all you project dependencies.

Body:
By experience I can say that each version of react-native has breaking changes, for example from version 17 on, you need to remove @override on

 public List<Class<? extends JavaScriptModule>> createJSModules()

So my advice is update progressively along with all you project dependencies.


问:
Measuring xcodebuild durations for all targets (including dependent ones)
Is it possible to measure time, that single xcodebuild command consumes to build every distinct target?

Let's say I have a target, which depends on some cocoapods: pod1 and pod2.
I build my target using xcodebuild. I can measure overall time.
I need to measure times, that were separately spent on pod1, pod2 and my target

I tried to find the answer in xcodebuild's output, but failed to do so.

Thanks in advance!

答:
I ended up writing a custom ruby script for modifing every target of my xcodeproj and of Pods.xcodeproj. This script adds two build phases that log the target name and current timestamp into an output file. One build phase executes first, an the other one executes last. Later on I simply substract one timestamp from another in a separate script.

Here is the result of the script:

The output file will look like this (after sorting)

```<code>Alamofire end: 1510929112.3409
Alamofire start: 1510929110.2161
AlamofireImage end: 1510929113.6925
AlamofireImage start: 1510929112.5205
</code>```

Path to the output file (/a/ci_automation/metrics/performance-metrics/a.txt on the screenshot) is not hardcoded anyhow. Instead, you pass it as a parameter of a ruby script like this:

$ruby prepare-for-target-build-time-profiling.rb ${PWD}/output.txt

Note, that this script requires cocoapods 1.3.1 (maybe 1.3).

Here is the ruby script: ruby prepare-for-target-build-time-profiling.rb

```<code>#!/usr/bin/env ruby

require 'xcodeproj'
require 'cocoapods'
require 'fileutils'

def inject_build_time_profiling_build_phases(project_path)
    project = Xcodeproj::Project.open(project_path)

    log_time_before_build_phase_name = '[Prefix placeholder] Log time before build'.freeze
    log_time_after_build_phase_name = '[Prefix placeholder] Log time after build'.freeze

    puts "Patching project at path: #{project_path}"
    puts
    project.targets.each do |target|
        puts "Target: #{target.name}"

        first_build_phase = create_leading_build_phase(target, log_time_before_build_phase_name)
        last_build_phase = create_trailing_build_phase(target, log_time_after_build_phase_name)

        puts
    end

    project.save

    puts "Finished patching project at path: #{project_path}"
    puts
end

def create_leading_build_phase(target, build_phase_name)
    remove_existing_build_phase(target, build_phase_name)

    build_phase = create_build_phase(target, build_phase_name)

    shift_build_phase_leftwards(target, build_phase)

    is_build_phase_leading = true

    inject_shell_code_into_build_phase(target, build_phase, is_build_phase_leading)

    return build_phase
end

def create_trailing_build_phase(target, build_phase_name)
    remove_existing_build_phase(target, build_phase_name)

    build_phase = create_build_phase(target, build_phase_name)

    is_build_phase_leading = false

    inject_shell_code_into_build_phase(target, build_phase, is_build_phase_leading)

    return build_phase
end

def remove_existing_build_phase(target, build_phase_name)
    existing_build_phase = target.shell_script_build_phases.find do |build_phase|
        build_phase.name.end_with?(build_phase_name)
        # We use `end_with` instead of `==`, because `cocoapods` adds its `[CP]` prefix to a `build_phase_name`
    end

    if !existing_build_phase.nil?
        puts "deleting build phase #{existing_build_phase.name}"

        target.build_phases.delete(existing_build_phase)
    end
end

def create_build_phase(target, build_phase_name)
    puts "creating build phase: #{build_phase_name}"

    build_phase = Pod::Installer::UserProjectIntegrator::TargetIntegrator
        .create_or_update_shell_script_build_phase(target, build_phase_name)

    return build_phase
end

def shift_build_phase_leftwards(target, build_phase)
    puts "moving build phase leftwards: #{build_phase.name}"

    target.build_phases.unshift(build_phase).uniq! unless target.build_phases.first == build_phase
end

def inject_shell_code_into_build_phase(target, build_phase, is_build_phase_leading)
    start_or_end = is_build_phase_leading ? "start" : "end"

    build_phase.shell_script = <<-SH.strip_heredoc
        timestamp=`echo "scale=4; $(gdate +%s%N/1000000000)" | bc`
        echo "#{target.name} #{start_or_end}: ${timestamp}" >> #{$build_time_logs_output_file}
    SH
end

def parse_arguments
    $build_time_logs_output_file = ARGV[0]

    if $build_time_logs_output_file.to_s.empty? || ! $build_time_logs_output_file.start_with?("/")
        puts "Error: you should pass a full path to a output file as an script's argument. Example:"
        puts "$ruby prepare-for-target-build-time-profiling.rb /path/to/script/output.txt"
        puts
        exit 1
    end
end

def print_arguments
    puts "Arguments:"
    puts "Output path: #{$build_time_logs_output_file}"
    puts
end

def clean_up_before_script
    if File.exist?($build_time_logs_output_file)
        FileUtils.rm($build_time_logs_output_file)
    end

    build_time_logs_output_folder = File.dirname($build_time_logs_output_file)
    unless File.directory?(build_time_logs_output_folder)
        FileUtils.mkdir_p(build_time_logs_output_folder)
    end
end

def main
    parse_arguments
    print_arguments
    clean_up_before_script
    inject_build_time_profiling_build_phases("path/to/project.xcodeproj")
    inject_build_time_profiling_build_phases("path/to/pods/project.xcodeproj")
end

# arguments:
$build_time_logs_output_file

main
</code>```

Body:
I ended up writing a custom ruby script for modifing every target of my xcodeproj and of Pods.xcodeproj. This script adds two build phases that log the target name and current timestamp into an output file. One build phase executes first, an the other one executes last. Later on I simply substract one timestamp from another in a separate script.

Here is the result of the script:

The output file will look like this (after sorting)

Alamofire end: 1510929112.3409
Alamofire start: 1510929110.2161
AlamofireImage end: 1510929113.6925
AlamofireImage start: 1510929112.5205

Path to the output file (/a/ci_automation/metrics/performance-metrics/a.txt on the screenshot) is not hardcoded anyhow. Instead, you pass it as a parameter of a ruby script like this:

$ruby prepare-for-target-build-time-profiling.rb ${PWD}/output.txt

Note, that this script requires cocoapods 1.3.1 (maybe 1.3).

Here is the ruby script: ruby prepare-for-target-build-time-profiling.rb

#!/usr/bin/env ruby

require 'xcodeproj'
require 'cocoapods'
require 'fileutils'

def inject_build_time_profiling_build_phases(project_path)
    project = Xcodeproj::Project.open(project_path)

    log_time_before_build_phase_name = '[Prefix placeholder] Log time before build'.freeze
    log_time_after_build_phase_name = '[Prefix placeholder] Log time after build'.freeze

    puts "Patching project at path: #{project_path}"
    puts
    project.targets.each do |target|
        puts "Target: #{target.name}"

        first_build_phase = create_leading_build_phase(target, log_time_before_build_phase_name)
        last_build_phase = create_trailing_build_phase(target, log_time_after_build_phase_name)

        puts
    end

    project.save

    puts "Finished patching project at path: #{project_path}"
    puts
end

def create_leading_build_phase(target, build_phase_name)
    remove_existing_build_phase(target, build_phase_name)

    build_phase = create_build_phase(target, build_phase_name)

    shift_build_phase_leftwards(target, build_phase)

    is_build_phase_leading = true

    inject_shell_code_into_build_phase(target, build_phase, is_build_phase_leading)

    return build_phase
end

def create_trailing_build_phase(target, build_phase_name)
    remove_existing_build_phase(target, build_phase_name)

    build_phase = create_build_phase(target, build_phase_name)

    is_build_phase_leading = false

    inject_shell_code_into_build_phase(target, build_phase, is_build_phase_leading)

    return build_phase
end

def remove_existing_build_phase(target, build_phase_name)
    existing_build_phase = target.shell_script_build_phases.find do |build_phase|
        build_phase.name.end_with?(build_phase_name)
        # We use `end_with` instead of `==`, because `cocoapods` adds its `[CP]` prefix to a `build_phase_name`
    end

    if !existing_build_phase.nil?
        puts "deleting build phase #{existing_build_phase.name}"

        target.build_phases.delete(existing_build_phase)
    end
end

def create_build_phase(target, build_phase_name)
    puts "creating build phase: #{build_phase_name}"

    build_phase = Pod::Installer::UserProjectIntegrator::TargetIntegrator
        .create_or_update_shell_script_build_phase(target, build_phase_name)

    return build_phase
end

def shift_build_phase_leftwards(target, build_phase)
    puts "moving build phase leftwards: #{build_phase.name}"

    target.build_phases.unshift(build_phase).uniq! unless target.build_phases.first == build_phase
end

def inject_shell_code_into_build_phase(target, build_phase, is_build_phase_leading)
    start_or_end = is_build_phase_leading ? "start" : "end"

    build_phase.shell_script = <<-SH.strip_heredoc
        timestamp=`echo "scale=4; $(gdate +%s%N/1000000000)" | bc`
        echo "#{target.name} #{start_or_end}: ${timestamp}" >> #{$build_time_logs_output_file}
    SH
end

def parse_arguments
    $build_time_logs_output_file = ARGV[0]

    if $build_time_logs_output_file.to_s.empty? || ! $build_time_logs_output_file.start_with?("/")
        puts "Error: you should pass a full path to a output file as an script's argument. Example:"
        puts "$ruby prepare-for-target-build-time-profiling.rb /path/to/script/output.txt"
        puts
        exit 1
    end
end

def print_arguments
    puts "Arguments:"
    puts "Output path: #{$build_time_logs_output_file}"
    puts
end

def clean_up_before_script
    if File.exist?($build_time_logs_output_file)
        FileUtils.rm($build_time_logs_output_file)
    end

    build_time_logs_output_folder = File.dirname($build_time_logs_output_file)
    unless File.directory?(build_time_logs_output_folder)
        FileUtils.mkdir_p(build_time_logs_output_folder)
    end
end

def main
    parse_arguments
    print_arguments
    clean_up_before_script
    inject_build_time_profiling_build_phases("path/to/project.xcodeproj")
    inject_build_time_profiling_build_phases("path/to/pods/project.xcodeproj")
end

# arguments:
$build_time_logs_output_file

main

ContentLicense: CC BY-SA 4.0


问:
Is there a step-by-step solution for implement voip into iphone?
I want to develop voip application for that how to I start up application.
provide me steps how to achieve this and there is a third party available for that.</p>

答: Check out MiuMiu, a VoIP app for iOS. It uses Asterisk for the server.</p>


问:
c# Math/Formula Calculation
I have an interesting problem i am trying to solve in my c# project, my head is hurting so any advice would be greatly appreciated

Basically i have an employee that works on a 3 week cycle

wk 1 - they work mon

wk 2 - they work wed

wk 3 - they work fri

wk 4 - they work mon

wk 5 - they work wed
.. and so on

I need a formula that will show me what day they worked on any given week, ie what day would they work on week 49 of employment?

Any thoughts on how i may solve this equation?

Cheers
Anthony

答:
As discussed in comment we can use modulo (%) operator in your formula.

int dayInt = (nthWeek % 3);

This will give you result in 0, 1, 2. 0 - friday, 1 - Monday, 2-
  wednesday

Here is the code:

```<code>int nthWeek = 49;

    int result = (nthWeek % 3);

    switch(result)
    {
        case 0:
            Console.WriteLine("Worker is working on Friday");
        break;

        case 1:
            Console.WriteLine("Worker is working on Monday");
        break;

        case 2:
            Console.WriteLine("Worker is working on Wednesday");
        break;

        default:
            Console.WriteLine("Worker is working on other day");
        break;
    }
</code>```

Implementation: DotnetFiddler

Title: c# Math/Formula Calculation

Body:
As discussed in comment we can use modulo (%) operator in your formula.

int dayInt = (nthWeek % 3);

This will give you result in 0, 1, 2. 0 - friday, 1 - Monday, 2-
  wednesday

Here is the code:

int nthWeek = 49;

    int result = (nthWeek % 3);

    switch(result)
    {
        case 0:
            Console.WriteLine("Worker is working on Friday");
        break;

        case 1:
            Console.WriteLine("Worker is working on Monday");
        break;

        case 2:
            Console.WriteLine("Worker is working on Wednesday");
        break;

        default:
            Console.WriteLine("Worker is working on other day");
        break;
    }

Implementation: DotnetFiddler


答:
```<code>public static boolean isNumeric(String str)
{
  try
  {
    decimal d = decimal.parseDouble(str);
  }
  catch(NumberFormatException nfe)
  {
    return false;
  }
  return true;
}
</code>```

If you want to use regular expression you can use as below,

```<code>public static boolean isNumeric(String str)
{
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}
</code>```

If function returns true then

```<code>if(isNumeric(Yourvalue)){
  decimal value = decimal.Parse(s, CultureInfo.InvariantCulture);
}
</code>```

Title: c# Correct way to convert string value to decimal

Body:
public static boolean isNumeric(String str)
{
  try
  {
    decimal d = decimal.parseDouble(str);
  }
  catch(NumberFormatException nfe)
  {
    return false;
  }
  return true;
}

If you want to use regular expression you can use as below,

public static boolean isNumeric(String str)
{
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

If function returns true then

if(isNumeric(Yourvalue)){
  decimal value = decimal.Parse(s, CultureInfo.InvariantCulture);
}


问:
What’s the best application that allows multiple concurrent users logged into a server without disturbing each other?
We have a server located at our office & we have 6 employees distributed over 6 different cities.
We are facing a case where these 6 employees sometimes try to login into the server through internet
concurrently and perform different tasks like ( opening our ERP system, checking
some emails, deleting some files) without disturbing each other i.e. each employee will
work independently from each other.

Of course, we would prefer a software which provides these features over the internet to pass all the firewalls or any obstacles.

I have found some applications like TeamViewer but only allows one user to have full control

答: What is OS running on your server. Assuming you have windows server you can use Remote Desktop Sessions - http://msdn.microsoft.com/en-us/library/aa383052(v=VS.85).aspx</p>


问:
Nesting await in Parallel.ForEach
In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop.  The problem is that the parallel loop exits before the WCF calls are all complete.

How would you refactor this to work as expected?

```<code>var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customers = new  System.Collections.Concurrent.BlockingCollection<Customer>();

Parallel.ForEach(ids, async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
});

foreach ( var customer in customers )
{
    Console.WriteLine(customer.ID);
}

Console.ReadKey();
</code>```

答:
After introducing a bunch of helper methods, you will be able run parallel queries with this simple syntax:

```<code>const int DegreeOfParallelism = 10;
IEnumerable<double> result = await Enumerable.Range(0, 1000000)
    .Split(DegreeOfParallelism)
    .SelectManyAsync(async i => await CalculateAsync(i).ConfigureAwait(false))
    .ConfigureAwait(false);
</code>```

What happens here is: we split source collection into 10 chunks (.Split(DegreeOfParallelism)), then run 10 tasks each processing its items one by one (.SelectManyAsync(...)) and merge those back into a single list.

Worth mentioning there is a simpler approach:

```<code>double[] result2 = await Enumerable.Range(0, 1000000)
    .Select(async i => await CalculateAsync(i).ConfigureAwait(false))
    .WhenAll()
    .ConfigureAwait(false);
</code>```

But it needs a precaution: if you have a source collection that is too big, it will schedule a Task for every item right away, which may cause significant performance hits.

Extension methods used in examples above look as follows:

```<code>public static class CollectionExtensions
{
    /// <summary>
    /// Splits collection into number of collections of nearly equal size.
    /// </summary>
    public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, int slicesCount)
    {
        if (slicesCount <= 0) throw new ArgumentOutOfRangeException(nameof(slicesCount));

        List<T> source = src.ToList();
        var sourceIndex = 0;
        for (var targetIndex = 0; targetIndex < slicesCount; targetIndex++)
        {
            var list = new List<T>();
            int itemsLeft = source.Count - targetIndex;
            while (slicesCount * list.Count < itemsLeft)
            {
                list.Add(source[sourceIndex++]);
            }

            yield return list;
        }
    }

    /// <summary>
    /// Takes collection of collections, projects those in parallel and merges results.
    /// </summary>
    public static async Task<IEnumerable<TResult>> SelectManyAsync<T, TResult>(
        this IEnumerable<IEnumerable<T>> source,
        Func<T, Task<TResult>> func)
    {
        List<TResult>[] slices = await source
            .Select(async slice => await slice.SelectListAsync(func).ConfigureAwait(false))
            .WhenAll()
            .ConfigureAwait(false);
        return slices.SelectMany(s => s);
    }

    /// <summary>Runs selector and awaits results.</summary>
    public static async Task<List<TResult>> SelectListAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector)
    {
        List<TResult> result = new List<TResult>();
        foreach (TSource source1 in source)
        {
            TResult result1 = await selector(source1).ConfigureAwait(false);
            result.Add(result1);
        }
        return result;
    }

    /// <summary>Wraps tasks with Task.WhenAll.</summary>
    public static Task<TResult[]> WhenAll<TResult>(this IEnumerable<Task<TResult>> source)
    {
        return Task.WhenAll<TResult>(source);
    }
}
</code>```

Title: Nesting await in Parallel.ForEach

Body:
In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop.  The problem is that the parallel loop exits before the WCF calls are all complete.

How would you refactor this to work as expected?

var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customers = new  System.Collections.Concurrent.BlockingCollection<Customer>();

Parallel.ForEach(ids, async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
});

foreach ( var customer in customers )
{
    Console.WriteLine(customer.ID);
}

Console.ReadKey();

Body:
After introducing a bunch of helper methods, you will be able run parallel queries with this simple syntax:

const int DegreeOfParallelism = 10;
IEnumerable<double> result = await Enumerable.Range(0, 1000000)
    .Split(DegreeOfParallelism)
    .SelectManyAsync(async i => await CalculateAsync(i).ConfigureAwait(false))
    .ConfigureAwait(false);

What happens here is: we split source collection into 10 chunks (.Split(DegreeOfParallelism)), then run 10 tasks each processing its items one by one (.SelectManyAsync(...)) and merge those back into a single list.

Worth mentioning there is a simpler approach:

double[] result2 = await Enumerable.Range(0, 1000000)
    .Select(async i => await CalculateAsync(i).ConfigureAwait(false))
    .WhenAll()
    .ConfigureAwait(false);

But it needs a precaution: if you have a source collection that is too big, it will schedule a Task for every item right away, which may cause significant performance hits.

Extension methods used in examples above look as follows:

public static class CollectionExtensions
{
    /// <summary>
    /// Splits collection into number of collections of nearly equal size.
    /// </summary>
    public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, int slicesCount)
    {
        if (slicesCount <= 0) throw new ArgumentOutOfRangeException(nameof(slicesCount));

        List<T> source = src.ToList();
        var sourceIndex = 0;
        for (var targetIndex = 0; targetIndex < slicesCount; targetIndex++)
        {
            var list = new List<T>();
            int itemsLeft = source.Count - targetIndex;
            while (slicesCount * list.Count < itemsLeft)
            {
                list.Add(source[sourceIndex++]);
            }

            yield return list;
        }
    }

    /// <summary>
    /// Takes collection of collections, projects those in parallel and merges results.
    /// </summary>
    public static async Task<IEnumerable<TResult>> SelectManyAsync<T, TResult>(
        this IEnumerable<IEnumerable<T>> source,
        Func<T, Task<TResult>> func)
    {
        List<TResult>[] slices = await source
            .Select(async slice => await slice.SelectListAsync(func).ConfigureAwait(false))
            .WhenAll()
            .ConfigureAwait(false);
        return slices.SelectMany(s => s);
    }

    /// <summary>Runs selector and awaits results.</summary>
    public static async Task<List<TResult>> SelectListAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector)
    {
        List<TResult> result = new List<TResult>();
        foreach (TSource source1 in source)
        {
            TResult result1 = await selector(source1).ConfigureAwait(false);
            result.Add(result1);
        }
        return result;
    }

    /// <summary>Wraps tasks with Task.WhenAll.</summary>
    public static Task<TResult[]> WhenAll<TResult>(this IEnumerable<Task<TResult>> source)
    {
        return Task.WhenAll<TResult>(source);
    }
}


问:
How to make new decorators available within a class without explicitly importing them?
Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator):

```<code>class SomeClass:

    @some_decorator
    def some_method(self):
        pass
</code>```

I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass.

Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery.

To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible.

ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

答:
As best I can tell a metaclass can do this.  You somehow need to get the decorators available to the metaclass, possibly by importing, and then you can include them in the prepared namespace:</p>

```<code>class includewraps(type):
    def prepare(*args):
        from functools import wraps
        return {'wraps': wraps}

class haswraps (metaclass = includewraps):
    # wraps is available in this scope
</code>```

Body:
Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator):

class SomeClass:

    @some_decorator
    def some_method(self):
        pass

I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass.

Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery.

To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible.

ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

Body:
As best I can tell a metaclass can do this.  You somehow need to get the decorators available to the metaclass, possibly by importing, and then you can include them in the prepared namespace:

class includewraps(type):
    def prepare(*args):
        from functools import wraps
        return {'wraps': wraps}

class haswraps (metaclass = includewraps):
    # wraps is available in this scope


问:
Html ,css Mobile view issue
The mobile view is not like that is on desktop
you can check this too https://portal2portal.ml in your mobile web browser
even the slider that i have made is not properly visible in mobile even i have tried media query to fix mobile view but not working.
the problem is with
1.Hover navigation bar.
2.Slider.

hope so someone will help me.
-----------CSS--------------------

```<code>.body{
    font-family:arial,sans-serif;
    height:auto;
    width:auto;
}

*{
    padding: 0px;
    margin: 0px;
}
#secdiv{
    opacity:100;
    filter:(opacity=70;);
}
#maindiv ul{
    width:100%;
    height:80px;
    background:black;
    line-height:80px;
    color:white;
    margin:auto;
    text-align:center;
     font-family: "Times New Roman", Times, serif;
    font-size:50px;

}
#secdiv ul a{
    text-decoration: none;
    color: white;
    padding:15px;
    text-align:center;
}
#secdiv ul li{
        list-style-type:none;
        display:inline-block;
        float:center;
        text-align:center;
    }
#secdiv ul li:hover{
    background:darkred;
    transition:all 0.40s;
}
#secdiv h1{
    width:100px;
    float:left;
    cursor:pointer;
    margin-left:29px;
}

body{
font-family:"Oxygen",sans-serif;
font-size:16px;
line-height:1.5;
}
.content{
position:relative;
z-index:2;
margin:13% auto;
width:50%;
text-align:center;

}
.heading{
     font-family: "Times New Roman", Georgia, Serif;
margin-bottom:24px;
color:RED;
font-size:44px;

}
.para{
margin-bottom:24px;
color:orange;
font-size:44px;
 font-family: "Times New Roman", Georgia, Serif;
}
.btn{
padding:12px 28px;
color:#ff3c64;
font-size:22px;
text-decoration:none;
border:4px solid #ff3c64;}
#wrapper {
    margin:0 auto;
    width:100%;
    text-align:center;
    position:absolute;
    top:500px;
}
#googleimg{
    border-radius:50%;
    width:150px;
    height:150px;
    background-image:url("googleimage.jpg");
  background-size:cover;
       box-shadow: 10px 10px 5px #888888;
}
#wrapper2 {
    margin:0 auto;
    width:100%;
    text-align:center;
    position:absolute;
    top:500px;
    left:200px;
}
#railwayimg{
    border-radius:50%;
    width:150px;
    height:150px;
    background-image:url("railwayimg.jpg");
  background-size:cover;
       box-shadow: 10px 10px 5px #888888;
}
#wrapper3 {
    margin:0 auto;
    width:100%;
    text-align:center;
    position:absolute;
    top:512px;
    left:400px;
}
#govind{
    border-radius:50%;
    width:150px;
    height:150px;
    background-image:url("govind.png");
  background-size:cover;
       box-shadow: 10px 10px 5px #888888;
}
#contactus
{
 font-family:"Times New Roman",Times,serif;
 font-size:35px;
}
.container
{
    text-align:center;
    color:#2c2c2c;
    text-decoration:none;
    outline:thick ridge red;
    height:300px;
    width:300px;
    right:400px;
    margin:auto;
    background-color:#ffd6cc;

}
#mySidenav a {
    position: absolute; /* Position them relative to the browser window */
    left: -80px; /* Position them outside of the screen */
    transition: 0.3s; /* Add transition on hover */
    padding: 15px; /* 15px padding */
    width: 100px; /* Set a specific width */
    text-decoration: none; /* Remove underline */
    font-size: 20px; /* Increase font size */
    color: white; /* White text color */
    border-radius: 0 5px 5px 0; /* Rounded corners on the top right and bottom right side */
    font-family: "Times New Roman", Times, serif;
}

#mySidenav a:hover {
    left:0; /* On mouse-over, make the elements appear as they should */
}

/* The about link: 20px from the top with a green background */
#about {
    top: 200px;
    background-color:red ;
     font-family: "Times New Roman", Times, serif;
}

#tools{
    top:300px;
    background-color:blue; /* Blue */
     font-family: "Times New Roman", Times, serif;
}
#contact {
    top:400px;
    background-color:green /* Light Black */
}
h1{
    text-align:center;
    text-shadow:2px 2px 5px red;
    font-family: "Times New Roman", Times, serif;
}

.slider{
    width:800px;
    height:400px;
    background:url("sliderimage1.PNG");
    margin:100px auto;
    animation:slide 5s infinite;
    outline:solid;

}
@keyframes slide{
    25%{
        background:url("sliderimage1.png");
    }

    25%{
        background:url("sliderimage11.jpg");
    }
}
</code>```

<!DOCTYPE html>

    <title>Test site</title>

    <link rel="stylesheet" type="text/css" href="style.css">
   <link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="mobilecss.css" />
   <link rel="stylesheet" type="text/css" href="slidercss.css">

HOME

This is a prototype Website the contents you will find here is owned by creaters of this website In below you can see Slider

  ABOUT
  TOOLS
  CONTACT US

```

答:
Ok,first you are missing viewport tag:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
</code>```

The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

You don't need  this:

```<code><link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="mobilecss.css" />
</code>```

Write media queries inside css file.

Title: Html ,css Mobile view issue

Body:
The mobile view is not like that is on desktop
you can check this too https://portal2portal.ml in your mobile web browser
even the slider that i have made is not properly visible in mobile even i have tried media query to fix mobile view but not working.
the problem is with
1.Hover navigation bar.
2.Slider.

hope so someone will help me.
-----------CSS--------------------

.body{
    font-family:arial,sans-serif;
    height:auto;
    width:auto;
}

*{
    padding: 0px;
    margin: 0px;
}
#secdiv{
    opacity:100;
    filter:(opacity=70;);
}
#maindiv ul{
    width:100%;
    height:80px;
    background:black;
    line-height:80px;
    color:white;
    margin:auto;
    text-align:center;
     font-family: "Times New Roman", Times, serif;
    font-size:50px;

}
#secdiv ul a{
    text-decoration: none;
    color: white;
    padding:15px;
    text-align:center;
}
#secdiv ul li{
        list-style-type:none;
        display:inline-block;
        float:center;
        text-align:center;
    }
#secdiv ul li:hover{
    background:darkred;
    transition:all 0.40s;
}
#secdiv h1{
    width:100px;
    float:left;
    cursor:pointer;
    margin-left:29px;
}

body{
font-family:"Oxygen",sans-serif;
font-size:16px;
line-height:1.5;
}
.content{
position:relative;
z-index:2;
margin:13% auto;
width:50%;
text-align:center;

}
.heading{
     font-family: "Times New Roman", Georgia, Serif;
margin-bottom:24px;
color:RED;
font-size:44px;

}
.para{
margin-bottom:24px;
color:orange;
font-size:44px;
 font-family: "Times New Roman", Georgia, Serif;
}
.btn{
padding:12px 28px;
color:#ff3c64;
font-size:22px;
text-decoration:none;
border:4px solid #ff3c64;}
#wrapper {
    margin:0 auto;
    width:100%;
    text-align:center;
    position:absolute;
    top:500px;
}
#googleimg{
    border-radius:50%;
    width:150px;
    height:150px;
    background-image:url("googleimage.jpg");
  background-size:cover;
       box-shadow: 10px 10px 5px #888888;
}
#wrapper2 {
    margin:0 auto;
    width:100%;
    text-align:center;
    position:absolute;
    top:500px;
    left:200px;
}
#railwayimg{
    border-radius:50%;
    width:150px;
    height:150px;
    background-image:url("railwayimg.jpg");
  background-size:cover;
       box-shadow: 10px 10px 5px #888888;
}
#wrapper3 {
    margin:0 auto;
    width:100%;
    text-align:center;
    position:absolute;
    top:512px;
    left:400px;
}
#govind{
    border-radius:50%;
    width:150px;
    height:150px;
    background-image:url("govind.png");
  background-size:cover;
       box-shadow: 10px 10px 5px #888888;
}
#contactus
{
 font-family:"Times New Roman",Times,serif;
 font-size:35px;
}
.container
{
    text-align:center;
    color:#2c2c2c;
    text-decoration:none;
    outline:thick ridge red;
    height:300px;
    width:300px;
    right:400px;
    margin:auto;
    background-color:#ffd6cc;

}
#mySidenav a {
    position: absolute; /* Position them relative to the browser window */
    left: -80px; /* Position them outside of the screen */
    transition: 0.3s; /* Add transition on hover */
    padding: 15px; /* 15px padding */
    width: 100px; /* Set a specific width */
    text-decoration: none; /* Remove underline */
    font-size: 20px; /* Increase font size */
    color: white; /* White text color */
    border-radius: 0 5px 5px 0; /* Rounded corners on the top right and bottom right side */
    font-family: "Times New Roman", Times, serif;
}

#mySidenav a:hover {
    left:0; /* On mouse-over, make the elements appear as they should */
}

/* The about link: 20px from the top with a green background */
#about {
    top: 200px;
    background-color:red ;
     font-family: "Times New Roman", Times, serif;
}

#tools{
    top:300px;
    background-color:blue; /* Blue */
     font-family: "Times New Roman", Times, serif;
}
#contact {
    top:400px;
    background-color:green /* Light Black */
}
h1{
    text-align:center;
    text-shadow:2px 2px 5px red;
    font-family: "Times New Roman", Times, serif;
}

.slider{
    width:800px;
    height:400px;
    background:url("sliderimage1.PNG");
    margin:100px auto;
    animation:slide 5s infinite;
    outline:solid;

}
@keyframes slide{
    25%{
        background:url("sliderimage1.png");
    }

    25%{
        background:url("sliderimage11.jpg");
    }
}

<!DOCTYPE html>

    <title>Test site</title>

    <link rel="stylesheet" type="text/css" href="style.css">
   <link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="mobilecss.css" />
   <link rel="stylesheet" type="text/css" href="slidercss.css">

HOME

This is a prototype Website the contents you will find here is owned by creaters of this website In below you can see Slider

  ABOUT
  TOOLS
  CONTACT US

Body:
Ok,first you are missing viewport tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

You don't need  this:

<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="mobilecss.css" />

Write media queries inside css file.


问:
Firebase Realtime Database read all existing data
It seems that Firebase Realtime Database notifies me if a new item is added or deleted, etc. That is great, but how to get all existing items of which I was previously notified?

For example, suppose that my app is listing the items in the database. I started my app for the first time. And then "item 1" and "item 2" were created. Firebase notified me of "item 1" and "item 2", so I added them to the list of my app.

Now, my app was closed and restarted. If a new item "item 3" is created, I will be notified of that, but how can I retrieve "item 1" and "item 2" again? In short, I want to display all items, again.

I have searched for examples, but all examples I could find were getting events, not "reading all".

PS: I think you two for spending your time for explanation. I misunderstood how Firebase Realtime Database works; I thought I would get notified for new items only once across sessions. It seems that I could be notified of only new items by addChildEventListener, and I can access the entire items with addValueEventListener and its dataSnapshot.

答:
To get all the item that exist in a node at a moment, even if were added before you have restarted your app or after that, you need to attach a listener on that node. Everything in Firebase is about listeners. This means that you are listening for every change that is made in your database at that particular location. So in every moment you can have dataSnapshot of a particular node from your database. So assume we have a database that looks like this:

```<code>Firebase-root
    |
    --- users
          |
          --- userId1
          |     |
          |     --- //details
          |
          --- userId2
                |
                --- //details
</code>```

If we attach a listener on users node, we can create a List which can contain all the users like this:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String userId = ds.getKey();
            list.add(userId);
            Log.d("TAG", userId);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>userId1
userId2
</code>```

So using this code, you can get all the users, even if they been added before you restared the app of after. You get the data in real time.

Body:
To get all the item that exist in a node at a moment, even if were added before you have restarted your app or after that, you need to attach a listener on that node. Everything in Firebase is about listeners. This means that you are listening for every change that is made in your database at that particular location. So in every moment you can have dataSnapshot of a particular node from your database. So assume we have a database that looks like this:

Firebase-root
    |
    --- users
          |
          --- userId1
          |     |
          |     --- //details
          |
          --- userId2
                |
                --- //details

If we attach a listener on users node, we can create a List which can contain all the users like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String userId = ds.getKey();
            list.add(userId);
            Log.d("TAG", userId);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

userId1
userId2

So using this code, you can get all the users, even if they been added before you restared the app of after. You get the data in real time.


问:
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"?
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)?

Please explain the rationale, if possible.

I read somewhere that != operator is better than comparison operators. also pre-increment operator is better than post-increment operator, since it doesn't require any temporary variable to store the intermediate value.

Is there any better form of for loop than these two?

p.s: I use the former one as suggested by one of the sources, which i don't remember now.

答:
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)?

the 2nd one since its a Bolian Operator, then this for(int i = _ ; i <= __ or etc ; i++ increment )? --> it's widely used as now a days even when are beginners  in programming.


问:
Oracle Grants life cycle
I have created a view or procedure in Oracle database and have given some grants to it.

If I again compiled the created view and procedure will the grants given to it will get revoked?

What is the life cycle of Grants?

答: Grant exists until database object would be dropped. You can compile them, you can replace them ("create or replace" statement) - grant will survive.</p>

Title: Oracle Grants life cycle


答:
The result you get will depend on your query. If you write a query to retrieve all the items, you will get all the elements for a node like in the first block of the following example:</p>

```<code>//Prefetch all the existing items for the node using a SingleValueEventListener
FirebaseDatabase.getInstance().getReference(key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //Fetches all the existing items
            Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
            for (DataSnapshot aSnapshotIterable : snapshotIterable) {
               aSnapshotIterable.getValue(Item.class);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

//Once you fetch all the existing items,add a listener on the last added item for realtime updates
FirebaseDatabase.getInstance().getReference(key).orderByKey().limitToLast(1).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
                Iterator<DataSnapshot> snapshotIterator = snapshotIterable.iterator();
                //Fetches the last added item
                if (snapshotIterator.hasNext()) {
                    Item value = snapshotIterator.next().getValue(Item.class);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

Title: Firebase Realtime Database read all existing data

Body:
It seems that Firebase Realtime Database notifies me if a new item is added or deleted, etc. That is great, but how to get all existing items of which I was previously notified?

For example, suppose that my app is listing the items in the database. I started my app for the first time. And then "item 1" and "item 2" were created. Firebase notified me of "item 1" and "item 2", so I added them to the list of my app.

Now, my app was closed and restarted. If a new item "item 3" is created, I will be notified of that, but how can I retrieve "item 1" and "item 2" again? In short, I want to display all items, again.

I have searched for examples, but all examples I could find were getting events, not "reading all".

PS: I think you two for spending your time for explanation. I misunderstood how Firebase Realtime Database works; I thought I would get notified for new items only once across sessions. It seems that I could be notified of only new items by addChildEventListener, and I can access the entire items with addValueEventListener and its dataSnapshot.

Body:
The result you get will depend on your query. If you write a query to retrieve all the items, you will get all the elements for a node like in the first block of the following example:

//Prefetch all the existing items for the node using a SingleValueEventListener
FirebaseDatabase.getInstance().getReference(key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //Fetches all the existing items
            Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
            for (DataSnapshot aSnapshotIterable : snapshotIterable) {
               aSnapshotIterable.getValue(Item.class);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

//Once you fetch all the existing items,add a listener on the last added item for realtime updates
FirebaseDatabase.getInstance().getReference(key).orderByKey().limitToLast(1).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
                Iterator<DataSnapshot> snapshotIterator = snapshotIterable.iterator();
                //Fetches the last added item
                if (snapshotIterator.hasNext()) {
                    Item value = snapshotIterator.next().getValue(Item.class);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


问:
Azure - Multiple Deployments per Web App?
I do want to build a very simple Single Page Application. There will be a backend (NodeJS-App) and a Frontend (AngularJS).

What is the best approach to deploy this in an Azure Web App? Can I host both in the same App or should I create two separate apps? One hosting the backend and another one just serving the static files of the Angular app?

Are there other (maybe better) solutions?

答:
I'll throw out two separate answers.

If you go the WebApp route, you do not need two separate WebApps. You can execute your NodeJS code and serve static Angular templates and controllers from the same WebApp.

Instead of going the WebApp route, consider using an Azure Function to host your NodeJS app. You can then serve static Angular files from Azure Blob Storage. The advantage of this approach are possibly cost and ease of scalability. This article walks you through doing so.