问:
How to read the file without encoding and extract desired urls with python3?
Environment :python3.

There are many files ,some of them encoding with gbk,others encoding with utf-8.
I want to extract all the jpg with regular expression

For s.html encoding with gbk.

```<code>tree = open("/tmp/s.html","r").read()
</code>```

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 135: invalid start byte

```<code>tree = open("/tmp/s.html","r",encoding="gbk").read()
pat = "http://.+\.jpg"
result = re.findall(pat,tree)
print(result)
</code>```

['http://somesite/2017/06/0_56.jpg']

It is a huge job to open all the files with specified encoding,i want a smart way to extract jpg urls in all the files.

答:
If they have mixed encoding, you could try one encoding and fall back to another:

```<code># first open as binary
with open(..., 'rb') as f:
    f_contents = f.read()
    try:
        contents = f_contents.decode('UTF-8')
    except UnicodeDecodeError:
        contents = f_contents.decode('gbk')
    ...
</code>```

If they are html files, you may also be able to find the encoding tag, or search them as binary with a binary regex:

```<code>contents = open(..., 'rb').read()
regex = re.compile(b'http://.+\.jpg')
result = regex.findall(contents)
# now you'll probably want to `.decode()` each of the urls, but you should be able to do that pretty trivially with even the `ASCII` codec
</code>```

Though now that I think of it, you probably don't really want to use regex to capture the links as you'll then have to deal with html entities (&) and may do better with something like pyquery

Here's a quick example using pyquery

```<code>contents = open(..., 'rb').read()
pq = pyquery.PyQuery(contents)
images = pq.find('img')
for img in images:
   img = pyquery.PyQuery(img)
   if img.attr('src').endswith('.jpg')
       print(img.attr('src'))
</code>```

Not on my computer with things installed, so mileage with these code samples may vary

Body:
Environment :python3.

There are many files ,some of them encoding with gbk,others encoding with utf-8.
I want to extract all the jpg with regular expression

For s.html encoding with gbk.

tree = open("/tmp/s.html","r").read()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 135: invalid start byte

tree = open("/tmp/s.html","r",encoding="gbk").read()
pat = "http://.+\.jpg"
result = re.findall(pat,tree)
print(result)

['http://somesite/2017/06/0_56.jpg']

It is a huge job to open all the files with specified encoding,i want a smart way to extract jpg urls in all the files.

Body:
If they have mixed encoding, you could try one encoding and fall back to another:

# first open as binary
with open(..., 'rb') as f:
    f_contents = f.read()
    try:
        contents = f_contents.decode('UTF-8')
    except UnicodeDecodeError:
        contents = f_contents.decode('gbk')
    ...

If they are html files, you may also be able to find the encoding tag, or search them as binary with a binary regex:

contents = open(..., 'rb').read()
regex = re.compile(b'http://.+\.jpg')
result = regex.findall(contents)
# now you'll probably want to `.decode()` each of the urls, but you should be able to do that pretty trivially with even the `ASCII` codec

Though now that I think of it, you probably don't really want to use regex to capture the links as you'll then have to deal with html entities (&amp;) and may do better with something like pyquery

Here's a quick example using pyquery

contents = open(..., 'rb').read()
pq = pyquery.PyQuery(contents)
images = pq.find('img')
for img in images:
   img = pyquery.PyQuery(img)
   if img.attr('src').endswith('.jpg')
       print(img.attr('src'))

Not on my computer with things installed, so mileage with these code samples may vary


来源: stackexchange

问:
Remove several rows based on one row
In the data.frame below, I have 3 variables. id (A1 to A10); var A to E and value. I want to remove specific rows based on these conditions

For each variable var (A, B, C, D or E);

If id == A5 and

if value < 5

then

remove all rows (10 rows) for this specific variable.

I will appreciate any suggestions how to do that.

```<code>> dput(df)
structure(list(id = structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L), .Label = c("A1",
"A10", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"), class = "factor"),
    var = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("A",
    "B", "C", "D", "E"), class = "factor"), value = c(2, 4, 7,
    8, 8, 6, 3, 8, 4, 2, 3, 5, 4, 3, 2, 7, 4, 2, 1, 22, 54, 21,
    36, 52, 14, 75, 12, 15, 24, 3, 2, 4, 5, 7, 9, 21, 22, 12,
    12, 12, 0.3, 0.4, 0.9, 2, 3, 2, 0.5, 0.2, 0.4, 0.7)), .Names = c("id",
"var", "value"), class = "data.frame", row.names = c(NA, -50L
))
</code>```

答:
We can do this with base R

```<code>df[with(df, ave(!(id == 'A5' & value < 5), var, FUN = any)),]
</code>```

Or using data.table

```<code>library(data.table)
setDT(df)[df[, .I[any(!(id == 'A5' & value  < 5))], var]$V1]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Remove several rows based on one row

Body:
In the data.frame below, I have 3 variables. id (A1 to A10); var A to E and value. I want to remove specific rows based on these conditions

For each variable var (A, B, C, D or E);

If id == A5 and

if value < 5

then

remove all rows (10 rows) for this specific variable.

I will appreciate any suggestions how to do that.

> dput(df)
structure(list(id = structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L), .Label = c("A1",
"A10", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"), class = "factor"),
    var = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("A",
    "B", "C", "D", "E"), class = "factor"), value = c(2, 4, 7,
    8, 8, 6, 3, 8, 4, 2, 3, 5, 4, 3, 2, 7, 4, 2, 1, 22, 54, 21,
    36, 52, 14, 75, 12, 15, 24, 3, 2, 4, 5, 7, 9, 21, 22, 12,
    12, 12, 0.3, 0.4, 0.9, 2, 3, 2, 0.5, 0.2, 0.4, 0.7)), .Names = c("id",
"var", "value"), class = "data.frame", row.names = c(NA, -50L
))

Body:
We can do this with base R

df[with(df, ave(!(id == 'A5' & value < 5), var, FUN = any)),]

Or using data.table

library(data.table)
setDT(df)[df[, .I[any(!(id == 'A5' & value  < 5))], var]$V1]


问:
Laravel Edit form error
this is my form:

```<code>{!! Form::model($countries, ['route' => ['countries.update', $countries->id], 'method' => "PUT"]) !!}
   {{ Form::label('code', 'Country Code:') }}
   {{ Form::text('code', null, ['class' => 'form-control']) }}
   {{ Form::label('name', 'Country Name:') }}
   {{ Form::text('name', null, ['class' => 'form-control']) }}
   {{ Form::submit('Save', ['class' => 'mt-20 btn btn-success btn-sm']) }}
{!! Form::close() !!}
</code>```

and this is my update function:

```<code>$countries = Country::find($id);
$this->validate($request, array(
   'code' => 'required|min:2|max:4',
   'name' => 'required|max:255'
));
$country = Country::where('id',$id)->first();
$country->code = Input::get('code');
$country->name = Input::get('name');
$country->save();
Session::flash('success', 'The Country info was successfully updated.');
return redirect()->route('locations.index', $country->id);
</code>```

what is the issue in my form that I'm getting Undefined variable: countries error from my blade?

答:
Consolidating this answer from our conversation in the comments.

The error Undefined variable: countries in the blade view (form) arises as you have forgotten to pass the said variable to the view.

In the edit function (as this the function calling the view), add the following

```<code>$countries = Country::find($id); // though I'd suggest naming it $country
...
return view('<view_name>', compact('countries'));
</code>```

Title: Laravel Edit form error

Body:
this is my form:

{!! Form::model($countries, ['route' => ['countries.update', $countries->id], 'method' => "PUT"]) !!}
   {{ Form::label('code', 'Country Code:') }}
   {{ Form::text('code', null, ['class' => 'form-control']) }}
   {{ Form::label('name', 'Country Name:') }}
   {{ Form::text('name', null, ['class' => 'form-control']) }}
   {{ Form::submit('Save', ['class' => 'mt-20 btn btn-success btn-sm']) }}
{!! Form::close() !!}

and this is my update function:

$countries = Country::find($id);
$this->validate($request, array(
   'code' => 'required|min:2|max:4',
   'name' => 'required|max:255'
));
$country = Country::where('id',$id)->first();
$country->code = Input::get('code');
$country->name = Input::get('name');
$country->save();
Session::flash('success', 'The Country info was successfully updated.');
return redirect()->route('locations.index', $country->id);

what is the issue in my form that I'm getting Undefined variable: countries error from my blade?

Body:
Consolidating this answer from our conversation in the comments.

The error Undefined variable: countries in the blade view (form) arises as you have forgotten to pass the said variable to the view.

In the edit function (as this the function calling the view), add the following

$countries = Country::find($id); // though I'd suggest naming it $country
...
return view('<view_name>', compact('countries'));


问:
Automatically closing Drawer when view width is decreasing
I'm trying to make a view like Firebase's console with React and material-ui.

How can I build a Drawer that will automatically close when view(browser) width is decreasing.

答:
Quite easy, you can hook up the listener on resize event on your react class:

var RootPage = React.createClass({
    render: function() {
        return <Drawer refs={'drawer'} />;
    },

    // we trigger our drawer here
    componentWillUpdate: function(nextProp, nextState) {
      if(nextState.width < this.state.width) {
        this.refs.drawer.open = false;
      }
    },

    windowOnResize: function() {
      var width = $(window).width();
      this.setState({ width: width });
    },

    componentWillMount: function() {
      this.windowOnResize();
    },

    componentDidMount: function() {
      window.addEventListener("resize", this.windowOnResize);
    },

    componentWillUnmount: function() {
      window.removeEventListener("resize", this.windowOnResize);
    }
});```


问:
Is there a more efficient way than a CNN for object recognition if only one object needs to be recognized?
It appears that currently the industry standard for object recognition is a CNN. However, if a system only needs to identify one type of object (ie people), is there a less resource intensive way to recognize the given object (maybe SVM or similar techniques?)</p>

答: CNN are the best approach to the problem (Since you are learning the features that represent the object). You have to think if you want to approach the problem as a binary one (specific object/background) or as an instance one (be able to identify a specific object but at the same time be able of identifying different instances of the same object)


问:
Set default value to a ForeignKey Field based on data-table row clicked
I have 2 data-table in my app, onClick on any of the project-content-datatable row will display its child content on a second table (Content Table), Now in my second table I have a button to pop-up a form in modal to create new content in it, In that form how I can set the default value of the parent_project_content = models.ForeignKey(ProjectContent, on_delete=models.CASCADE) based on which row project-content-datatable user click at.

Any help is much appreciated, Thank you

Here is my code
HTML

```<code><table id="project-content-datatable" class="display table table-hover table-responsive" style="width: 100%">
    <thead>
    <tr>
        <th class="small text-muted text-uppercase"><strong>Name</strong></th>
        <th class="small text-muted text-uppercase"><strong>Description</strong></th>
    </tr>
    </thead>
    <tbody>
    {% for content in content_list %}
        {% if content.search_type.name == searchtype.name %}
            <tr class="text-primary">
                <td class="text-left" style="cursor: pointer"
                    onclick='load_workorder({{ content.id }});'>
                    {{ content.id }}
                </td>
                <td class="text-left" style="cursor: pointer" onclick='load_workorder({{ content.id }});'>
                    {{ content.name }} </td>
            </tr>
        {% endif %}
    {% endfor content_list %}
    </tbody>
</table>
<!-- END Hover Table -->

<!-- WORKORDER START-->
    <h3 class="panel-title text-white">WorkOrders</h3>
 <div class="btn-group" role="group" aria-label="...">
    <button
        data-toggle="modal" data-target="#create_new_workorder"
        type="button" class="btn btn-sm btn-success btn-outline"><span
        class="hidden-md hidden-sm hidden-xs">Create Workorder</span> <i
        class="fa fa-fw fa-plus"></i>
    </button>
</div>
<!--Create Workorder Form Modal -->
<div class="modal fade" id="create_new_workorder" tabindex="-1" role="dialog"
     aria-labelledby="TitleLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h4 class="modal-title">Create New Workorder</h4>
            </div>
            <form method="POST" enctype="multipart/form-data">{% csrf_token %}
                <div class="modal-body">
                    {{ workorder_form.as_p }}
                </div>
                <div class="modal-footer">
                    <input class="btn btn-primary" type="submit"
                           value="Create Workorder"/>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

model.py

```<code>class WorkOrder(models.Model):
     parent_project_content = models.ForeignKey(ProjectContent, on_delete=models.CASCADE)
    description = models.TextField(default='workorder of project content', blank=True)
    assign_to = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='assign_to', null=True, blank=True)
</code>```

form.py

```<code>class CreateWorkorderForm(forms.ModelForm):
    class Meta:
        model = WorkOrder
        fields = ['parent_project_content','description', 'assign_to',]
</code>```

view.py

```<code>def content_view(request, project_id):
    """
    :param request:
    :param project_id:
    :return:
    """
    selected_project = get_object_or_404(Project, id=project_id)
    search_type_list = selected_project.search_type.all()
    project = get_object_or_404(Project, id=project_id)
    form = CreateProjectContentForm(request.POST or None, request.FILES or None)
    workorder_form = CreateWorkorderForm(request.POST or None, request.FILES or None)

    if workorder_form.is_valid():
        instance = workorder_form.save(commit=False)
        instance.parent_project_content = WorkOrder.objects.get(parent_project_content=24)
        instance.save()

    if form.is_valid():
        inst = form.save(commit=False)
        inst.project = project
        inst.save()

    context = {
        'form': form,
        'workorder_form': workorder_form,
        "search_type_list": search_type_list,
        "selected_project": selected_project,
        "content_list": ProjectContent.objects.all().filter(project=selected_project.id),
        "content_id": WorkOrder.objects.all,
    }
    return render(request, 'dashboard/projects/content.html', context)
</code>```

答:
create a separate view for handling workorder form,place an 'href' on the button that pops up the work order form, this is going to lead you to the view that handles workorder submission something like:

```<code>href="{% url 'workorder_handle' pk=content.pk %}"
</code>```

your urls.py would be like:`

```<code>url(r'/workorder_form/(?P<pk>\d+)/$', workorder_view, name='workorder_handle'),
</code>```

I'm imagining things here, replace what needs to be replaced

Body:
I have 2 data-table in my app, onClick on any of the project-content-datatable row will display its child content on a second table (Content Table), Now in my second table I have a button to pop-up a form in modal to create new content in it, In that form how I can set the default value of the parent_project_content = models.ForeignKey(ProjectContent, on_delete=models.CASCADE) based on which row project-content-datatable user click at.

Any help is much appreciated, Thank you

Here is my code
HTML

        Name
        Description

    {% for content in content_list %}
        {% if content.search_type.name == searchtype.name %}

                    {{ content.id }}

                    {{ content.name }}

        {% endif %}
    {% endfor content_list %}

WorkOrders

    <button
        data-toggle="modal" data-target="#create_new_workorder"
        type="button" class="btn btn-sm btn-success btn-outline">Create Workorder
    </button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×</button>

Create New Workorder

            <form method="POST" enctype="multipart/form-data">{% csrf_token %}

                    {{ workorder_form.as_p }}

                    <input class="btn btn-primary" type="submit"
                           value="Create Workorder"/>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel
                    </button>

            </form>

model.py

class WorkOrder(models.Model):
     parent_project_content = models.ForeignKey(ProjectContent, on_delete=models.CASCADE)
    description = models.TextField(default='workorder of project content', blank=True)
    assign_to = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='assign_to', null=True, blank=True)

form.py

class CreateWorkorderForm(forms.ModelForm):
    class Meta:
        model = WorkOrder
        fields = ['parent_project_content','description', 'assign_to',]

view.py

def content_view(request, project_id):
    """
    :param request:
    :param project_id:
    :return:
    """
    selected_project = get_object_or_404(Project, id=project_id)
    search_type_list = selected_project.search_type.all()
    project = get_object_or_404(Project, id=project_id)
    form = CreateProjectContentForm(request.POST or None, request.FILES or None)
    workorder_form = CreateWorkorderForm(request.POST or None, request.FILES or None)

    if workorder_form.is_valid():
        instance = workorder_form.save(commit=False)
        instance.parent_project_content = WorkOrder.objects.get(parent_project_content=24)
        instance.save()

    if form.is_valid():
        inst = form.save(commit=False)
        inst.project = project
        inst.save()

    context = {
        'form': form,
        'workorder_form': workorder_form,
        "search_type_list": search_type_list,
        "selected_project": selected_project,
        "content_list": ProjectContent.objects.all().filter(project=selected_project.id),
        "content_id": WorkOrder.objects.all,
    }
    return render(request, 'dashboard/projects/content.html', context)

Body:
create a separate view for handling workorder form,place an 'href' on the button that pops up the work order form, this is going to lead you to the view that handles workorder submission something like:

href="{% url 'workorder_handle' pk=content.pk %}"

your urls.py would be like:`

url(r'/workorder_form/(?P<pk>\d+)/$', workorder_view, name='workorder_handle'),

I'm imagining things here, replace what needs to be replaced


答:
It depends on a few things but something like this may work for you

im assuming this count never changes as it is in the past so the result can be cached somehow

```<code>count1 = "select count(*) from record_updates where date_updated <= '2009-10-11 15:33:22'"
</code>```

gives you the total count of records in the table,
this is an approximate value in innodb table so BEWARE, depends on engine

```<code>count2 = "select table_rows from information_schema.`TABLES` where table_schema = 'marctoxctransformation' and TABLE_NAME = 'record_updates'"
</code>```

your answer

result = count2 - count1

ContentLicense: CC BY-SA 4.0

Title: optimize mysql count query

Body:
Is there a way to optimize this further or should I just be satisfied that it takes 9 seconds to count 11M rows ?

devuser@xcmst > mysql --user=user --password=pass -D marctoxctransformation -e "desc record_updates"
+--------------+----------+------+-----+---------+-------+
| Field        | Type     | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
| record_id    | int(11)  | YES  | MUL | NULL    |       |
| date_updated | datetime | YES  | MUL | NULL    |       |
+--------------+----------+------+-----+---------+-------+
devuser@xcmst > date; mysql --user=user --password=pass -D marctoxctransformation -e "select count(*) from record_updates where date_updated > '2009-10-11 15:33:22' "; date
Thu Dec  9 11:13:17 EST 2010
+----------+
| count(*) |
+----------+
| 11772117 |
+----------+
Thu Dec  9 11:13:26 EST 2010
devuser@xcmst > mysql --user=user --password=pass -D marctoxctransformation -e "explain select count(*) from record_updates where date_updated > '2009-10-11 15:33:22' "
+----+-------------+----------------+-------+--------------------------------------------------------+--------------------------------------------------------+---------+------+----------+--------------------------+
| id | select_type | table          | type  | possible_keys                                          | key                                                    | key_len | ref  | rows     | Extra                    |
+----+-------------+----------------+-------+--------------------------------------------------------+--------------------------------------------------------+---------+------+----------+--------------------------+
|  1 | SIMPLE      | record_updates | index | idx_marctoxctransformation_record_updates_date_updated | idx_marctoxctransformation_record_updates_date_updated | 9       | NULL | 11772117 | Using where; Using index |
+----+-------------+----------------+-------+--------------------------------------------------------+--------------------------------------------------------+---------+------+----------+--------------------------+
devuser@xcmst > mysql --user=user --password=pass -D marctoxctransformation -e "show keys from record_updates"
+----------------+------------+--------------------------------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+
| Table          | Non_unique | Key_name                                               | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+----------------+------------+--------------------------------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+
| record_updates |          1 | idx_marctoxctransformation_record_updates_date_updated |            1 | date_updated | A         |        2416 |     NULL | NULL   | YES  | BTREE      |         |
| record_updates |          1 | idx_marctoxctransformation_record_updates_record_id    |            1 | record_id    | A         |    11772117 |     NULL | NULL   | YES  | BTREE      |         |
+----------------+------------+--------------------------------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+

Body:
It depends on a few things but something like this may work for you

im assuming this count never changes as it is in the past so the result can be cached somehow

count1 = "select count(*) from record_updates where date_updated <= '2009-10-11 15:33:22'"

gives you the total count of records in the table,
this is an approximate value in innodb table so BEWARE, depends on engine

count2 = "select table_rows from information_schema.`TABLES` where table_schema = 'marctoxctransformation' and TABLE_NAME = 'record_updates'"

your answer

result = count2 - count1

ContentLicense: CC BY-SA 2.5


问:
What is the replacement method to use for the deprecated codenameone getTitleArea
I am looking for the alternative method replacement for (deprecated)getTitleArea() method as it is widely used in the MaterialScreensUIKit demo

Thanks in Advance.

答: It isn't used we just set it's UIID but don't do anything risky which is the reason for the deprecation. The Toolbar class is where most of the functionality is placed now.


问:
Go concurrency with for loop and anonymous function behaves unexpectedly
I have already found out a way for the code to behave as I want, but I would like to understand why it behaves like this so that my understanding of Go concurrency improves.

I was testing out sync.WaitGroup to wait for some goroutines to finish because I plan on doing multiple uploads to Amazon S3 in this way.

This was the code I had originally:

```<code>func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go func() {
            fmt.Println(i)
            time.Sleep(time.Second * 1)
            wg.Done()
        }()
    }

    wg.Wait()
}
</code>```

I was surprised to see that the output was: 6, 6, 6, 6, 6.

Instead of something like: 2, 4, 1, 5, 3.

Since the loop does not even go to 6, this made no sense to me.
I later passed the i variable to the anonymous function as argument
and then it behaved as I expected.

Why does this happen? I don't understand it.

答:
To answer your question, you have to pass i into your func so that each routine would have its own copy of the value of i.

So your code should look like this

```<code>func main() {
    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go func(i int) {
            fmt.Println(i)
            time.Sleep(time.Second * 1)
            wg.Done()
        }(i)
    }

    wg.Wait()
}
</code>```

I wrote this utility function to help parallelize a group of functions:

```<code>import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So in your case, we could do this

```<code>func main() {
    functions := []func(){}
    for i := 1; i <= 5; i++ {
            function := func(i int) func() {
                return func() {
                        fmt.Println(i)
                }
            }(i)

        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Done")
}
</code>```

If you wanted to use the Parallelize function, you can find it here https://github.com/shomali11/util

Body:
I have already found out a way for the code to behave as I want, but I would like to understand why it behaves like this so that my understanding of Go concurrency improves.

I was testing out sync.WaitGroup to wait for some goroutines to finish because I plan on doing multiple uploads to Amazon S3 in this way.

This was the code I had originally:

func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go func() {
            fmt.Println(i)
            time.Sleep(time.Second * 1)
            wg.Done()
        }()
    }

    wg.Wait()
}

I was surprised to see that the output was: 6, 6, 6, 6, 6.

Instead of something like: 2, 4, 1, 5, 3.

Since the loop does not even go to 6, this made no sense to me.
I later passed the i variable to the anonymous function as argument
and then it behaved as I expected.

Why does this happen? I don't understand it.

Body:
To answer your question, you have to pass i into your func so that each routine would have its own copy of the value of i.

So your code should look like this

func main() {
    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go func(i int) {
            fmt.Println(i)
            time.Sleep(time.Second * 1)
            wg.Done()
        }(i)
    }

    wg.Wait()
}

I wrote this utility function to help parallelize a group of functions:

import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So in your case, we could do this

func main() {
    functions := []func(){}
    for i := 1; i <= 5; i++ {
            function := func(i int) func() {
                return func() {
                        fmt.Println(i)
                }
            }(i)

        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Done")
}

If you wanted to use the Parallelize function, you can find it here https://github.com/shomali11/util


答:
You may use textscan, and get the indices/ line numbers of the labels you want. After knowing the line numbers, you can extract what you want.

```<code>fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
S = S{1} ;
fclose(fid) ;
%% get bicycle lines
idx = strfind(S, 'bicycle');
idx = find(not(cellfun('isempty', idx)));
S_bicycle = S(idx)
%% write this to text file
fid2 = fopen('text.txt','wt') ;
fprintf(fid2,'%s\n',S_bicycle{:});
fclose(fid2) ;
</code>```

From S_bicycle, you can extract your numbers.

Title: MATLAB - replace the string in a text file with index and delete those line without indexed

Body:
I have a text file with data structure like this

30,311.263671875,158.188034058,20.6887207031,17.4877929688,0.000297248129755,aeroplane
30,350.668334961,177.547393799,19.1939697266,18.3677368164,0.00026999923648,aeroplane
30,367.98135376,192.697219849,16.7747192383,23.0987548828,0.000186387239864,aeroplane
30,173.569274902,151.629364014,38.0069885254,37.5704650879,0.000172595537151,aeroplane
30,553.904602051,309.903320312,660.893981934,393.194030762,5.19620243722e-05,aeroplane
30,294.739196777,156.249740601,16.3522338867,19.8487548828,1.7795707663e-05,aeroplane
30,34.1946258545,63.4127349854,475.104492188,318.754821777,6.71026540999e-06,aeroplane
30,748.506652832,0.350944519043,59.9415283203,28.3256549835,3.52978979379e-06,aeroplane
30,498.747009277,14.3766479492,717.006652832,324.668731689,1.61551643174e-06,aeroplane
30,81.6389465332,498.784301758,430.23046875,210.294677734,4.16855394647e-07,aeroplane
30,251.932098389,216.641052246,19.8385009766,20.7131652832,3.52147743106,bicycle
30,237.536972046,226.656692505,24.0902862549,15.7586669922,1.8601918593,bicycle
30,529.673400879,322.511322021,25.1921386719,21.6920166016,0.751171214506,bicycle
30,255.900146484,196.583847046,17.1589355469,27.4430847168,0.268321367912,bicycle
30,177.663650513,114.458488464,18.7516174316,16.6759414673,0.233057001606,bicycle
30,436.679382324,273.383331299,17.4342041016,19.6081542969,0.128449092153,bicycle

I want to index those file with a label file.and the result will be something like this.

60,509.277435303,284.482452393,26.1684875488,31.7470092773,0.00807665128377,15
60,187.909835815,170.448471069,40.0388793945,58.8763122559,0.00763951029512,15
60,254.447280884,175.946624756,18.7212677002,21.9440612793,0.00442053096776,15

However there might be some class that is not in label class and I need to filter those line out so I can use load() to load in.(you can't have char inside that text file and execute load().

here is my implement:

function test(vName,meta)
f_dt   = fopen([vName '.txt'],'r');
f_indexed = fopen([vName '_indexed.txt'], 'w');
lbls   = loadlbl()

count = 1;
while(true),
  if(f_dt == -1),
    break;
  end
  dt = fgets(f_dt);

  if(dt == -1),
    break
  else
    dt_cls = strsplit(dt,','){7};
    dt_cls = regexprep(dt_cls, '\s+', '');

    cls_idx = find(strcmp(lbls,dt_cls));
    if(~isempty(cls_idx))
      dt = strrep(dt,dt_cls,int2str(cls_idx));
      fprintf(f_indexed,dt);
    end
  end

end

fclose(f_indexed);
if(f_dt ~= -1),
fclose(f_dt);
end

end

However it work very very slow because the text file contains 100 thousand of lines. Is it anyway that I could do this task smarter and faster?

Body:
You may use textscan, and get the indices/ line numbers of the labels you want. After knowing the line numbers, you can extract what you want.

fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
S = S{1} ;
fclose(fid) ;
%% get bicycle lines
idx = strfind(S, 'bicycle');
idx = find(not(cellfun('isempty', idx)));
S_bicycle = S(idx)
%% write this to text file
fid2 = fopen('text.txt','wt') ;
fprintf(fid2,'%s\n',S_bicycle{:});
fclose(fid2) ;

From S_bicycle, you can extract your numbers.


问:
How to trigger Multibranch Pipeline build with github webhook
In freestyle job there is an option named "GitHub hook trigger for GITScm polling" on stage Build Trigger.

screen capture here:

.

Together with webhook in gitlab config "http://myjenkins/gitlab/notify_commit" it works fine, meaning that the build will be triggered automatically when something is pushed to the repository.
But why in Multibranch Pipeline there is only one option named "Periodically if not otherwise run"? Is there some plug-in not installed? How to trigger Multibranch Pipeline build with github webhook like freestyle job

答:
This page described how to configure pipeline-as-code on multibranch workflow in jenkins.

This is the quote from the description inside:

The Workflow Multibranch feature (provided by the workflow plugin) provides the following key abilities:

Automatic Workflow (job) creation in Jenkins per new branch in the
repo (assuming webhooks are registered from GH to Jenkins).

Build specific to that child-branch and its unique scm change and build history.

Automatic job pruning/deletion for branches deleted from the repository, according to the settings.

Flexibility to individually configure branch properties, by overriding the parent properties, if required.

To configure the webhooks, refer to this page.

To check if the events notify your jenkins you can use this feature below:

PS: Watch the URL target that you configured, if you miss the "/" at the end of url it might not be able to reach the jenkins.

I hope this helps!


问:
Odoo Wizard: How to populate with active fields from parent view
I'm stuck to populate a wizard since a week know, and I'm completely lost on the way to do that.

Until know, I've created a custom button on the stock module, view_picking_form record with an inherited model (see views.xml). I also know how to create a custom wizard (wizard.py wizard.xml).

But what I do not know is how to populate it with the list of products fields product_id, product_qty, qty_done that are linked to to the parent view. I'm working with the new API on Odoo 10 and couln't find the method to do that.
Odoo always tells me it doesn't know the fields I want to pass and nothing display on the wizard.

Can anyone help me on that ?

views.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <odoo>
        <data>
            <record id="view_picking_form_inherit" model="ir.ui.view">
                <field name="name">stock.picking.form.inherit</field>
                <field name="model">stock.picking</field>
                <field name="inherit_id" ref="stock.view_picking_form"/>
                <field name="arch" type="xml">

                    <xpath expr="//form/sheet/h1[@class='hidden-xs']" position="inside">
                        <div class="oe_right oe_button_box">

                            <button string="Open Wizard" name="%(action_wizard)d"
                                    type="action" class="oe_button oe_form_button oe_highlight"/>
                        </div>
                    </xpath>
                </field>
            </record>
        </data>
    </odoo>
</code>```

wizard.py

```<code># -*- coding: utf-8 -*-
from odoo import _, api, fields, models

class MyClass(models.TransientModel):
    _name = 'stock.picking.wizard'
    _inherit = ['stock.picking', 'stock.pack.operation']

    def _default_products(self):
        active_id = self.env.context.get('active_id')
        if active_id:
            product = self.env['stock.picking'].browse(active_id)
            return product.product_id
        return False

    product_id = fields.Many2one('product.product', string='Product', default=_default_products)
</code>```

wizard.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
        <record id="view_wizard" model="ir.ui.view">
            <field name="name">stock_picking_wizard</field>
            <field name="model">stock.picking.wizard</field>
            <field name="arch" type="xml">
                <form string="Stock Products">
                    <field name="picking_id"/>
                    <tree string="Product list">
                        <field name="product_id"/>
                        <field name="product_qty"/>
                    </tree>
                </form>
            </field>
        </record>

        <record id="action_wizard" model="ir.actions.act_window">
            <field name="name">Wizard</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">stock.picking.wizard</field>
            <field name="view_type">form</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="view_wizard"/>
            <field name="target">new</field>
        </record>
    </data>
</odoo>
</code>```

答:
You need to pass the active_id through context:  context="{'default_active_id': active_id}"

```<code>  <button string="Open Wizard" name="%(action_wizard)d"
                                        type="action" context="{'default_active_id': active_id}" class="oe_button oe_form_button oe_highlight"/>
</code>```

Body:
I'm stuck to populate a wizard since a week know, and I'm completely lost on the way to do that.

Until know, I've created a custom button on the stock module, view_picking_form record with an inherited model (see views.xml). I also know how to create a custom wizard (wizard.py wizard.xml).

But what I do not know is how to populate it with the list of products fields product_id, product_qty, qty_done that are linked to to the parent view. I'm working with the new API on Odoo 10 and couln't find the method to do that.
Odoo always tells me it doesn't know the fields I want to pass and nothing display on the wizard.

Can anyone help me on that ?

views.xml

    <?xml version="1.0" encoding="utf-8"?>
    <odoo>
        <data>
            <record id="view_picking_form_inherit" model="ir.ui.view">
                <field name="name">stock.picking.form.inherit</field>
                <field name="model">stock.picking</field>
                <field name="inherit_id" ref="stock.view_picking_form"/>
                <field name="arch" type="xml">

                    <xpath expr="//form/sheet/h1[@class='hidden-xs']" position="inside">

                            <button string="Open Wizard" name="%(action_wizard)d"
                                    type="action" class="oe_button oe_form_button oe_highlight"/>

                    </xpath>
                </field>
            </record>
        </data>
    </odoo>

wizard.py

# -*- coding: utf-8 -*-
from odoo import _, api, fields, models

class MyClass(models.TransientModel):
    _name = 'stock.picking.wizard'
    _inherit = ['stock.picking', 'stock.pack.operation']

    def _default_products(self):
        active_id = self.env.context.get('active_id')
        if active_id:
            product = self.env['stock.picking'].browse(active_id)
            return product.product_id
        return False

    product_id = fields.Many2one('product.product', string='Product', default=_default_products)

wizard.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
        <record id="view_wizard" model="ir.ui.view">
            <field name="name">stock_picking_wizard</field>
            <field name="model">stock.picking.wizard</field>
            <field name="arch" type="xml">
                <form string="Stock Products">
                    <field name="picking_id"/>
                    <tree string="Product list">
                        <field name="product_id"/>
                        <field name="product_qty"/>
                    </tree>
                </form>
            </field>
        </record>

        <record id="action_wizard" model="ir.actions.act_window">
            <field name="name">Wizard</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">stock.picking.wizard</field>
            <field name="view_type">form</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="view_wizard"/>
            <field name="target">new</field>
        </record>
    </data>
</odoo>

Body:
You need to pass the active_id through context:  context="{'default_active_id': active_id}"

  <button string="Open Wizard" name="%(action_wizard)d"
                                        type="action" context="{'default_active_id': active_id}" class="oe_button oe_form_button oe_highlight"/>


问:
Instantiating JavaFX property inside a JPA entity causes "Unable to load class" error
I have the following class in a War. It's also the only class that has any JPA annotations:

```<code>@MappedSuperclass
public abstract class BaseEntity {
    protected ObjectProperty<Object> loc3 = new SimpleObjectProperty<>();
}
</code>```

When I deploy the War I get the following error:

```<code>ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 65) MSC000001: Failed to start service jboss.persistenceunit."DevCrowd.war#prod": org.jboss.msc.service.StartException in service jboss.persistenceunit."DevCrowd.war#prod": org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [pl.devcrowd.virtual.business.state.entity.BaseEntity]
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:179)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:121)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:193)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [pl.devcrowd.virtual.business.state.entity.BaseEntity]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:232)
    at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:103)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.<init>(MetadataBuildingProcess.java:147)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:141)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:161)
    ... 7 more
Caused by: java.lang.NoClassDefFoundError: javafx/beans/property/ObjectProperty
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: javafx.beans.property.ObjectProperty from [Module "deployment.DevCrowd.war:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
    ... 17 more
</code>```

but if I remove the instantiation

```<code>@MappedSuperclass
public abstract class BaseEntity {
    protected ObjectProperty<Object> loc3;
}
</code>```

It works. This is also for IntegerProperty.

For comparison without javafx beans:

```<code>@MappedSuperclass
public abstract class BaseEntity {
    Object loc3 = new Object();
}
</code>```

works with or without initialization. Why is that?

Edit - runtime config:

Classpath entries:

答:
Going by the comments I read Class Loading in WildFly and according to what's written under Accessing JDK classes I added this jboss-deployment-structure.xml to my src\main\webapp\WEB-INF folder:

```<code><jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
    <deployment>
        <dependencies>
            <system export="true">
                <paths>
                    <path name="javafx/beans/property"/>
                    <path name="javafx/beans/binding"/>
                </paths>
            </system>
        </dependencies>
    </deployment>
</jboss-deployment-structure>
</code>```

Both are needed even though the properties are located under javafx.beans.property probably because their superclasses are in .binding.

Body:
I have the following class in a War. It's also the only class that has any JPA annotations:

@MappedSuperclass
public abstract class BaseEntity {
    protected ObjectProperty<Object> loc3 = new SimpleObjectProperty<>();
}

When I deploy the War I get the following error:

ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 65) MSC000001: Failed to start service jboss.persistenceunit."DevCrowd.war#prod": org.jboss.msc.service.StartException in service jboss.persistenceunit."DevCrowd.war#prod": org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [pl.devcrowd.virtual.business.state.entity.BaseEntity]
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:179)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:121)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:193)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [pl.devcrowd.virtual.business.state.entity.BaseEntity]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:232)
    at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:103)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.<init>(MetadataBuildingProcess.java:147)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:141)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:161)
    ... 7 more
Caused by: java.lang.NoClassDefFoundError: javafx/beans/property/ObjectProperty
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: javafx.beans.property.ObjectProperty from [Module "deployment.DevCrowd.war:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
    ... 17 more

but if I remove the instantiation

@MappedSuperclass
public abstract class BaseEntity {
    protected ObjectProperty<Object> loc3;
}

It works. This is also for IntegerProperty.

For comparison without javafx beans:

@MappedSuperclass
public abstract class BaseEntity {
    Object loc3 = new Object();
}

works with or without initialization. Why is that?

Edit - runtime config:

Classpath entries:

Body:
Going by the comments I read Class Loading in WildFly and according to what's written under Accessing JDK classes I added this jboss-deployment-structure.xml to my src\main\webapp\WEB-INF folder:

<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
    <deployment>
        <dependencies>
            <system export="true">
                <paths>
                    <path name="javafx/beans/property"/>
                    <path name="javafx/beans/binding"/>
                </paths>
            </system>
        </dependencies>
    </deployment>
</jboss-deployment-structure>

Both are needed even though the properties are located under javafx.beans.property probably because their superclasses are in .binding.


问:
Refactoring advice: maps to POJOs
I currently am part of a project where there is an interface like this:

```<code>public interface RepositoryOperation {

    public OperationResult execute(Map<RepOpParam, Object> params);
}
</code>```

This interface has about ~100 implementers.

To call an implementer one needs to do the following:

```<code>final Map<RepOpParam, Object> opParams = new HashMap<RepOpParam, Object>();
opParams.put(ParamName.NAME1, val1);
opParams.put(ParamName.NAME2, val2);
</code>```

Now I think that there is obviously something wrong with anything with a<Something, Object> generic declaration.

Currently this causes a caller of a OperationImpl to have to actually read the code of the operation in order to know how to build the argument map. (and this is not even the worst of the problems, but I don't want to cite them all since they are fairly obvious)

After some discussion I managed to convince my colleagues to let me do some refactoring.

It seems to me that the simplest 'fix' would be to change the interface like so:

```<code>public interface RepositoryOperation {

    public OperationResult execute(OperationParam param);
}
</code>```

After all the concrete operations will define (extend) their own OperationParam and the needed arguments would be visible to everybody. (which is the 'normal way' to do things like that IMHO)

So as I see it since the interface implementers are quite numerous I have several choices:

Try to change the interface and rewrite all the Operation calls to use objects instead of maps. This seems the cleanest, but I think that since the operations are a lot it might be too much work in practice. (~2 weeks with tests probably)

Add an additional method to the interface like so:

```<code>public interface RepositoryOperation {
    public OperationResult execute(Map<String, Object> params);
    public OperationResult execute(OperationParam params);
}
</code>```

and fix the map calls whenever I come across them during functionality implementation.

Live with it (please no !).

So my question is.

Does anyone see a better approach for 'fixing' the maps and if you do would you fix them with method 1 or 2 or not fix them at all.

EDIT:
Thanks for the great answers. I would accept both Max's and Riduidel's answers if I could, but since I can't I'm leaning a bit more towards Riduidel's.

答:
I can see a third way.

You have a map made of <RepOpParam, Object>. If I understand you correctly, what bothers you is the fact that there is no type checking. And obviously, it's not ideal. But, it is possible to move the type-checking issue from the whole parameter (your OperationParam) to individual RepOpParam. Let me explain it.

Suppose your RepOpParam interface (which currently seems like a tagging interface) is modified as it :

```<code>public interface RepOpParam<Value> {
    public Value getValue(Map<RepOpParam, Object> parameters);
}
</code>```

You can then update modern code by replacing old calls to

```<code>String myName = (String) params.get(ParamName.NAME1);
</code>```

with new calls to

```<code>String myName = ParamName.NAME1.getValue(params);
</code>```

The obvious collateral advantage being that you can now have a default value for your parameter, hidden in its very definition.

I have however to make clear that this third way is nothing more than a way to merge your two operations of the second way into only one, respecting old code prototype, while adding new powers in it. As a consequence, I would personnally go the first way, and rewrite all that "stuff", using modern objects (besides, consider taking a look at configuration librarires, which may lead you to interesting anwsers to this problem).

Title: Refactoring advice: maps to POJOs

Body:
I currently am part of a project where there is an interface like this:

public interface RepositoryOperation {

    public OperationResult execute(Map<RepOpParam, Object> params);
}

This interface has about ~100 implementers.

To call an implementer one needs to do the following:

final Map<RepOpParam, Object> opParams = new HashMap<RepOpParam, Object>();
opParams.put(ParamName.NAME1, val1);
opParams.put(ParamName.NAME2, val2);

Now I think that there is obviously something wrong with anything with a<Something, Object> generic declaration.

Currently this causes a caller of a OperationImpl to have to actually read the code of the operation in order to know how to build the argument map. (and this is not even the worst of the problems, but I don't want to cite them all since they are fairly obvious)

After some discussion I managed to convince my colleagues to let me do some refactoring.

It seems to me that the simplest 'fix' would be to change the interface like so:

public interface RepositoryOperation {

    public OperationResult execute(OperationParam param);
}

After all the concrete operations will define (extend) their own OperationParam and the needed arguments would be visible to everybody. (which is the 'normal way' to do things like that IMHO)

So as I see it since the interface implementers are quite numerous I have several choices:

Try to change the interface and rewrite all the Operation calls to use objects instead of maps. This seems the cleanest, but I think that since the operations are a lot it might be too much work in practice. (~2 weeks with tests probably)

Add an additional method to the interface like so:

public interface RepositoryOperation {
    public OperationResult execute(Map<String, Object> params);
    public OperationResult execute(OperationParam params);
}

and fix the map calls whenever I come across them during functionality implementation.

Live with it (please no !).

So my question is.

Does anyone see a better approach for 'fixing' the maps and if you do would you fix them with method 1 or 2 or not fix them at all.

EDIT:
Thanks for the great answers. I would accept both Max's and Riduidel's answers if I could, but since I can't I'm leaning a bit more towards Riduidel's.

Body:
I can see a third way.

You have a map made of <RepOpParam, Object>. If I understand you correctly, what bothers you is the fact that there is no type checking. And obviously, it's not ideal. But, it is possible to move the type-checking issue from the whole parameter (your OperationParam) to individual RepOpParam. Let me explain it.

Suppose your RepOpParam interface (which currently seems like a tagging interface) is modified as it :

public interface RepOpParam<Value> {
    public Value getValue(Map<RepOpParam, Object> parameters);
}

You can then update modern code by replacing old calls to

String myName = (String) params.get(ParamName.NAME1);

with new calls to

String myName = ParamName.NAME1.getValue(params);

The obvious collateral advantage being that you can now have a default value for your parameter, hidden in its very definition.

I have however to make clear that this third way is nothing more than a way to merge your two operations of the second way into only one, respecting old code prototype, while adding new powers in it. As a consequence, I would personnally go the first way, and rewrite all that "stuff", using modern objects (besides, consider taking a look at configuration librarires, which may lead you to interesting anwsers to this problem).


问:
How to set setContentView(); to GONE
I have my main layout which is, setContentView(R.layout.activity_detail),

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
</code>```

how do i set the visibility of my layout as GONE within the below code

```<code>   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }
</code>```

答:
I think actually you are trying to close the current activity while opening a new one.

You can do it as below, no need to hide the current activity.

```<code> Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
 blog .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 blog.putExtra("URL", "url");
 blog.putExtra("filename", "Blog");
 startActivity(blog);
 finish();
</code>```

Title: How to set setContentView(); to GONE

Body:
I have my main layout which is, setContentView(R.layout.activity_detail),

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

how do i set the visibility of my layout as GONE within the below code

   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }

Body:
I think actually you are trying to close the current activity while opening a new one.

You can do it as below, no need to hide the current activity.

 Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
 blog .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 blog.putExtra("URL", "url");
 blog.putExtra("filename", "Blog");
 startActivity(blog);
 finish();


问:
How to get the contents of the first `<li>` from `<ul>` with Beautifulsoup
HTML like below

```<code><div class="carousel">
  <div class="carousel_Wrapper">
    <div class="carousel_Container swiper-container">
      <ul class="swiper-wrapper">
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0001.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0002.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0003.jpg"/></figure>
        </li>
      </ul>
    </div>
    <div class="carousel_NextBtn"></div>
    <div class="carousel_PrevBtn"></div>
  </div>
</div>

<div class="carousel">
  <div class="carousel_Wrapper">
    <div class="carousel_Container swiper-container">
      <ul class="swiper-wrapper">
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0004.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0005.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0006.jpg"/></figure>
        </li>
      </ul>
    </div>
    <div class="carousel_NextBtn"></div>
    <div class="carousel_PrevBtn"></div>
  </div>
</div>
</code>```

I would like to change to HTML like below using BeautifulSoup.

```<code><figure><img alt="" src="https://s3.amazonaws.com/0001.jpg"/></figure>
<p><a href="https://xxxx.jp">other photos</a></p>

<figure><img alt="" src="https://s3.amazonaws.com/0004.jpg"/></figure>
<p><a href="https://xxxx.jp">other photos</a></p>
</code>```

I'm thinking about removing unnecessary  in the following way.

Since there may be other  s, we are specifying the class and doing decoponse (), unwrap ().

```<code>html = # First mentioned html

content = BeautifulSoup(html)

content.find('div', class_='carousel_NextBtn').decompose()
content.find('div', class_='carousel').unwrap()
content.find('div', class_='carousel_Wrapper').unwrap()
content.find('div', class_='carousel_Container swiper-container').unwrap()
</code>```

When applying the above processing, I think that html as shown below will be generated.

```<code><ul class="swiper-wrapper">
  <li class="swiper-slide">
    <figure><img alt="" src="https://s3.amazonaws.com/0001.jpg"/></figure>
  </li>
  <li class="swiper-slide">
    <figure><img alt="" src="https://s3.amazonaws.com/0002.jpg"/></figure>
  </li>
  <li class="swiper-slide">
    <figure><img alt="" src="https://s3.amazonaws.com/0003.jpg"/></figure>
  </li>
</ul>
<div class="carousel_PrevBtn"></div>

<ul class="swiper-wrapper">
  <li class="swiper-slide">
    <figure><img alt="" src="https://s3.amazonaws.com/0004.jpg"/></figure>
  </li>
    <li class="swiper-slide">
  <figure><img alt="" src="https://s3.amazonaws.com/0005.jpg"/></figure>
  </li>
    <li class="swiper-slide">
  <figure><img alt="" src="https://s3.amazonaws.com/0006.jpg"/></figure>
  </li>
</ul>
<div class="carousel_PrevBtn"></div>
</code>```

We believe that the necessary processing is as follows from here.

1.Retrieve the content of the first
 element of each

2.Insert
other photos

For 2, I think that there is no problem by replacing  .

But I do not know how to implement 1.

Please show the way to solve it.

答:
```<code>html = """<div class="carousel">
  <div class="carousel_Wrapper">
    <div class="carousel_Container swiper-container">
      <ul class="swiper-wrapper">
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0001.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0002.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0003.jpg"/></figure>
        </li>
      </ul>
    </div>
    <div class="carousel_NextBtn"></div>
    <div class="carousel_PrevBtn"></div>
  </div>
</div>

<div class="carousel">
  <div class="carousel_Wrapper">
    <div class="carousel_Container swiper-container">
      <ul class="swiper-wrapper">
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0004.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0005.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0006.jpg"/></figure>
        </li>
      </ul>
    </div>
    <div class="carousel_NextBtn"></div>
    <div class="carousel_PrevBtn"></div>
  </div>
</div>"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
all_div = soup.find_all('ul', {'class': 'swiper-wrapper'})  # find all ul tag with specified class
for tag in all_div:
    print('-------------------- iteration : ' + str(all_div.index(tag)) + ' --------------------')
    print(tag.find('li', {'class': 'swiper-slide'}))  # this method works only if your item has class
    print(tag.contents[1])  # this method will also work if your item don't have a class
</code>```

Your solution for "Retrieve the content of the first
 element of each
" can be achieved as shown in above code. you didn't face any problem for 2nd one so I haven't posted it yet. If you need any help on this let me know.

Body:
HTML like below

I would like to change to HTML like below using BeautifulSoup.

other photos

other photos

I'm thinking about removing unnecessary  in the following way.

Since there may be other  s, we are specifying the class and doing decoponse (), unwrap ().

html = # First mentioned html

content = BeautifulSoup(html)

content.find('div', class_='carousel_NextBtn').decompose()
content.find('div', class_='carousel').unwrap()
content.find('div', class_='carousel_Wrapper').unwrap()
content.find('div', class_='carousel_Container swiper-container').unwrap()

When applying the above processing, I think that html as shown below will be generated.

We believe that the necessary processing is as follows from here.

1.Retrieve the content of the first
 element of each

2.Insert
other photos

For 2, I think that there is no problem by replacing  .

But I do not know how to implement 1.

Please show the way to solve it.

Body:
html = """<div class="carousel">
  <div class="carousel_Wrapper">
    <div class="carousel_Container swiper-container">
      <ul class="swiper-wrapper">
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0001.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0002.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0003.jpg"/></figure>
        </li>
      </ul>
    </div>
    <div class="carousel_NextBtn"></div>
    <div class="carousel_PrevBtn"></div>
  </div>
</div>

<div class="carousel">
  <div class="carousel_Wrapper">
    <div class="carousel_Container swiper-container">
      <ul class="swiper-wrapper">
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0004.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0005.jpg"/></figure>
        </li>
        <li class="swiper-slide">
          <figure><img alt="" src="https://s3.amazonaws.com/0006.jpg"/></figure>
        </li>
      </ul>
    </div>
    <div class="carousel_NextBtn"></div>
    <div class="carousel_PrevBtn"></div>
  </div>
</div>"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
all_div = soup.find_all('ul', {'class': 'swiper-wrapper'})  # find all ul tag with specified class
for tag in all_div:
    print('-------------------- iteration : ' + str(all_div.index(tag)) + ' --------------------')
    print(tag.find('li', {'class': 'swiper-slide'}))  # this method works only if your item has class
    print(tag.contents[1])  # this method will also work if your item don't have a class

Your solution for "Retrieve the content of the first <li> element of each <ul>" can be achieved as shown in above code. you didn't face any problem for 2nd one so I haven't posted it yet. If you need any help on this let me know.


问:
How to add a column with values corresponding to another column?
I will summarize how I got the dataframes I work with:

```<code>     name abundance
1    joe  1
2    tim  1
3    bob  1
4    joe  1
5    bob  1
</code>```

First I created a new dataframe by aggregating the columns and calculated what the relative freqeuency would be:

```<code>     name  abundance  relative_ab
1    joe   2          0.4
2    tim   1          0.2
3    bob   2          0.4
</code>```

But I want to add a column to the first dataframe so that there are redundant entries with the relative_ab like so (the actual data set has other information in it and I would lose the information by aggregating them).

```<code>     name abundance relative_ab
1    joe  1         0.4
2    tim  1         0.2
3    bob  1         0.4
4    joe  1         0.4
5    bob  1         0.4
</code>```

I think I could brute force this but I am relatively new to R and wondering what slick ways you guys might come up with.

Thanks!

答:
We can do this with data.table

```<code>library(data.table)
setDT(df)[, relative_ab := sum(abundance)/sum(df$abundance) , name]
df
#   name abundance relative_ab
#1:  joe         1         0.4
#2:  tim         1         0.2
#3:  bob         1         0.4
#4:  joe         1         0.4
#5:  bob         1         0.4
</code>```

Body:
I will summarize how I got the dataframes I work with:

     name abundance
1    joe  1
2    tim  1
3    bob  1
4    joe  1
5    bob  1

First I created a new dataframe by aggregating the columns and calculated what the relative freqeuency would be:

     name  abundance  relative_ab
1    joe   2          0.4
2    tim   1          0.2
3    bob   2          0.4

But I want to add a column to the first dataframe so that there are redundant entries with the relative_ab like so (the actual data set has other information in it and I would lose the information by aggregating them).

     name abundance relative_ab
1    joe  1         0.4
2    tim  1         0.2
3    bob  1         0.4
4    joe  1         0.4
5    bob  1         0.4

I think I could brute force this but I am relatively new to R and wondering what slick ways you guys might come up with.

Thanks!

Body:
We can do this with data.table

library(data.table)
setDT(df)[, relative_ab := sum(abundance)/sum(df$abundance) , name]
df
#   name abundance relative_ab
#1:  joe         1         0.4
#2:  tim         1         0.2
#3:  bob         1         0.4
#4:  joe         1         0.4
#5:  bob         1         0.4


问:
Using beautiful soup to obtain class contents with a conditional
I would like to use beautiful soup to find tags where the child tags(gains or losses) are greater than 0. I would then like to print the contents of the inner tags "gains" "losses" and "band.textualrepresentation". This is essentially the script I want (although this one doesn't work).

```<code>import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup('anytype', 'gains'.string>0 || 'losses'.string>0):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain loss band

parseLog(sys.argv[1])
</code>```

I am running into troubles early on, I can't even print the contents of gains, let alone print the contents that meet a certain criteria. My current Script

```<code>def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup.findall('anytype'):
                gain = anytype.fetch('gains')
                print gain

parseLog(sys.argv[1])
</code>```

returns

```<code>Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup.findall('anytype'):
TypeError: 'NoneType' object is not callable
</code>```

.

Sample Input

```<code>      <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.1
          </textualrepresentation>
         </band>
         <gains>
          2
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.2
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q12
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          0
         </losses>
         <structs>
          0
         </structs>
        </anytype>
</code>```

Sample output

```<code>2  1  22q11.1
0  1  22q11.2
</code>```

.

.

Update
The current solution

```<code>import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain, loss, band

parseLog(sys.argv[1])
</code>```

Still returns the error

```<code>Traceback (most recent call last):
  File "./soup.py", line 15, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 659, in __call__
    return apply(self.findAll, args, kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 849, in findAll
    return self._findAll(name, attrs, text, limit, generator, **kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 377, in _findAll
    found = strainer.search(i)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 966, in search
    found = self.searchTag(markup)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 924, in searchTag
    or (markup and self._matches(markup, self.name)) \
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 983, in _matches
    result = matchAgainst(markup)
  File "./soup.py", line 9, in <lambda>
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
AttributeError: 'NoneType' object has no attribute 'string'
</code>```

Even when I reduce the for loop to

```<code>for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains'))):
        gain = anytype.gains.string
        print gain
</code>```

I still get

```<code>Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 10, in parseLog
    gain = anytype.gains.string
AttributeError: 'NoneType' object has no attribute 'string'
</code>```

答:
The code should be:

```<code>for anytype in soup(lambda x: x.name=='anytype' and (int(x.gains.string) > 0 or int(x.losses.string) > 0)):
    gain = anytype.gains.string
    loss = anytype.losses.string
    band = anytype.band.textualrepresentation.string
    print gain loss band
</code>```

python || is or and we need to convert string to number before perform integer comparison, e.g. int(x.gains.string). Hope this help.

Body:
I would like to use beautiful soup to find tags where the child tags(gains or losses) are greater than 0. I would then like to print the contents of the inner tags "gains" "losses" and "band.textualrepresentation". This is essentially the script I want (although this one doesn't work).

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup('anytype', 'gains'.string>0 || 'losses'.string>0):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain loss band

parseLog(sys.argv[1])

I am running into troubles early on, I can't even print the contents of gains, let alone print the contents that meet a certain criteria. My current Script

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup.findall('anytype'):
                gain = anytype.fetch('gains')
                print gain

parseLog(sys.argv[1])

returns

Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup.findall('anytype'):
TypeError: 'NoneType' object is not callable

.

Sample Input

      <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.1
          </textualrepresentation>
         </band>
         <gains>
          2
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.2
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q12
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          0
         </losses>
         <structs>
          0
         </structs>
        </anytype>

Sample output

2  1  22q11.1
0  1  22q11.2

.

.

Update
The current solution

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain, loss, band

parseLog(sys.argv[1])

Still returns the error

Traceback (most recent call last):
  File "./soup.py", line 15, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 659, in __call__
    return apply(self.findAll, args, kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 849, in findAll
    return self._findAll(name, attrs, text, limit, generator, **kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 377, in _findAll
    found = strainer.search(i)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 966, in search
    found = self.searchTag(markup)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 924, in searchTag
    or (markup and self._matches(markup, self.name)) \
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 983, in _matches
    result = matchAgainst(markup)
  File "./soup.py", line 9, in <lambda>
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
AttributeError: 'NoneType' object has no attribute 'string'

Even when I reduce the for loop to

for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains'))):
        gain = anytype.gains.string
        print gain

I still get

Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 10, in parseLog
    gain = anytype.gains.string
AttributeError: 'NoneType' object has no attribute 'string'

Body:
The code should be:

for anytype in soup(lambda x: x.name=='anytype' and (int(x.gains.string) > 0 or int(x.losses.string) > 0)):
    gain = anytype.gains.string
    loss = anytype.losses.string
    band = anytype.band.textualrepresentation.string
    print gain loss band

python || is or and we need to convert string to number before perform integer comparison, e.g. int(x.gains.string). Hope this help.


问:
C# How to pass Datatable results in one array variable
Good day!

I am trying to achieve to convert all datatable result in one array variable. I searched multiple times, but still cannot achieve my desired result.

Server side code:

```<code>List<string> holidays = holiday.AsEnumerable().Select(r => r.Field<string>("holiday_date")).ToList();
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "applyCss(" + holidays + ")", true);
</code>```

Client side code:

```<code>        var applyCss = function (param1) {

        var paramlength = param1.length;

        for (var i = 0; i < paramlength; i++)
        {
            var css = "#CalendarPanel1-month-day-" + param1 + " {background-color: pink;}";
            Ext.net.ResourceMgr.registerCssClass("script" + i, css);
        }
</code>```

I am not sure if I am doing it right using List. I used var[] but it returns an error.

Will appreciate suggestions / comments / solutions. Thank you very much!

答:
I have created a temp datatable for this.

Html file where function gets comma separated value after that you can split and use according to your requirement.

Image Url:- https://i.stack.imgur.com/F6Tae.png
Image Url:- https://i.stack.imgur.com/ZiAhT.png

Body:
Good day!

I am trying to achieve to convert all datatable result in one array variable. I searched multiple times, but still cannot achieve my desired result.

Server side code:

List<string> holidays = holiday.AsEnumerable().Select(r => r.Field<string>("holiday_date")).ToList();
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "applyCss(" + holidays + ")", true);

Client side code:

        var applyCss = function (param1) {

        var paramlength = param1.length;

        for (var i = 0; i < paramlength; i++)
        {
            var css = "#CalendarPanel1-month-day-" + param1 + " {background-color: pink;}";
            Ext.net.ResourceMgr.registerCssClass("script" + i, css);
        }

I am not sure if I am doing it right using List. I used var[] but it returns an error.

Will appreciate suggestions / comments / solutions. Thank you very much!


问:
How to change the case of all characters in a text file to lowercase in java?
So if the contents of a text file is FCCCC, the output of the same text file should be fcccc.

I have written the following code

```<code>  import java.lang.*;
  import java.io.*;
  import java.io.FileWriter;
  import java.io.IOException;
  class A
  {
   public static void main(String args[]) throws IOException
   {
      try
      {
            FileReader reader = new FileReader("doc1.txt");
            FileWriter writer = new FileWriter("doc1.txt", true);
            int character=' ';
            char m;
            while ((character = reader.read()) != -1)
            {
                m=Character.toLowerCase((char)character);
                System.out.println(m);
                writer.write(m);
            }
            reader.close();
            writer.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
 }
</code>```

In the code above if the contents of the text file are FCCCC then the output is FCCCCfcccc.

What is the mistake in the code?

答:
Try this :

```<code>import java.io.*;

public class TextFile {
    public static void main (String[] args) throws IOException {
            File file1 = new File("intext.txt");
            File file2 = new File("outtext.txt");
            char CharCounter = 0;
            BufferedReader in = (new BufferedReader(newFileReader(file1)));
            PrintWriter out = (new PrintWriter(new FileWriter(file2)));

            int ch;
            while ((ch = in.read()) != -1){

                if (Character.isUpperCase(ch)){
                    Character.toLowerCase(ch);

                }
                out.write(ch);

            }
            in.close();
            out.close();
        }
    }
</code>```

and the delete old text and rename the new one.

Body:
So if the contents of a text file is FCCCC, the output of the same text file should be fcccc.

I have written the following code

  import java.lang.*;
  import java.io.*;
  import java.io.FileWriter;
  import java.io.IOException;
  class A
  {
   public static void main(String args[]) throws IOException
   {
      try
      {
            FileReader reader = new FileReader("doc1.txt");
            FileWriter writer = new FileWriter("doc1.txt", true);
            int character=' ';
            char m;
            while ((character = reader.read()) != -1)
            {
                m=Character.toLowerCase((char)character);
                System.out.println(m);
                writer.write(m);
            }
            reader.close();
            writer.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
 }

In the code above if the contents of the text file are FCCCC then the output is FCCCCfcccc.

What is the mistake in the code?

Body:
Try this :

import java.io.*;

public class TextFile {
    public static void main (String[] args) throws IOException {
            File file1 = new File("intext.txt");
            File file2 = new File("outtext.txt");
            char CharCounter = 0;
            BufferedReader in = (new BufferedReader(newFileReader(file1)));
            PrintWriter out = (new PrintWriter(new FileWriter(file2)));

            int ch;
            while ((ch = in.read()) != -1){

                if (Character.isUpperCase(ch)){
                    Character.toLowerCase(ch);

                }
                out.write(ch);

            }
            in.close();
            out.close();
        }
    }

and the delete old text and rename the new one.


问:
Does trend suggest server-side web programming model (e.g. ASP.NET) being replaced by JavaScript/Ajax?
ASP.NET server controls has a few categories, for example, normal ones e.g. TextBox, Button which can be done in HTML/JS; Validation controls: can be done in JS; Login controls: I have seen them implemented in JS. Data bound controls: not sure, but maybe JS can work directly with databases, implementing controls like photo slider.

So in the time span of next 5-10 years, will server-side web programming model fall out of mainstream and be replaced by JS/Ajax that interacts directly with databases?

答:
Unless you are talking about a database on the users machine, then there will need to be something on the server end to connect to the database (unless you leave your database open to the public internet, which is never a good idea if it can be helped).

It seems that with technology, it is always a pendulum.  Client side has one set of benefits and costs while server side has a different set.  Usually if everything is heavy on the server side, then people feel that pain, and start to look at client side for the answer.  Then the pendulum swings the other way and client side is popular.  But then people begin to feel the pain of the cost of client side, and server side starts to look very good, so the pendulum swings back the other way.

So while 5-10 years down the road it may be heavy on the client side, in another 5-10 years it may be heavy on the server side again.

Just my two cents.


问:
How to trace "Parse error: syntax error" in a PHP program?
I've tried repl, linter and can't find what's missing. I am new to PHP.

Error:Parse error: syntax error, unexpected $end on line 62

'Line 62' is the last line of code and it's for an email form for my site

Code:

```<code><?php
if(isset($_POST['email'])) {

   $email_to = "(my email is in here)";
   $email_subject = "Enquiry";

   // validation expected data exists
   if(!isset($_POST['first_name']) ||
       !isset($_POST['email']) ||
       !isset($_POST['comments'])) {
       died('We are sorry, but there appears to be a problem with the form you submitted.');
   }

   $first_name = $_POST['first_name']; // required

   $email_from = $_POST['email']; // required
   $comments = $_POST['comments']; // required

   $error_message = "";
   $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 if(!preg_match($email_exp,$email_from)) {
   $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
 }
   $string_exp = "/^[A-Za-z\s.'-]+$/";
 if(!preg_match($string_exp,$first_name)) {
   $error_message .= 'The First Name you entered does not appear to be valid.<br />';
 }

 if(strlen($comments) < 2) {
   $error_message .= 'The Comments you entered do not appear to be valid.<br />';
 }
 if(strlen($error_message) > 0) {
   died($error_message);
 }
   $email_message = "Details below.\n\n";

   function clean_string($string) {
     $bad = array("content-type","bcc:","to:","cc:","href");
     return str_replace($bad,"",$string);
   }

   $email_message .= "First Name: ".clean_string($first_name)."\n";

   $email_message .= "Email: ".clean_string($email_from)."\n";
   $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_to."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
sleep(1);
echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com">";
?>

<?php
}
?>-->
</code>```

答: You missed '}' in the end of script. You started condition if(isset($_POST['email'])) { but didn't close it.

Body:
I've tried repl, linter and can't find what's missing. I am new to PHP.

Error:Parse error: syntax error, unexpected $end on line 62

'Line 62' is the last line of code and it's for an email form for my site

Code:

<?php
if(isset($_POST['email'])) {

   $email_to = "(my email is in here)";
   $email_subject = "Enquiry";

   // validation expected data exists
   if(!isset($_POST['first_name']) ||
       !isset($_POST['email']) ||
       !isset($_POST['comments'])) {
       died('We are sorry, but there appears to be a problem with the form you submitted.');
   }

   $first_name = $_POST['first_name']; // required

   $email_from = $_POST['email']; // required
   $comments = $_POST['comments']; // required

   $error_message = "";
   $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 if(!preg_match($email_exp,$email_from)) {
   $error_message .= 'The Email Address you entered does not appear to be valid.
';
 }
   $string_exp = "/^[A-Za-z\s.'-]+$/";
 if(!preg_match($string_exp,$first_name)) {
   $error_message .= 'The First Name you entered does not appear to be valid.
';
 }

 if(strlen($comments) < 2) {
   $error_message .= 'The Comments you entered do not appear to be valid.
';
 }
 if(strlen($error_message) > 0) {
   died($error_message);
 }
   $email_message = "Details below.\n\n";

   function clean_string($string) {
     $bad = array("content-type","bcc:","to:","cc:","href");
     return str_replace($bad,"",$string);
   }

   $email_message .= "First Name: ".clean_string($first_name)."\n";

   $email_message .= "Email: ".clean_string($email_from)."\n";
   $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_to."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
sleep(1);
echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com">";
?>

<?php
}
?>-->


问:
Cells image view width will not change
I have an image view in a cell and I've change the multiplier so that the width changes depending on the screen size. But the problem is that the width doesnt change accordingly. The width is a ratio of the cells width and the width remains constant to that of my xib width. So my width never changes and the width only appears fine for one of the screen sizes but not the rest. How can I update my width of my image view. There is an image of my auto layout below. I also called layout if needed for my image view and the image view shrinks and does funky stuff so that doesnt work. Below is a picture of the auto layout for the image views width.

答: Instead of using "ratio", try use "equal width" then set the multiplier to 0.3 for 30% from screen width or if you prefer 40%, make it 0.4.</p>

Title: Cells image view width will not change


问:
Swift cross compile to single linux binary
Is it possible to compile a swift binary from an OS X computer so that it runs on a server running Linux as a single binary without no extra libraries that need to be dynamically linked?

I'm thinking something like passing a -target to the swift command and passing another parameter to let it statically link all dependencies, but I'm not sure what the exact commands are.

The exact value for -target seems to be rather elusive.

Do I need to know the exact target distribution to be able to pass the correct string to the -target parameter?

答:
Is it possible to compile a swift binary from an OS X computer so that it runs on a server running Linux as a single binary without no extra libraries that need to be dynamically linked?

The short answer? Of course it is! Anything is possible when you put your heart to it!

Is it efficient? Inherently, no.

While I'm sure everyone here is familiar with what a compiler does, for the sake of this question and its newest of users, a compiler is an application that converts human readable code and maps it to a binary format that a computer can understand. However it should be worth mentioning that not all computers are the same. Each computer operating system has a different binary mapping than the other so a simple operation like copying values could be expressed as 1010 on one machine, and 0101 on another. As stated before in many questions prior, and for example this one, many programming languages are buildable across a variety of machines, but very few of them are portable across them because each computer has a different binary mapping.

~~~~~~~
So how do we fix this?
~~~~~~~

Well there are a number of solutions to fix this. The most obvious
method is to simply make your environment the target environment and
build your program to your hearts content. You obviously already did
this through a virtual machine and this typically what many
developers will do. This is by far the easiest solution but it
defeats the purpose of the question where you want to simply build
from your OSX machine.

Earlier you said you heard people talking about compiling windows programs on linux machines. Cygwin is a a development platform aimed at obtaining the windows framework that is not normally present on linux machines and allows many programs to be built with the windows framework in mind. However all its doing is adding binaries so that the compiler has some proper places to map to when windows only commands are found within a configuration. All its doing is introducing the binary configurations necessary for a program to successfully be ported over. This ties into the second option.

Secondly comes a compiler that supports cross platform compilation.
While I am currently uninformed and/or unfamiliar with such
compilers, this is technically a valid solution but would I call it
reliable? Probably not. If anything you're just adding more work to
your compiler as not only does it have to correctly map the syntax of
one computer program for one computer, it has to waste time linking
it to the new binaries. Additionally you would need to have the
compiler remember these linking's which could entail more wasted
memory space for having this one compiler.

Even then, systems like these are few and far between and whether its guaranteed to work depends upon how well the compilers maintainer knows their stuff, how frequently they update it etc. etc. And the chances that they even performed to correct mappings of binaries in the first place is not something I'd stake my life on.

The third and perhaps most ideal solution is to look into container technologies such as docker. Their containers are essentially ways for you to build your app and port it to new machines without having to change or modify anything about how you build and compile it. Simply build one, store it in a container, port it to your machine of choice and integrate it into your current project. Come to think of it, container systems like docker were built to prevent the very thing that you are currently experiencing, where you have a source code working on your one machine but no place else. Something like docker will be able to run your code on any machine without having to recompile it for each new machine.

Docker provides an interesting framework for container to container communication, application examples and has a fairly straightforward documentation that it would be worthwhile to look at to see if your project could have some of its parts ported to docker.

This being said, there are multiple ways to fix the issue you are currently facing, so as you being a software engineer, its up to you in what would be the most ideal way of handling your project.

// EDIT //

Will edit this to be a better response once im not drop-dead tired.