问:
UISearchController: searchResultsController not displaying
I am pretty new to UISearchController so pardon if this is a silly question.

I tried following this question but was not able to get the results I wanted.

In my MapViewController's viewDidLoad I initialize the search controller like so:

searchController = UISearchController(searchResultsController: customViewController)

where customViewController is a subclass UIViewController with some text labels for now (through interface builder).
(I declare it like so: let customViewController = MyCustomeViewController()

I tried to follow the above link by hiding and unhiding the searchResultsController with searchController.searchResultsController?.view.isHidden = false in the delegate methods to no luck.

The result is the same: where only the view is dimmed.

Ideally I want it to be something similar to Facebook's app where when you tap the search bar it shows a different view.

I printed the searchResultsController object in the delegate willPresentSearchController and it does indicate it as MyCustomViewController.

Am I missing something here or is this not the right approach?

答: Turns out that the controller to display needs to be a UITableViewControlleror a subclass of one. I tried a regular UIViewController with a UITableView inside it but no luck.


来源: stackexchange

问:
Can't find and scrape some Divs using Simple Html Dom (PHP)
I'm trying to scrape that table in the middle, it's the only thing that I need from this web, and also it's the only thing I can't get from there.
after few attempts, I created this little code that scrape ALL the html divs, please tell me what i'm doing wrong and what you think.
thanks!
(In the bottom: picture of the part from this page that I'm looking for)

```<code><?php
include_once("simple_html_dom.php");
$link = 'http://www.oddsportal.com/soccer/argentina/copa-argentina/colon-santa-fe-ind-rivadavia-bTD4Oj2C/?r=1#1X2;2';

$html = file_get_html($link);
$table = true;
$i = 0;

while ($table)
{
$table = $html->find("div",$i++);
echo $table;

}
?>
</code>```

the table

Thanks again :)

答:
Updated Answer

Table in the web site that you want to scrape it, puts the table there with ajax calls when the page was loaded. So; when you scrape html, there is no table in there.

You can all simulate their ajax calls but this will be harder for you. Open your network tab on Chrome and analyze all request, when you found the real request that getting the table to the page, scrape it.

Old Answer

I assume that; you scrape the table properly. After that you need a for loop to scrape each div in the table.

```<code>foreach($html->find('tr div.l a') as $element) {
   echo $element->href;
}
</code>```

You should adapt the above code to your code.

Full Code

```<code><?php
  include_once("simple_html_dom.php");
  $link = 'http://www.oddsportal.com/soccer/argentina/copa-argentina/colon-santa-fe-ind-rivadavia-bTD4Oj2C/?r=1#1X2;2';

  $html = file_get_html($link);
  foreach($html->find('tr div.l a') as $element) {
    echo $element->href;
  }
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to scrape that table in the middle, it's the only thing that I need from this web, and also it's the only thing I can't get from there.
after few attempts, I created this little code that scrape ALL the html divs, please tell me what i'm doing wrong and what you think.
thanks!
(In the bottom: picture of the part from this page that I'm looking for)

<?php
include_once("simple_html_dom.php");
$link = 'http://www.oddsportal.com/soccer/argentina/copa-argentina/colon-santa-fe-ind-rivadavia-bTD4Oj2C/?r=1#1X2;2';

$html = file_get_html($link);
$table = true;
$i = 0;

while ($table)
{
$table = $html->find("div",$i++);
echo $table;

}
?>

the table

Thanks again :)

Body:
Updated Answer

Table in the web site that you want to scrape it, puts the table there with ajax calls when the page was loaded. So; when you scrape html, there is no table in there.

You can all simulate their ajax calls but this will be harder for you. Open your network tab on Chrome and analyze all request, when you found the real request that getting the table to the page, scrape it.

Old Answer

I assume that; you scrape the table properly. After that you need a for loop to scrape each div in the table.

foreach($html->find('tr div.l a') as $element) {
   echo $element->href;
}

You should adapt the above code to your code.

Full Code

<?php
  include_once("simple_html_dom.php");
  $link = 'http://www.oddsportal.com/soccer/argentina/copa-argentina/colon-santa-fe-ind-rivadavia-bTD4Oj2C/?r=1#1X2;2';

  $html = file_get_html($link);
  foreach($html->find('tr div.l a') as $element) {
    echo $element->href;
  }
?>


问:
Javascript Regex 1-10
I am trying to get a regex that can get from 1-10 and i have been having trouble

I have tried :

```<code>/^[1-9]|10$/ //this will matches out 1-9 but not 10
/^10|[1-9]$/ //this will matches 10 but no 1-9 digits
</code>```

I feel weird because i have seen this question before and people said either of these expression should work. Any ideas of another way to get any # from 1-10?

答:
Assuming you want to match a string containing a number 1–10 and nothing else, you were close with /^[1-9]|10$/. The problem here is that the alternation | includes the ^ and $ characters, i.e. this expression will match either ^[1-9] (any string beginning with 1–9) or10$` (any string ending with 10). Parentheses solve this neatly:

```<code>/^([1-9]|10)$/
</code>```

See it in action below:

const regex = /^([1-9]|10)$/gm; // `gm` flags for demo only; read below
const str = `1
2
3
4
foo
5
6
7
8
9
10`;

let m;
while (m = regex.exec(str)) {
  console.log('Found match:', m[0]);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%}</code>```

The snippet uses the g and m flags to find all of the matches across multiple lines. m makes ^ and $ match the beginning and end of each line rather than the beginning and end of the string. For your use case you probably don't want either flag.

Title: Javascript Regex 1-10

Body:
I am trying to get a regex that can get from 1-10 and i have been having trouble

I have tried :

/^[1-9]|10$/ //this will matches out 1-9 but not 10
/^10|[1-9]$/ //this will matches 10 but no 1-9 digits

I feel weird because i have seen this question before and people said either of these expression should work. Any ideas of another way to get any # from 1-10?

Body:
Assuming you want to match a string containing a number 1–10 and nothing else, you were close with /^[1-9]|10$/. The problem here is that the alternation | includes the ^ and $ characters, i.e. this expression will match either ^[1-9] (any string beginning with 1–9) or10$` (any string ending with 10). Parentheses solve this neatly:

/^([1-9]|10)$/

See it in action below:

const regex = /^([1-9]|10)$/gm; // `gm` flags for demo only; read below
const str = `1
2
3
4
foo
5
6
7
8
9
10`;

let m;
while (m = regex.exec(str)) {
  console.log('Found match:', m[0]);
}

.as-console-wrapper{min-height:100%}

The snippet uses the g and m flags to find all of the matches across multiple lines. m makes ^ and $ match the beginning and end of each line rather than the beginning and end of the string. For your use case you probably don't want either flag.


问:
How could I replace a form with text when form is submitted?
I want my form to disappear when someone submits it (and it passes all of the error checking)
and text replaces where it was and says something like "Thank you a confirmation email has been sent"

What are some ways I would be able to do this?

I have the form working and the error checks and everything working, all I would need to do is make it disappear when the user clicks submit..

I am using php, Thanks!

答:
you will need to use some Javascript to :

1.) submit the form via AJAX,

2.) change the content of the element holding the form

```<code><div id='myForm_container'>
    <form id='myForm'>
         <input id="name" name="name">
         <input id="email" name="email">
        <input type=submit id='mySubmit'>
    </form>
</div>

<script>
    $('#mySubmit').click(function(){
        //do your validation and if passes:
        $.post("form_submit.php", { name: $('#name').val(), email: $('#email').val()},
        function(data){
            $('#myForm_container').html(data);
        });
    });
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
you will need to use some Javascript to :

1.) submit the form via AJAX,

2.) change the content of the element holding the form

<div id='myForm_container'>
    <form id='myForm'>
         <input id="name" name="name">
         <input id="email" name="email">
        <input type=submit id='mySubmit'>
    </form>
</div>

<script>
    $('#mySubmit').click(function(){
        //do your validation and if passes:
        $.post("form_submit.php", { name: $('#name').val(), email: $('#email').val()},
        function(data){
            $('#myForm_container').html(data);
        });
    });
</script>


问:
Deleting content of every string after first empty space
How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?</p>

答:
A simple way to do it can be:</p>

```<code>System.out.println("Hello world!".split(" ")[0]);
</code>```

Body:
A simple way to do it can be:

System.out.println("Hello world!".split(" ")[0]);


问:
Update dataframe according to another dataframe based on certain conditions
I have two dataframes df1 and df2. Df1 has columns A,B,C,D,E,F and df2 A,B,J,D,E,K. I want to update the second dataframe with the rows of the first but only when two first columns have the same value in both dataframes. For each row that the following two conditions are true:

df1.A = df2.A

df1.B = df2.B

then update accordingly:

```<code>df2.D = df1.D
df2.E = df1.E
</code>```

My dataframes have different number of rows.

When I tried this code I get a TypeError :cannot do positional indexing with these indexers of type 'str'.

```<code>for a in df1:
    for t in df2:
        if df1.iloc[a]['A'] == df2.iloc[t]['A'] and df1.iloc[a]['B'] == df2.iloc[t]['B']:
            df2.iloc[t]['D'] = df1.iloc[a]['D']
            df2.iloc[t]['E'] = df1.iloc[a]['E']
</code>```

答:
The Question:

You'd be better served merging the dataframes than doing nested iteration.

```<code>df2 = df2.merge(df1[['A', 'B', 'D', 'E']], on=['A', 'B'], how='left', suffixes=['_old', ''])
df2['D'] = df2['D'].fillna(df2['D_old'])
df2['E'] = df2['E'].fillna(df2['E_old'])
del df2['D_old']
del df2['E_old']
</code>```

The first row attaches columns to df2 with values for columns D and E from corresponding rows of df1, and renames the old columns.
The next two lines fill in the rows for which df1 had no matching row, and the next two delete the initial, now outdated versions of the columns.

The Error:

Your TypeError happened because for a in df1: iterates over the columns of a dataframe, which are strings here, while .iloc only takes integers. Additionally, though you didn't get to this point, to set a value you'd need both index and column contained within the brackets.

So if you did need to set values by row, you'd want something more like

```<code>for a in df1.iterrows():
    for t in df2.iterrows():
        if df1.loc[a, 'A'] == ...
</code>```

Though I'd strongly caution against doing that. If you find yourself thinking about it, there's probably either a much faster, less painful way to do it in pandas, or you're better off using another tool less focused on tabular data.

Body:
I have two dataframes df1 and df2. Df1 has columns A,B,C,D,E,F and df2 A,B,J,D,E,K. I want to update the second dataframe with the rows of the first but only when two first columns have the same value in both dataframes. For each row that the following two conditions are true:

df1.A = df2.A

df1.B = df2.B

then update accordingly:

df2.D = df1.D
df2.E = df1.E

My dataframes have different number of rows.

When I tried this code I get a TypeError :cannot do positional indexing with these indexers of type 'str'.

for a in df1:
    for t in df2:
        if df1.iloc[a]['A'] == df2.iloc[t]['A'] and df1.iloc[a]['B'] == df2.iloc[t]['B']:
            df2.iloc[t]['D'] = df1.iloc[a]['D']
            df2.iloc[t]['E'] = df1.iloc[a]['E']

Body:
The Question:

You'd be better served merging the dataframes than doing nested iteration.

df2 = df2.merge(df1[['A', 'B', 'D', 'E']], on=['A', 'B'], how='left', suffixes=['_old', ''])
df2['D'] = df2['D'].fillna(df2['D_old'])
df2['E'] = df2['E'].fillna(df2['E_old'])
del df2['D_old']
del df2['E_old']

The first row attaches columns to df2 with values for columns D and E from corresponding rows of df1, and renames the old columns.
The next two lines fill in the rows for which df1 had no matching row, and the next two delete the initial, now outdated versions of the columns.

The Error:

Your TypeError happened because for a in df1: iterates over the columns of a dataframe, which are strings here, while .iloc only takes integers. Additionally, though you didn't get to this point, to set a value you'd need both index and column contained within the brackets.

So if you did need to set values by row, you'd want something more like

for a in df1.iterrows():
    for t in df2.iterrows():
        if df1.loc[a, 'A'] == ...

Though I'd strongly caution against doing that. If you find yourself thinking about it, there's probably either a much faster, less painful way to do it in pandas, or you're better off using another tool less focused on tabular data.


问:
Insert DLookup values into table
So I have two tables, tblMaster and Software.

Is there a way in MS Access vba to do DLookup on tblMaster.Title to find the Software Titles in Software and insert the values in tblMaster.Software Title?

tblMaster

```<code>|ID|Title                           |type|state|Software Title|
---------------------------------------------------------------
|1 |Adobe Reader                    |A   |Close|
|2 |Apache HTTP Server              |A   |Close|
|3 |Multiple Mozilla Products       |A   |Open |
|4 |Microsoft Windows File Handling |A   |Open |
|5 |Microsoft Windows Client Server |A   |Open |
|6 |HP Printer                      |A   |Open |
|7 |Adobe Acrobat                   |A   |Close|
</code>```

Software

```<code>|SWID|Software Title    |location|
----------------------------------
|1   |Adobe             |1|
|2   |Apache            |1|
|3   |Mozilla           |1|
|4   |Microsoft Windows |2|
|5   |HP                |3|
</code>```

I would like tblMaster to look like this after the DLookup:

tblMaster

```<code>|ID|Title                           |type|state|SWID|Software Title|
---------------------------------------------------------------
|1 |Adobe Reader                    |A   |Close|1   |Adobe
|2 |Apache HTTP Server              |A   |Close|2   |Apache
|3 |Multiple Mozilla Products       |A   |Open |3   |Mozilla
|4 |Microsoft Windows File Handling |A   |Open |4   |Microsoft Windows
|5 |Microsoft Windows Client Server |A   |Open |4   |Microsoft Windows
|6 |HP Printer                      |A   |Open |5   |HP
|7 |Adobe Acrobat                   |A   |Close|1   |Adobe
</code>```

答:
A query might get what you want. Should probably just save the software ID into tblMaster then build queries that join the two tables to pull the title.

UPDATE tblMaster Set SoftwareID = DLookUp("SWID","Software","InStr('" & [Title] & "', [Software Title])>0");

Title: Insert DLookup values into table

Body:
So I have two tables, tblMaster and Software.

Is there a way in MS Access vba to do DLookup on tblMaster.Title to find the Software Titles in Software and insert the values in tblMaster.Software Title?

tblMaster

|ID|Title                           |type|state|Software Title|
---------------------------------------------------------------
|1 |Adobe Reader                    |A   |Close|
|2 |Apache HTTP Server              |A   |Close|
|3 |Multiple Mozilla Products       |A   |Open |
|4 |Microsoft Windows File Handling |A   |Open |
|5 |Microsoft Windows Client Server |A   |Open |
|6 |HP Printer                      |A   |Open |
|7 |Adobe Acrobat                   |A   |Close|

Software

|SWID|Software Title    |location|
----------------------------------
|1   |Adobe             |1|
|2   |Apache            |1|
|3   |Mozilla           |1|
|4   |Microsoft Windows |2|
|5   |HP                |3|

I would like tblMaster to look like this after the DLookup:

tblMaster

|ID|Title                           |type|state|SWID|Software Title|
---------------------------------------------------------------
|1 |Adobe Reader                    |A   |Close|1   |Adobe
|2 |Apache HTTP Server              |A   |Close|2   |Apache
|3 |Multiple Mozilla Products       |A   |Open |3   |Mozilla
|4 |Microsoft Windows File Handling |A   |Open |4   |Microsoft Windows
|5 |Microsoft Windows Client Server |A   |Open |4   |Microsoft Windows
|6 |HP Printer                      |A   |Open |5   |HP
|7 |Adobe Acrobat                   |A   |Close|1   |Adobe


问:
Generic type conversion
I'm having some serious design problems due to generics issues. Perhaps someone has some suggestions.

EDIT: So, I know this is not usually done, but I've completely changed my example code, because I've realized that the original pseudo-code did not really explain my problem. The following code much more closely resembles the real example I am dealing with. I hope that my problem will be clearer from it. I apologize ahead that it is a bit lengthy, but from my experience, problems with generics usually show up when you try to build a more complex structure. So:

```<code>class Program
    {
        static void Main(string[] args)
        {
            IConnector<IService> connector = ConnectorBuilderFactory.NewBuilder<IService>("someEndpoint").MakeReliable().GetConnector();
            connector.Connect();
        }
    }

    public interface IService : IConnectionMaintainable
    {
        void DoSomething();
    }

    public interface IConnectionMaintainable
    {
        DateTime GetServerTime();
    }

    public interface IConnector<T>
    {
        T Channel { get; }
        void Connect();
        void Disconnect();
    }

    public interface IConnectorBuilder<T>
    {
        IConnector<T> GetConnector();
        IConnectorBuilder<T> MakeReliable();
        // ...more connector-configuration methods
    }

    public class ChannelWatchDog<T> where T : IConnectionMaintainable
    {
        private IConnector<T> connector;

        public ChannelWatchDog(IConnector<T> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class Connector<T> : IConnector<T>
    {
        private T channel;

        public Connector(string endpoint)
        {
            // ...build channel
        }

        public T Channel
        {
            get { return channel; }
        }

        public void Connect()
        {
            // ...connect to server
        }

        public void Disconnect()
        {
            // ...disconnect from server
        }
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            // ChannelWatchDog<T> watchDog = new ChannelWatchDog<T>(connector);

            return connector;
        }

        public IConnectorBuilder<T> MakeReliable()
        {
            // save various parameters required to build the ChannelWatchDog
            return this;
        }
    }

    public static class ConnectorBuilderFactory
    {
        public static IConnectorBuilder<T> NewBuilder<T>(string endpoint)
        {
            return new ConnectorBuilder<T>(endpoint);
        }
    }
</code>```

So, firstly, if you find the GetConnector method in the ConnectorBuilder class, you will see the commented line of code, which does not compile if uncommented. This line is the essence of my problem. The problem might be obvious from the code, but I will try to explain it anyway in case it is not:

I have an internal class (ChannelWatchDog) that needs an IConnector. But not just any IConnector, an IConnector, because other than the non-generic IConnector methods, it also needs the GetServerTime method from the IConnectionMaintainable interface.

To simplify construction of connectors, I hoped to implement a builder using the Expression Builder pattern (the IConnectionBuilder interface). However, I want to be able to construct any IConnector, not just IConnector<IConnectionMaintainable>. Therefore, I cannot constrain T in IConnectorBuilder in the same way as I constrain it for the ChannelWatchDog. Lacking this constraint, I have no way to build it when GetConnector is called. Adding the constraint to the MakeReliable method does not help.

So, essentially the reason I posted this question was that I wanted to do something that is apparently impossible. I wanted the ChannelWatchDog and ConnectorBuilder class to look something like this:

```<code>public class ChannelWatchDog
    {
        private IConnector<IConnectionMaintainable> connector;

        public ChannelWatchDog(IConnector<IConnectionMaintainable> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

            return connector;
        }

        public IConnectorBuilder<TReliable> MakeReliable<TReliable>() where TReliable : T, IConnectionMaintainable
        {
            // save various parameters required to build the ChannelWatchDog
            return (IConnectorBuilder<TReliable>)this;
        }
    }
</code>```

But the cast to IConnector fails at runtime.

So that was much more lengthy than I had originally intended. If you've gotten this far in reading then you already have my thanks :)
Any ideas are welcome, including restructuring the code.

BTW, Having not found a solution to this myself, I created different ConnectorBuilders (in this case, a ReliableConnectorBuilder) and different factory methods in the factory. But I don't like this solution much.

EDIT: Just to clarify and reiterate: I cannot constrain the IConnector nor the ConnectionBuilder because these need to support cases in which the IConnectionMaintainable interface is not implemented.

答: You should make the generic parameter T in the class ConnectorBuilder implement the interface IConnectionMaintainable. The reason for this is that it is needed for the generic type of ChannelWatchDog. The generic T is not strict enough for the generic type parameter of ChannelWatchDog.</p>

Title: Generic type conversion

Body:
I'm having some serious design problems due to generics issues. Perhaps someone has some suggestions.

EDIT: So, I know this is not usually done, but I've completely changed my example code, because I've realized that the original pseudo-code did not really explain my problem. The following code much more closely resembles the real example I am dealing with. I hope that my problem will be clearer from it. I apologize ahead that it is a bit lengthy, but from my experience, problems with generics usually show up when you try to build a more complex structure. So:

class Program
    {
        static void Main(string[] args)
        {
            IConnector<IService> connector = ConnectorBuilderFactory.NewBuilder<IService>("someEndpoint").MakeReliable().GetConnector();
            connector.Connect();
        }
    }

    public interface IService : IConnectionMaintainable
    {
        void DoSomething();
    }

    public interface IConnectionMaintainable
    {
        DateTime GetServerTime();
    }

    public interface IConnector<T>
    {
        T Channel { get; }
        void Connect();
        void Disconnect();
    }

    public interface IConnectorBuilder<T>
    {
        IConnector<T> GetConnector();
        IConnectorBuilder<T> MakeReliable();
        // ...more connector-configuration methods
    }

    public class ChannelWatchDog<T> where T : IConnectionMaintainable
    {
        private IConnector<T> connector;

        public ChannelWatchDog(IConnector<T> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class Connector<T> : IConnector<T>
    {
        private T channel;

        public Connector(string endpoint)
        {
            // ...build channel
        }

        public T Channel
        {
            get { return channel; }
        }

        public void Connect()
        {
            // ...connect to server
        }

        public void Disconnect()
        {
            // ...disconnect from server
        }
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            // ChannelWatchDog<T> watchDog = new ChannelWatchDog<T>(connector);

            return connector;
        }

        public IConnectorBuilder<T> MakeReliable()
        {
            // save various parameters required to build the ChannelWatchDog
            return this;
        }
    }

    public static class ConnectorBuilderFactory
    {
        public static IConnectorBuilder<T> NewBuilder<T>(string endpoint)
        {
            return new ConnectorBuilder<T>(endpoint);
        }
    }

So, firstly, if you find the GetConnector method in the ConnectorBuilder class, you will see the commented line of code, which does not compile if uncommented. This line is the essence of my problem. The problem might be obvious from the code, but I will try to explain it anyway in case it is not:

I have an internal class (ChannelWatchDog) that needs an IConnector. But not just any IConnector, an IConnector, because other than the non-generic IConnector methods, it also needs the GetServerTime method from the IConnectionMaintainable interface.

To simplify construction of connectors, I hoped to implement a builder using the Expression Builder pattern (the IConnectionBuilder interface). However, I want to be able to construct any IConnector, not just IConnector<IConnectionMaintainable>. Therefore, I cannot constrain T in IConnectorBuilder in the same way as I constrain it for the ChannelWatchDog. Lacking this constraint, I have no way to build it when GetConnector is called. Adding the constraint to the MakeReliable method does not help.

So, essentially the reason I posted this question was that I wanted to do something that is apparently impossible. I wanted the ChannelWatchDog and ConnectorBuilder class to look something like this:

public class ChannelWatchDog
    {
        private IConnector<IConnectionMaintainable> connector;

        public ChannelWatchDog(IConnector<IConnectionMaintainable> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

            return connector;
        }

        public IConnectorBuilder<TReliable> MakeReliable<TReliable>() where TReliable : T, IConnectionMaintainable
        {
            // save various parameters required to build the ChannelWatchDog
            return (IConnectorBuilder<TReliable>)this;
        }
    }

But the cast to IConnector fails at runtime.

So that was much more lengthy than I had originally intended. If you've gotten this far in reading then you already have my thanks :)
Any ideas are welcome, including restructuring the code.

BTW, Having not found a solution to this myself, I created different ConnectorBuilders (in this case, a ReliableConnectorBuilder) and different factory methods in the factory. But I don't like this solution much.

EDIT: Just to clarify and reiterate: I cannot constrain the IConnector nor the ConnectionBuilder because these need to support cases in which the IConnectionMaintainable interface is not implemented.


问:
Why shebang `env <executable>` instead of `executable`, even when there is no need to pre-set environment variables?
Why it is recommended to use /usr/bin/env python as opposed to /usr/bin/python.
This was inspired from reading the responses here:
What do I use on linux to make a python program executable

I think both would do exactly the same thing, but the answer that mentions both equally has 2 votes, rather than 88 votes for the answer that says to use env. People seem to really agree with using env, but don't explain why. Does env help you find any executable named "python", rather than just the one in a specific path which the user could have customized?

I'm really interested to know the various advantages and use cases for using env, and man env didn't explain it.  man env only says that you can use env to set environment variables before running, NAME=VALUE, but we aren't doing that in the linked example.

I feel the community clearly is recommending to use env, but my own research has not hinted at a reason, so if you have ideas why it's good or good style to do so, please answer.

答:
Using #!/usr/bin/env python ensures that the first Python interpreter in the currently-defined PATH is used, honoring any user overrides (which, for Python, includes virtualenvs and the like).

This is particularly important for environments such as MacOS, where OS-vendor packages are often out-of-date (for instance, /bin/bash is 3.2 -- a release series from 2006 -- whereas if the user has MacPorts or Homebrew, /opt/local/bin/bash or /usr/local/bin/bash may be a modern 4.x; thus, #!/usr/bin/env bash will gain the benefit of any updated bash interpreter a user has installed, whether system-wide or under their home directory, so long as the location of that interpreter is present in their PATH at runtime).


问:
How to read a file in javascript
the way how I wrote the path is it right?</p>

```<code> <script>
     fs = require('fs')
    fs.readFile('C:/Users/user/Desktop/qwe.txt', 'utf8', function (err,data) {
      if (err) {
        return console.log(err);
      }
      console.log(data);
    });
</script>
</code>```

答:
You can use XMLHttpRequest object for this

```<code>var fileObj;

if(window.XMLHttpRequest)
{
  fileObj = new XMLHttpRequest();
}
else{
  fileObj = new ActiveXObject("Microsoft.XMLHTTP");
}

fileObj.open("GET", "file://abc.txt", false);
fileObj.onreadystatechange = function ()
{

    if(fileObj.readyState === 4 && (fileObj.status === 200 || fileObj.status == 0))
    {
        var fileText= fileObj.responseText;
        alert(fileText);
    }
}

fileObj.send(null);
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to read a file in javascript

Body:
You can use XMLHttpRequest object for this

var fileObj;

if(window.XMLHttpRequest)
{
  fileObj = new XMLHttpRequest();
}
else{
  fileObj = new ActiveXObject("Microsoft.XMLHTTP");
}

fileObj.open("GET", "file://abc.txt", false);
fileObj.onreadystatechange = function ()
{

    if(fileObj.readyState === 4 && (fileObj.status === 200 || fileObj.status == 0))
    {
        var fileText= fileObj.responseText;
        alert(fileText);
    }
}

fileObj.send(null);


问:
Korn Shell - env, printenv, export - How to get CRLF as a delimiter
This seems simple, but I can't find anything on how to do this : I'm basically using a KSH variable to build my email body text.  In an error/exception situation I want to dump the env/printenv/export as well using '\n' as a delimiter.

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env)"
    echo -e $MESSAGE >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

So, according to the documentation on env/printenv/export, it's already using LF as a delimiter, but when I receive the email, it's just one big BLOCK of text :

```<code>Runtime:

Runtime:
</code>```

What I want is each variable on a separate line :

```<code>Runtime :
ACCESSDB=[Sybase-Database]
ACCESSSRV=[Sybase-Server]
...etc...
</code>```

Is there anyway to force a '\n' in place of the LF currently being used?

UPDATE : I'm using sed -s 's/$/\r\n/g' and it's formatting the env output, but now the entire email body text gets sent as an attachment :

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    env | sort | sed 's/$/\r\n/g' > ${TEMPFILES}/env.txt
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(cat ${TEMPFILES}/env.txt)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

Any ideas?  I'm thinking it's some kinda mail setting on max email size, but I'm a Java programmer more than a shell scripter...

CLOSE SOLUTION : Turns out the \r\n was causing the attachment issue [https://access.redhat.com/solutions/1136493].  So I used sed -s 's/$/\n/g' and this is pretty close to what I wanted except the env is output using double lines :

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort | sed 's/$/\n/g')"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

Produces output :

```<code>Runtime:
ACCESSDB=[Sybase-Database]

ACCESSSRV=[Sybase-server]

ARCHIVEDB=[Sybase-Database]

ASBIN=[Directory-Path]
</code>```

FINAL SOLUTION : Implemented markp's fix and then just took out my sed -s stuff and it works correctly :

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

tia,  adym

答:
As @markp correctly observes, your use of

```<code>echo $MESSAGE >>$MAILFILE1
</code>```

will substitute the string $MESSAGE as several white space separated arguments to echo, and echo will simply put a space between arguments. This is similar to typing

```<code>$ echo a     b               c
a b c
</code>```

I in your place would do it thus

```<code> echo "$MESSAGE"                         >>$MAILFILE1
 echo "Batch Process:\t $BATCHPROCESS"   >>$MAILFILE1
 echo "Environment: ...."                >>$MAKEFILE1
</code>```

Or with an inline document:

```<code>   cat <<FINE >>$MAKEFILE1
$MESSAGE
Batch Process:      $BATCHPROCESS
Environment: ....
....
FINE
</code>```

Body:
This seems simple, but I can't find anything on how to do this : I'm basically using a KSH variable to build my email body text.  In an error/exception situation I want to dump the env/printenv/export as well using '\n' as a delimiter.

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env)"
    echo -e $MESSAGE >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

So, according to the documentation on env/printenv/export, it's already using LF as a delimiter, but when I receive the email, it's just one big BLOCK of text :

Runtime:

Runtime:

What I want is each variable on a separate line :

Runtime :
ACCESSDB=[Sybase-Database]
ACCESSSRV=[Sybase-Server]
...etc...

Is there anyway to force a '\n' in place of the LF currently being used?

UPDATE : I'm using sed -s 's/$/\r\n/g' and it's formatting the env output, but now the entire email body text gets sent as an attachment :

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    env | sort | sed 's/$/\r\n/g' > ${TEMPFILES}/env.txt
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(cat ${TEMPFILES}/env.txt)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

Any ideas?  I'm thinking it's some kinda mail setting on max email size, but I'm a Java programmer more than a shell scripter...

CLOSE SOLUTION : Turns out the \r\n was causing the attachment issue [https://access.redhat.com/solutions/1136493].  So I used sed -s 's/$/\n/g' and this is pretty close to what I wanted except the env is output using double lines :

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort | sed 's/$/\n/g')"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

Produces output :

Runtime:
ACCESSDB=[Sybase-Database]

ACCESSSRV=[Sybase-server]

ARCHIVEDB=[Sybase-Database]

ASBIN=[Directory-Path]

FINAL SOLUTION : Implemented markp's fix and then just took out my sed -s stuff and it works correctly :

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

tia,  adym

Body:
As @markp correctly observes, your use of

echo $MESSAGE >>$MAILFILE1

will substitute the string $MESSAGE as several white space separated arguments to echo, and echo will simply put a space between arguments. This is similar to typing

$ echo a     b               c
a b c

I in your place would do it thus

 echo "$MESSAGE"                         >>$MAILFILE1
 echo "Batch Process:\t $BATCHPROCESS"   >>$MAILFILE1
 echo "Environment: ...."                >>$MAKEFILE1

Or with an inline document:

   cat <<FINE >>$MAKEFILE1
$MESSAGE
Batch Process:      $BATCHPROCESS
Environment: ....
....
FINE


问:
Why does my loop use 100% CPU and never end?
I have this method:

```<code>    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }
</code>```

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

```<code>    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }
</code>```

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

答:
I would change:

```<code>while(true)
</code>```

to:

```<code>while(!sr.EOS) {

}
</code>```

It is a better way to check to end the loop.

OwnerDisplayName: Malfist

Body:
I have this method:

    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

LastEditorDisplayName: Rich B

Body:
I would change:

while(true)

to:

while(!sr.EOS) {

}

It is a better way to check to end the loop.

OwnerDisplayName: jjnguy


问:
Select multiple/random elements from an arraylist
How would I select random elements from an array list, except for one element?
Here's my arraylist:

```<code>ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");
</code>```

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

```<code> for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }
</code>```

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

答:
If you need randomization often (e.g. for randomized testing), you can add a Qala Datagen dependency and then get a random element like this:

```<code>String e = sample(provinces);
</code>```

Though you'd still need to remove extra element from the collection.

Disclaimer: I'm the author of the lib.

Body:
How would I select random elements from an array list, except for one element?
Here's my arraylist:

ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

 for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

Body:
If you need randomization often (e.g. for randomized testing), you can add a Qala Datagen dependency and then get a random element like this:

String e = sample(provinces);

Though you'd still need to remove extra element from the collection.

Disclaimer: I'm the author of the lib.


问:
One-to-One Relationship Tables not Linked
My one-to-one relationship table in MS Access is not linked in the sense that when I update one the other updates.  Is this supposed to happen?  If I manually update the one table that is linked, it contains the data from the parent table, but it's not doing it as I update the parent.  Is there a way to get this done automatically?  Or do I have to individually add each line?  (btw there is 19,000+ records so far)</p>

答:
I guess you are misunderstanding the way relationships in Access work.
I do guess also that you used the relationship manager.
What does it do? It tells Access which tables to show preferably in sub-forms and sub-tables to name just one feature, but it definitely does not synchronize the tables.

If you want to synchronize tables in a 1to1 relation, make sure that the linked fields are unique within each table (indexed), write a query to synchronize the tables (guess the query wizard has a template).
You could as well write a macro or use a form in case you want to synchronize the items individually.

In summary: you need to do the synchronisation by yourself.

On the other hand, if you really want to have the data synchronized and it is a 1to1 relation, then why split the data over two tables?

HTH, Y.


问:
python stucks when concat columns to pandas DataFrame using for loop [Segmentation fault (core dumped)]
I am trying to subtract each value of an array from the DataFrame and want to construct new DataFrame.

I tried as below but python stucks over it and hangs my PC with forceful close of spyder I get terminal error [$ Segmentation fault (core dumped)]. It runs for small loop. I want dataframe of size (20200 by 3000) as out put.
If there is any another way to perform this will be helpful. Thanks

```<code>error = np.arange(-150, 150, 0.1) ## length 3000
data = pd.DataFrame(np.arange(-20,2000,0.1)) ## length 20200
result = pd.DataFrame()

for i in error:
    x = data - i
    result = pd.concat([result, x], axis=1, ignore_index=True)
</code>```

also, when I assign np.arange array to dataframe the float values chages. I am using python 3.6 on anaconda.

答:
Don't keep concatenating at every step, its not efficient. </p>

```<code>error = np.arange(-150, 150, 0.1) ## length 3000
data = pd.DataFrame(np.arange(-20,2000,0.1)) ## length 20200
result = pd.DataFrame()
result_list = []

for i in error:
    x = data - i
    result_list.append(x)

result = pd.concat(result_list, axis=1, ignore_index=True)
</code>```

Body:
I am trying to subtract each value of an array from the DataFrame and want to construct new DataFrame.

I tried as below but python stucks over it and hangs my PC with forceful close of spyder I get terminal error [$ Segmentation fault (core dumped)]. It runs for small loop. I want dataframe of size (20200 by 3000) as out put.
If there is any another way to perform this will be helpful. Thanks

error = np.arange(-150, 150, 0.1) ## length 3000
data = pd.DataFrame(np.arange(-20,2000,0.1)) ## length 20200
result = pd.DataFrame()

for i in error:
    x = data - i
    result = pd.concat([result, x], axis=1, ignore_index=True)

also, when I assign np.arange array to dataframe the float values chages. I am using python 3.6 on anaconda.

Body:
Don't keep concatenating at every step, its not efficient.

error = np.arange(-150, 150, 0.1) ## length 3000
data = pd.DataFrame(np.arange(-20,2000,0.1)) ## length 20200
result = pd.DataFrame()
result_list = []

for i in error:
    x = data - i
    result_list.append(x)

result = pd.concat(result_list, axis=1, ignore_index=True)


问:
How do I read (i.e. understand) this Java array?
```<code>String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};
</code>```

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

```<code>int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };
</code>```

答:
Building on @smarx answer:

```<code>// [][][] is an array of 2D arrays
String[][][] arr = { // begin declaration of arr
    // first 2D array
    {
        {"[0][0][0]", "[0][0][1]", "[0][0][2]"},
        {"[0][1][0]", "[0][1][1]", null, "[0][1][3]"}
    },
    // second 2D array
    {
        {"[1][0][0]", "[1][0][1]"},
        null // we should check for this when reading
    },
    // third 2D array
    {
        {"[2][0][0]", "[2][0][1]", "[2][0][2]"}
    },
    // fourth 2D array
    {
        {"[3][0][0]", "[3][0][1]"},
        {}
    },
    // fifth 2D array
    {
        {"[4][0][0]", "[4][0][1]", "[4][0][2]"},
        {"[4][1][0]", "[4][1][1]"},
        {"[4][2][0]", "[4][2][1]", "[4][2][2]"}
    }
};

// Reading the 3D array, as: [x][y][z]
for (int x = 0; x < arr.length; x++) {
    for (int y = 0; y < arr[x].length; y++) {
        // one of our 2D arrays has a null array,
        // declared in the line: {"[0][1][0]", "[0][1][1]", null, "[0][1][3]"}
        if (arr[x][y] != null) {
            for (int z = 0; z < arr[x][y].length; z++) {
                System.out.println(arr[x][y][z]);
            }
        } else {
            System.out.println("null 2D array");
        }
    }
}
</code>```

We must check for the null arrays because we are trying to access something and it doesn't exist. The null string doesn't need to be checked (for printing) because Java will already make this check when printing, see why null reference prints as "null"?

Body:
String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };

Body:
Building on @smarx answer:

// [][][] is an array of 2D arrays
String[][][] arr = { // begin declaration of arr
    // first 2D array
    {
        {"[0][0][0]", "[0][0][1]", "[0][0][2]"},
        {"[0][1][0]", "[0][1][1]", null, "[0][1][3]"}
    },
    // second 2D array
    {
        {"[1][0][0]", "[1][0][1]"},
        null // we should check for this when reading
    },
    // third 2D array
    {
        {"[2][0][0]", "[2][0][1]", "[2][0][2]"}
    },
    // fourth 2D array
    {
        {"[3][0][0]", "[3][0][1]"},
        {}
    },
    // fifth 2D array
    {
        {"[4][0][0]", "[4][0][1]", "[4][0][2]"},
        {"[4][1][0]", "[4][1][1]"},
        {"[4][2][0]", "[4][2][1]", "[4][2][2]"}
    }
};

// Reading the 3D array, as: [x][y][z]
for (int x = 0; x < arr.length; x++) {
    for (int y = 0; y < arr[x].length; y++) {
        // one of our 2D arrays has a null array,
        // declared in the line: {"[0][1][0]", "[0][1][1]", null, "[0][1][3]"}
        if (arr[x][y] != null) {
            for (int z = 0; z < arr[x][y].length; z++) {
                System.out.println(arr[x][y][z]);
            }
        } else {
            System.out.println("null 2D array");
        }
    }
}

We must check for the null arrays because we are trying to access something and it doesn't exist. The null string doesn't need to be checked (for printing) because Java will already make this check when printing, see why null reference prints as "null"?


问:
Get object inside partial View
Friends,

I have a View page called "OtherDatas.cshtml" and i need to render a PartialView inside her. So, to make this, i need to check if the object inside partialView is null or not. If not, the partialView Appears. How can i get the object inside the partialView? Here is my code:

OtherDatas.cshtml:

```<code><div class="table-responsive">
        @{
            if (//I need to check the object inside ){
                Html.Partial("~/Views/Outrosdados/Search.cshtml");
            }
            else
            {
            <table class="table table-striped">
                <tr>
                    <th style="min-width:130px;">Mês</th>
                    <th style="min-width:80px;">Amortização</th>
                    <th style="min-width:100px;">Recebimento do Mês</th>
                    <th style="min-width:100px;">Atraso</th>
                    <th style="min-width:100px;">DAMP3</th>
                </tr>
            </table>
            }
        }
    </div>
</code>```

PartialView Search.html:

```<code>@model TB_DADOS_MANUAIS
@using EixoX.Html;
@using Gestão.Models;
@using System.Globalization;
@{
    List<TB_OUTROS_DADOS> od = (List<TB_OUTROS_DADOS>)ViewData["outrosDados"];
Bootstrap3Presenter<TB_OUTROS_DADOS> presenter =
Bootstrap3Presenter<TB_OUTROS_DADOS>.GetInstance("pt-BR");
ViewBag.Title = "Outros Dados";
</code>```

}

```<code><table class="table table-striped">
    <tr>
        <th style="min-width:130px;">Mês</th>
        <th style="min-width:80px;">Amortização</th>
        <th style="min-width:100px;">Recebimento do Mês</th>
        <th style="min-width:100px;">Atraso</th>
        <th style="min-width:100px;">DAMP3</th>
    </tr>
    @foreach (TB_OUTROS_DADOS dados in od){
        <tr>
<td>@dados.DT_MES_UTILIZACAO.ToString(CultureInfo.CreateSpecificCulture("pt-BR"))</td>
    <td><span class="money" />@dados.VL_AMORTIZACAO</td>
    <td><span class="money" />@dados.VL_RECEBIMENTO_MES</td>
    <td><span class="money" />@dados.VL_ATRASO</td>
    <td><span class="money" />@dados.VL_DAMP3</td>
    </tr>
    }
</table>
</code>```

I need to check inside of the 'foreach' if i have some 'TB_OUTROS_DADOS' inside the 'od' list.

Thanks!

答:
You can't do that in this way.
Pass List<> as model to you parent view or declare this list in same way like in partial view then do check, and if it is good pass it to partial view.
In this way:

```<code>@{
    List<TB_OUTROS_DADOS> od = (List<TB_OUTROS_DADOS>)ViewData["outrosDados"];
    <div class="table-responsive">
            @{
                if (od.Count > 0){
                    Html.Partial("~/Views/Outrosdados/Search.cshtml",od);
                }
                else
                {
                <table class="table table-striped">
                <tr>
                    <th style="min-width:130px;">Mês</th>
                    <th style="min-width:80px;">Amortização</th>
                    <th style="min-width:100px;">Recebimento do Mês</th>
                    <th style="min-width:100px;">Atraso</th>
                    <th style="min-width:100px;">DAMP3</th>
                </tr>
            </table>
            }
        }
    </div>
</code>```

And in PartialView

```<code>@model List<TB_OUTROS_DADOS>
@using EixoX.Html;
@using Gestão.Models;
@using System.Globalization;
@{

Bootstrap3Presenter<TB_OUTROS_DADOS> presenter =
Bootstrap3Presenter<TB_OUTROS_DADOS>.GetInstance("pt-BR");
ViewBag.Title = "Outros Dados";
}

<table class="table table-striped">
    <tr>
        <th style="min-width:130px;">Mês</th>
        <th style="min-width:80px;">Amortização</th>
        <th style="min-width:100px;">Recebimento do Mês</th>
        <th style="min-width:100px;">Atraso</th>
        <th style="min-width:100px;">DAMP3</th>
    </tr>
    @foreach (TB_OUTROS_DADOS dados in Model){
        <tr>
<td>@dados.DT_MES_UTILIZACAO.ToString(CultureInfo.CreateSpecificCulture("pt-BR"))</td>
    <td><span class="money" />@dados.VL_AMORTIZACAO</td>
    <td><span class="money" />@dados.VL_RECEBIMENTO_MES</td>
    <td><span class="money" />@dados.VL_ATRASO</td>
    <td><span class="money" />@dados.VL_DAMP3</td>
    </tr>
    }
</table>
</code>```

Title: Get object inside partial View

Body:
Friends,

I have a View page called "OtherDatas.cshtml" and i need to render a PartialView inside her. So, to make this, i need to check if the object inside partialView is null or not. If not, the partialView Appears. How can i get the object inside the partialView? Here is my code:

OtherDatas.cshtml:

        @{
            if (//I need to check the object inside ){
                Html.Partial("~/Views/Outrosdados/Search.cshtml");
            }
            else
            {

                    Mês
                    Amortização
                    Recebimento do Mês
                    Atraso
                    DAMP3

            }
        }

PartialView Search.html:

@model TB_DADOS_MANUAIS
@using EixoX.Html;
@using Gestão.Models;
@using System.Globalization;
@{
    List<TB_OUTROS_DADOS> od = (List<TB_OUTROS_DADOS>)ViewData["outrosDados"];
Bootstrap3Presenter<TB_OUTROS_DADOS> presenter =
Bootstrap3Presenter<TB_OUTROS_DADOS>.GetInstance("pt-BR");
ViewBag.Title = "Outros Dados";

}

        Mês
        Amortização
        Recebimento do Mês
        Atraso
        DAMP3

    @foreach (TB_OUTROS_DADOS dados in od){

@dados.DT_MES_UTILIZACAO.ToString(CultureInfo.CreateSpecificCulture("pt-BR"))
    @dados.VL_AMORTIZACAO
    @dados.VL_RECEBIMENTO_MES
    @dados.VL_ATRASO
    @dados.VL_DAMP3

    }

I need to check inside of the 'foreach' if i have some 'TB_OUTROS_DADOS' inside the 'od' list.

Thanks!

Body:
You can't do that in this way.
Pass List<> as model to you parent view or declare this list in same way like in partial view then do check, and if it is good pass it to partial view.
In this way:

@{
    List<TB_OUTROS_DADOS> od = (List<TB_OUTROS_DADOS>)ViewData["outrosDados"];
    <div class="table-responsive">
            @{
                if (od.Count > 0){
                    Html.Partial("~/Views/Outrosdados/Search.cshtml",od);
                }
                else
                {
                <table class="table table-striped">
                <tr>
                    <th style="min-width:130px;">Mês</th>
                    <th style="min-width:80px;">Amortização</th>
                    <th style="min-width:100px;">Recebimento do Mês</th>
                    <th style="min-width:100px;">Atraso</th>
                    <th style="min-width:100px;">DAMP3</th>
                </tr>
            </table>
            }
        }
    </div>

And in PartialView

@model List<TB_OUTROS_DADOS>
@using EixoX.Html;
@using Gestão.Models;
@using System.Globalization;
@{

Bootstrap3Presenter<TB_OUTROS_DADOS> presenter =
Bootstrap3Presenter<TB_OUTROS_DADOS>.GetInstance("pt-BR");
ViewBag.Title = "Outros Dados";
}

<table class="table table-striped">
    <tr>
        <th style="min-width:130px;">Mês</th>
        <th style="min-width:80px;">Amortização</th>
        <th style="min-width:100px;">Recebimento do Mês</th>
        <th style="min-width:100px;">Atraso</th>
        <th style="min-width:100px;">DAMP3</th>
    </tr>
    @foreach (TB_OUTROS_DADOS dados in Model){
        <tr>
<td>@dados.DT_MES_UTILIZACAO.ToString(CultureInfo.CreateSpecificCulture("pt-BR"))</td>
    <td><span class="money" />@dados.VL_AMORTIZACAO</td>
    <td><span class="money" />@dados.VL_RECEBIMENTO_MES</td>
    <td><span class="money" />@dados.VL_ATRASO</td>
    <td><span class="money" />@dados.VL_DAMP3</td>
    </tr>
    }
</table>


问:
`ExpressibleByArrayLiteral` conformed to by class and its superclass => "<superclass> is not convertible to <subclass>"
I want to be able to instantiate a subclass, here named MyLabel, which is a subclass of UILabel, using array literals. I am making use of this in my framework ViewComposer which allows for creating UIViews using an array of enums attributing the view, like this:

```<code>let label: UILabel = [.text("Hello World"), .textColor(.red)]
</code>```

In this question I have dramatically simplified the use case, instead allowing for writing:

```<code>let vanilla: UILabel = [1, 2, 3, 4]  // works!
print(vanilla.text!) // prints: "Sum: 10"
</code>```

What I want to do is use the same ExpressibleByArrayLiteral syntax, but to a subclass of UILabel, called MyLabel. However the compiler stops me when I am trying to :

```<code>let custom: MyLabel = [1, 2, 3, 4] // Compilation error: "Could not cast value of type 'UILabel' to 'MyLabel'"
</code>```

Instantiation of UILabel using array literals works, thanks to conformance to custom protocol Makeable below.

Is it somehow possible to make the compiler understand that I am referring to the array literal initializer of the subclass MyLabel and not its superclass UILabel?

The following code might not make any logical sense, but it is a minimal example, hiding away what I really want:

```<code>// This protocol has been REALLY simplified, in fact it has another name and important code.
public protocol ExpressibleByNumberArrayLiteral: ExpressibleByArrayLiteral {
    associatedtype Element
}

public protocol Makeable: ExpressibleByNumberArrayLiteral {
    // we want `init()` but we are unable to satisfy such a protocol from `UILabel`, thus we need this work around
    associatedtype SelfType
    static func make(values: [Element]) -> SelfType
}

public protocol Instantiatable: ExpressibleByNumberArrayLiteral {
    init(values: [Element])
}

// My code might have worked if it would be possible to check for _NON-conformance_ in where clause
// like this: `extension Makeable where !(Self: Instantiatable)`
extension Makeable {
    public init(arrayLiteral elements: Self.Element...) {
        self = Self.make(values: elements) as! Self
    }
}

extension Instantiatable {
    init(arrayLiteral elements: Self.Element...) {
        self.init(values: elements)
    }
}

extension UILabel: Makeable {
    public typealias SelfType = UILabel
    public typealias Element = Int

    public static func make(values: [Element]) -> SelfType {
        let label = UILabel()
        label.text = "Sum: \(values.reduce(0,+))"
        return label
    }
}

public class MyLabel: UILabel, Instantiatable {
    public typealias Element = Int
    required public init(values: [Element]) {
        super.init(frame: .zero)
        text = "Sum: \(values.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let vanilla: UILabel = [1, 2, 3, 4]
print(vanilla.text!) // prints: "Sum: 10"

let custom: MyLabel = [1, 2, 3, 4] // Compilation error: "Could not cast value of type 'UILabel' to 'MyLabel'"
</code>```

I have also tried conforming to ExpressibleByArrayLiteral protocol by extending ExpressibleByNumberArrayLiteral instead (I suspect the two solutions might be equivalent, and compile to the same code..), like this:

```<code>extension ExpressibleByNumberArrayLiteral where Self: Makeable {
    public init(arrayLiteral elements: Self.Element...) {
        self = Self.make(values: elements) as! Self
    }
}

extension ExpressibleByNumberArrayLiteral where Self: Instantiatable {
    init(arrayLiteral elements: Self.Element...) {
        self.init(values: elements)
    }
}
</code>```

But that did not work either. The same compilation error occurs.

I've written a comment in the big code block above, the compiler might have been able to determine which array literal initializer I was referring to if I would have been able to use negation in the where clause:
extension Makeable where !(Self: Instantiatable)

But AFAIK that is not possible, that code does not compile at least. Nor does extension Makeable where Self != Instantiatable.

Is what I want to do possible?

I would be okay with having to make MyLabel a final class. But that makes no difference.

Please please please say that this is possible.

答:
after going through the Apple Docs, I initially thought this was not possible. However, I did find a post here, which applied to Strings and other non-UI classes. From the post i merged the idea that you cannot apply ExpressibleByArrayLiteral to a subclass through the inheritance approach, which is probably why you get the error (which I could reproduce many times with many other approaches).

Finally, by moving the ExpressibleByArrayLiteral adoption directly onto your UILabel subclass, it seems to be working!

```<code>public class MyLabel: UILabel, ExpressibleByArrayLiteral {

    public typealias Element = Int

    public override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init(values: [Element]) {
        super.init(frame: .zero)
        text = "Sum: \(values.reduce(0,+))"
    }

    public convenience required init(arrayLiteral: Element...) {
        self.init()
        self.text = "Sum: \(arrayLiteral.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let vanilla: MyLabel = [1, 2, 3, 4]

print(vanilla.text) // prints Sum: 10
</code>```

Turns out we can't even inherit Expressibility on element type classes (Strings, Ints, etc), you still have to re-specify the initializer for it.

With some tweaking, I also applied these other methods for thought!

```<code>public class MyLabel: UILabel, ExpressibleByArrayLiteral {

    public typealias Element = Int

    private var values : [Element]?

    public var append : Element? {
        didSet {
            if let t = append {
                values?.append(t)
            }
        }
    }

    public var sum : Element {
        get {
            guard let s = values else {
                return 0
            }
            return s.reduce(0,+)
        }
    }

    public var sumString : String {
        get {
            return "\(sum)"
        }
    }

    public var label : String {
        get {
            guard let v = values, v.count > 0 else {
                return ""
            }
            return "Sum: \(sumString)"
        }
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init(values: [Element]) {
        super.init(frame: .zero)
        text = "Sum: \(values.reduce(0,+))"
    }

    public convenience required init(arrayLiteral: Element...) {
        self.init()
        self.values = arrayLiteral
        self.text = label
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let vanilla: MyLabel = [1, 2, 3, 4]

print(vanilla.label) //prints out Sum: 10 , without unwrapping ;)
</code>```

For now, I can't seem to apply the Expressibility to a protocol approach like you did. However, as workarounds go, this seems to do the trick. Guess for now we just have to apply the initializers to each subclass. Unfortunate, but still worth looking all this up!

UPDATE TO RE-AFFIRM THE ISSUE WITH THE EXTENSION APPROACH

Swift's inheritance prohibits convenience inits when it cannot guarantee that the superclass will not be altered dramatically. While your init does not change UILABEL's properties, the strict-typing for extensions just does not support the combinations of required and convenience on this type of initializer.

I'm taking this from this post, which was included in the link above btw:

Because this is a non-final class. Consider if there were a subclass
  to Stack that had its own required initializer. How would you ensure
  that init(arrayLiteral:) called it? It couldn't call it (because it
  wouldn't know that it existed). So either init(arrayLiteral:) has to
  be required (which means it needs to be part of the main declaration
  and not a extension), or Stack has to be final.

If you mark it final, this works like you expect. If you want it to be
  subclassed, just move it out of the extension and into the main body.

And if we look at the TWO errors you get, simply by trying to extend UILabel to ExpressibleByArrayLiteral directly, and not through a nested network of protocols like what you are doing:

```<code>Initializer requirement 'init(arrayLiteral:)' can only be satisfied by a 'required' initializer in the definition of non-final class 'UILabel'

'required' initializer must be declared directly in class 'UILabel' (non in an extension).
</code>```

So first. ExpressibleByArrayLiteral requires a 'required' initializer method to conform to it, to which as the compiler says: you cannot implement directly inside of extensions for the superclass you wish to customize. Unfortunately, by this logic alone.. your desired approach is flawed.

Second. The very specific initializer you want, 'init(arrayLiteral:), is for final - type classes. As in, classes which you mark with the keyword FINAL on it's declaration header, or class TYPES (Strings are one, and so are number classes). UILabel is simply non a final-class to allow subclassing and you cannot change this without hacking the language. To illustrate non-final and final, try subclass String, and you will get an error since it is not a class or protocol. which wouldn't get your through the App Store ANYWAYS. So by DESIGN, you just cannot use this method on UILabel itself via an extension.

Three. You take the custom protocol approach, and try to apply it to UILabel by extension and inheritance.. I do apologize, but Swift just does not ignore it's language structure simply because you layer some custom code between the two ends of the constrtaint. Your protocol approach, while elegant as it is, is just nesting the problem here, not addressing it. And this is because it just re-applies these initialization constraints back onto UILabel regardless of your own middleware.

Fourth. On a bit of a logical train of thought here. If you look at the Apple Docs on Expressibles inside of XCode (the code file itself), you notice that the protocols especially applies to RawRepresentable classes and types (Strings, Ints, Doubles, etc.):

For any enumeration with a string, integer, or floating-point raw
  type, the Swift compiler automatically adds RawRepresentable
  conformance. When defining your own custom enumeration, you give it a
  raw type by specifying the raw type as the first item in the
  enumeration's type inheritance list. You can also use literals to
  specify values for one or more cases.

So anything which is data representation as the root-level of the class, can adopt this by extension. You can clearly see above, when adding this protocol immediately to UILabel, you're also imposing the RawRepresentable protocol to it. Which it cannot adopt my nature, which i'm willing to bet is the source of the "MyLabel Cannot be cast to UILabel" error. UILabel is not one of these things, which is kind of why it gets this non-final class attribute: It's a UI element, which is a combination of many RawRepresentables. So it makes sense that you should not be able to directly initialize a class which is an ensemble of RawRepresentables directly, because if some mix up happens on init compiler-side and it does not alter the Raw type you're aiming for, it could just corrupt the class instance altogether and take every one down a debug nightmare.

To illustrate the RawRepresentable point I'm trying to make, here's what happens when you apply this approach to String, a RawRepresentable-conforming type:

```<code>extension String: ExpressibleByArrayLiteral {
    public typealias Element = Int

    public init(arrayLiteral elements: Element...) {
        self.init()
        self = "Sum: \(elements.reduce(0,+))"//WE GET NO ERRORS
    }

}

let t : String = [1,2,3,4]

print(t) // prints -> Sum: 10
</code>```

Whereas...

```<code>extension UILabel: ExpressibleByArrayLiteral {
    public typealias Element = Int

    public convenience required init(arrayLiteral elements: Element...) { //The compiler even keeps suggesting you add the method types here illogically without taking to account what is there.. ie: it's confused by what you're trying to do..
        self.init()
        self.text = "Sum: \(elements.reduce(0,+))" //WE GET THE ERRORS
    }

}

//CANNOT PRINT.....
</code>```

I'll even demonstrate how far the constraint goes in terms of add Expressibles on UILabel subclasses, and it's second-tier subclasses:

```<code>class Label : UILabel, ExpressibleByArrayLiteral {

    public typealias Element = Int

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    public required init(arrayLiteral elements: Element...) {
        super.init(frame: .zero)
        self.text = "Sum: \(elements.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let te : Label = [1,2,3,4]

print(te.text!) //prints:  Sum: 10

class SecondLabel : Label {

    public typealias Element = Int

    required init(arrayLiteral elements: Element...) {
        //THIS IS STILL REQUIRED... EVEN THOUGH WE DO NOT NEED TO MANUALLY ADOPT THE PROTOCOL IN THE CLASS HEADER
        super.init(frame: .zero)
        self.text = "Sum: \(elements.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }

}

let ta : SecondLabel = [1,2,3,4]

print(ta.text!) //prints:  Sum: 10
</code>```

In conclusion.
Swift is designed this way. You cannot apply this particular protocol directly onto it because UILabel is a language level superclass and the guys who come up with this stuff don't want you to have this much over-reach into UILabel. So, you simply cannot do this because this protocol cannot be applied through extensions of non-final superclasses due to the nature of UILabel and the protocol itself. They are just not compatible this way. However, you can apply this on its subclasses on a per-subclass basis. Meaning you have to re-declare the conforming initializer each time. It sucks! But it's just how it works.

I commend your approach, it seems to almost get the extensions approach down to a T.  However, there seems to be some things in how Swift is built that you just cannot circumvent. I am not the only one to affirm this conclusion (just check the links), so I would ask you to remove your downvote. You have a solution that i've given you, I've given you the references to validate my point, and i've also provided code to show you how you can remedy this constraint in the language's nature. Sometimes there just is no solution to the desired approach. And other times another approach is the only way to get around things.

Body:
I want to be able to instantiate a subclass, here named MyLabel, which is a subclass of UILabel, using array literals. I am making use of this in my framework ViewComposer which allows for creating UIViews using an array of enums attributing the view, like this:

let label: UILabel = [.text("Hello World"), .textColor(.red)]

In this question I have dramatically simplified the use case, instead allowing for writing:

let vanilla: UILabel = [1, 2, 3, 4]  // works!
print(vanilla.text!) // prints: "Sum: 10"

What I want to do is use the same ExpressibleByArrayLiteral syntax, but to a subclass of UILabel, called MyLabel. However the compiler stops me when I am trying to :

let custom: MyLabel = [1, 2, 3, 4] // Compilation error: "Could not cast value of type 'UILabel' to 'MyLabel'"

Instantiation of UILabel using array literals works, thanks to conformance to custom protocol Makeable below.

Is it somehow possible to make the compiler understand that I am referring to the array literal initializer of the subclass MyLabel and not its superclass UILabel?

The following code might not make any logical sense, but it is a minimal example, hiding away what I really want:

// This protocol has been REALLY simplified, in fact it has another name and important code.
public protocol ExpressibleByNumberArrayLiteral: ExpressibleByArrayLiteral {
    associatedtype Element
}

public protocol Makeable: ExpressibleByNumberArrayLiteral {
    // we want `init()` but we are unable to satisfy such a protocol from `UILabel`, thus we need this work around
    associatedtype SelfType
    static func make(values: [Element]) -> SelfType
}

public protocol Instantiatable: ExpressibleByNumberArrayLiteral {
    init(values: [Element])
}

// My code might have worked if it would be possible to check for _NON-conformance_ in where clause
// like this: `extension Makeable where !(Self: Instantiatable)`
extension Makeable {
    public init(arrayLiteral elements: Self.Element...) {
        self = Self.make(values: elements) as! Self
    }
}

extension Instantiatable {
    init(arrayLiteral elements: Self.Element...) {
        self.init(values: elements)
    }
}

extension UILabel: Makeable {
    public typealias SelfType = UILabel
    public typealias Element = Int

    public static func make(values: [Element]) -> SelfType {
        let label = UILabel()
        label.text = "Sum: \(values.reduce(0,+))"
        return label
    }
}

public class MyLabel: UILabel, Instantiatable {
    public typealias Element = Int
    required public init(values: [Element]) {
        super.init(frame: .zero)
        text = "Sum: \(values.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let vanilla: UILabel = [1, 2, 3, 4]
print(vanilla.text!) // prints: "Sum: 10"

let custom: MyLabel = [1, 2, 3, 4] // Compilation error: "Could not cast value of type 'UILabel' to 'MyLabel'"

I have also tried conforming to ExpressibleByArrayLiteral protocol by extending ExpressibleByNumberArrayLiteral instead (I suspect the two solutions might be equivalent, and compile to the same code..), like this:

extension ExpressibleByNumberArrayLiteral where Self: Makeable {
    public init(arrayLiteral elements: Self.Element...) {
        self = Self.make(values: elements) as! Self
    }
}

extension ExpressibleByNumberArrayLiteral where Self: Instantiatable {
    init(arrayLiteral elements: Self.Element...) {
        self.init(values: elements)
    }
}

But that did not work either. The same compilation error occurs.

I've written a comment in the big code block above, the compiler might have been able to determine which array literal initializer I was referring to if I would have been able to use negation in the where clause:
extension Makeable where !(Self: Instantiatable)

But AFAIK that is not possible, that code does not compile at least. Nor does extension Makeable where Self != Instantiatable.

Is what I want to do possible?

I would be okay with having to make MyLabel a final class. But that makes no difference.

Please please please say that this is possible.

Body:
after going through the Apple Docs, I initially thought this was not possible. However, I did find a post here, which applied to Strings and other non-UI classes. From the post i merged the idea that you cannot apply ExpressibleByArrayLiteral to a subclass through the inheritance approach, which is probably why you get the error (which I could reproduce many times with many other approaches).

Finally, by moving the ExpressibleByArrayLiteral adoption directly onto your UILabel subclass, it seems to be working!

public class MyLabel: UILabel, ExpressibleByArrayLiteral {

    public typealias Element = Int

    public override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init(values: [Element]) {
        super.init(frame: .zero)
        text = "Sum: \(values.reduce(0,+))"
    }

    public convenience required init(arrayLiteral: Element...) {
        self.init()
        self.text = "Sum: \(arrayLiteral.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let vanilla: MyLabel = [1, 2, 3, 4]

print(vanilla.text) // prints Sum: 10

Turns out we can't even inherit Expressibility on element type classes (Strings, Ints, etc), you still have to re-specify the initializer for it.

With some tweaking, I also applied these other methods for thought!

public class MyLabel: UILabel, ExpressibleByArrayLiteral {

    public typealias Element = Int

    private var values : [Element]?

    public var append : Element? {
        didSet {
            if let t = append {
                values?.append(t)
            }
        }
    }

    public var sum : Element {
        get {
            guard let s = values else {
                return 0
            }
            return s.reduce(0,+)
        }
    }

    public var sumString : String {
        get {
            return "\(sum)"
        }
    }

    public var label : String {
        get {
            guard let v = values, v.count > 0 else {
                return ""
            }
            return "Sum: \(sumString)"
        }
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init(values: [Element]) {
        super.init(frame: .zero)
        text = "Sum: \(values.reduce(0,+))"
    }

    public convenience required init(arrayLiteral: Element...) {
        self.init()
        self.values = arrayLiteral
        self.text = label
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let vanilla: MyLabel = [1, 2, 3, 4]

print(vanilla.label) //prints out Sum: 10 , without unwrapping ;)

For now, I can't seem to apply the Expressibility to a protocol approach like you did. However, as workarounds go, this seems to do the trick. Guess for now we just have to apply the initializers to each subclass. Unfortunate, but still worth looking all this up!

UPDATE TO RE-AFFIRM THE ISSUE WITH THE EXTENSION APPROACH

Swift's inheritance prohibits convenience inits when it cannot guarantee that the superclass will not be altered dramatically. While your init does not change UILABEL's properties, the strict-typing for extensions just does not support the combinations of required and convenience on this type of initializer.

I'm taking this from this post, which was included in the link above btw:

Because this is a non-final class. Consider if there were a subclass
  to Stack that had its own required initializer. How would you ensure
  that init(arrayLiteral:) called it? It couldn't call it (because it
  wouldn't know that it existed). So either init(arrayLiteral:) has to
  be required (which means it needs to be part of the main declaration
  and not a extension), or Stack has to be final.

If you mark it final, this works like you expect. If you want it to be
  subclassed, just move it out of the extension and into the main body.

And if we look at the TWO errors you get, simply by trying to extend UILabel to ExpressibleByArrayLiteral directly, and not through a nested network of protocols like what you are doing:

Initializer requirement 'init(arrayLiteral:)' can only be satisfied by a 'required' initializer in the definition of non-final class 'UILabel'

'required' initializer must be declared directly in class 'UILabel' (non in an extension).

So first. ExpressibleByArrayLiteral requires a 'required' initializer method to conform to it, to which as the compiler says: you cannot implement directly inside of extensions for the superclass you wish to customize. Unfortunately, by this logic alone.. your desired approach is flawed.

Second. The very specific initializer you want, 'init(arrayLiteral:), is for final - type classes. As in, classes which you mark with the keyword FINAL on it's declaration header, or class TYPES (Strings are one, and so are number classes). UILabel is simply non a final-class to allow subclassing and you cannot change this without hacking the language. To illustrate non-final and final, try subclass String, and you will get an error since it is not a class or protocol. which wouldn't get your through the App Store ANYWAYS. So by DESIGN, you just cannot use this method on UILabel itself via an extension.

Three. You take the custom protocol approach, and try to apply it to UILabel by extension and inheritance.. I do apologize, but Swift just does not ignore it's language structure simply because you layer some custom code between the two ends of the constrtaint. Your protocol approach, while elegant as it is, is just nesting the problem here, not addressing it. And this is because it just re-applies these initialization constraints back onto UILabel regardless of your own middleware.

Fourth. On a bit of a logical train of thought here. If you look at the Apple Docs on Expressibles inside of XCode (the code file itself), you notice that the protocols especially applies to RawRepresentable classes and types (Strings, Ints, Doubles, etc.):

For any enumeration with a string, integer, or floating-point raw
  type, the Swift compiler automatically adds RawRepresentable
  conformance. When defining your own custom enumeration, you give it a
  raw type by specifying the raw type as the first item in the
  enumeration's type inheritance list. You can also use literals to
  specify values for one or more cases.

So anything which is data representation as the root-level of the class, can adopt this by extension. You can clearly see above, when adding this protocol immediately to UILabel, you're also imposing the RawRepresentable protocol to it. Which it cannot adopt my nature, which i'm willing to bet is the source of the "MyLabel Cannot be cast to UILabel" error. UILabel is not one of these things, which is kind of why it gets this non-final class attribute: It's a UI element, which is a combination of many RawRepresentables. So it makes sense that you should not be able to directly initialize a class which is an ensemble of RawRepresentables directly, because if some mix up happens on init compiler-side and it does not alter the Raw type you're aiming for, it could just corrupt the class instance altogether and take every one down a debug nightmare.

To illustrate the RawRepresentable point I'm trying to make, here's what happens when you apply this approach to String, a RawRepresentable-conforming type:

extension String: ExpressibleByArrayLiteral {
    public typealias Element = Int

    public init(arrayLiteral elements: Element...) {
        self.init()
        self = "Sum: \(elements.reduce(0,+))"//WE GET NO ERRORS
    }

}

let t : String = [1,2,3,4]

print(t) // prints -> Sum: 10

Whereas...

extension UILabel: ExpressibleByArrayLiteral {
    public typealias Element = Int

    public convenience required init(arrayLiteral elements: Element...) { //The compiler even keeps suggesting you add the method types here illogically without taking to account what is there.. ie: it's confused by what you're trying to do..
        self.init()
        self.text = "Sum: \(elements.reduce(0,+))" //WE GET THE ERRORS
    }

}

//CANNOT PRINT.....

I'll even demonstrate how far the constraint goes in terms of add Expressibles on UILabel subclasses, and it's second-tier subclasses:

class Label : UILabel, ExpressibleByArrayLiteral {

    public typealias Element = Int

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    public required init(arrayLiteral elements: Element...) {
        super.init(frame: .zero)
        self.text = "Sum: \(elements.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }
}

let te : Label = [1,2,3,4]

print(te.text!) //prints:  Sum: 10

class SecondLabel : Label {

    public typealias Element = Int

    required init(arrayLiteral elements: Element...) {
        //THIS IS STILL REQUIRED... EVEN THOUGH WE DO NOT NEED TO MANUALLY ADOPT THE PROTOCOL IN THE CLASS HEADER
        super.init(frame: .zero)
        self.text = "Sum: \(elements.reduce(0,+))"
    }

    public required init?(coder: NSCoder) { fatalError() }

}

let ta : SecondLabel = [1,2,3,4]

print(ta.text!) //prints:  Sum: 10

In conclusion.
Swift is designed this way. You cannot apply this particular protocol directly onto it because UILabel is a language level superclass and the guys who come up with this stuff don't want you to have this much over-reach into UILabel. So, you simply cannot do this because this protocol cannot be applied through extensions of non-final superclasses due to the nature of UILabel and the protocol itself. They are just not compatible this way. However, you can apply this on its subclasses on a per-subclass basis. Meaning you have to re-declare the conforming initializer each time. It sucks! But it's just how it works.

I commend your approach, it seems to almost get the extensions approach down to a T.  However, there seems to be some things in how Swift is built that you just cannot circumvent. I am not the only one to affirm this conclusion (just check the links), so I would ask you to remove your downvote. You have a solution that i've given you, I've given you the references to validate my point, and i've also provided code to show you how you can remedy this constraint in the language's nature. Sometimes there just is no solution to the desired approach. And other times another approach is the only way to get around things.


问:
Import face_recognition by python on ubuntu
I am trying to play around with face_recognition on python, but after I pip install the face_recognition module everytime I try to import face_recognition I get the following error messages:

import face_recognition

Traceback (most recent call last):

File "", line 1, in

File "/usr/local/lib/python2.7/dist-packages/face_recognition/init.py", line 7, in

from .api import load_image_file, face_locations, face_landmarks, face_encodings, compare_faces, face_distance

File "/usr/local/lib/python2.7/dist-packages/face_recognition/api.py", line 4, in

import dlib

File "/usr/local/lib/python2.7/dist-packages/dlib/init.py", line 1, in

from .dlib import *

ImportError: libboost_python.so.1.64.0: cannot open shared object file: No such file or directory

I don't know what could be causing the trouble. Any help is appreciated! I believe It has to do with the shared file in the last line of the error message, though I don't have any clues as to where it is located :(

答:
Have you installed Boost.Python? Try apt-get install libboost-python-dev on Debian-likes.

Ah, but I see on Ubuntu packages and Debian testing that that is only at version 1.62, and it seems that your module specifically requires version 1.64 — which was released less than two months ago.

Most distributions do not seem to have available for Boost 1.64, so if you need that version specifically, you may have to build it from source. There are some instructions in the Boost.Python docs.