问:
python string splitting with multiple splitting points
Ok so ill get straight to the point here is my code

```<code>def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment
</code>```

Input for this function is a list of multiple strings (seq) e.g. :

```<code>List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
</code>```

And enzymes as input:

```<code>[["TC", 1],["GC",1]]
</code>```

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

```<code>Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]
</code>```

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

答:
Here is something that should work using regex. In this solution, I find all occurrences of your enzyme strings and split using their corresponding index.</p>

```<code>def digestfragmentwithenzyme(seqs, enzymes):
    out = []
    dic = dict(enzymes) # dictionary of enzyme indices

    for seq in seqs:
        sub = []
        pos1 = 0

        enzstr = '|'.join(enz[0] for enz in enzymes) # "TC|GC" in this case
        for match in re.finditer('('+enzstr+')', seq):
            index = dic[match.group(0)]
            pos2 = match.start()+index
            sub.append(seq[pos1:pos2])
            pos1 = pos2
        sub.append(seq[pos1:])
        out.append(sub)
        # [['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'], ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAAAAAAT', 'C']]
    return out
</code>```

Body:
Ok so ill get straight to the point here is my code

def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment

Input for this function is a list of multiple strings (seq) e.g. :

List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]

And enzymes as input:

[["TC", 1],["GC",1]]

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

Body:
Here is something that should work using regex. In this solution, I find all occurrences of your enzyme strings and split using their corresponding index.

def digestfragmentwithenzyme(seqs, enzymes):
    out = []
    dic = dict(enzymes) # dictionary of enzyme indices

    for seq in seqs:
        sub = []
        pos1 = 0

        enzstr = '|'.join(enz[0] for enz in enzymes) # "TC|GC" in this case
        for match in re.finditer('('+enzstr+')', seq):
            index = dic[match.group(0)]
            pos2 = match.start()+index
            sub.append(seq[pos1:pos2])
            pos1 = pos2
        sub.append(seq[pos1:])
        out.append(sub)
        # [['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'], ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAAAAAAT', 'C']]
    return out


来源: stackexchange

问:
Bootstrap Button Group Show/Hide Div
I've got a Bootstrap button group that has 2 buttons (JSON and XML) with JSON being active when the page is loaded.  Pressing the XML button will automatically change focus to it.

Now, I'd like to attach some behavior to these buttons so that clicking the XML button hides the error-json pre element and shows the error-xml pre element.

Is there a Bootstrap-native way to accomplish this?

```<code><div class="btn-group">
    <button class="btn btn-default" autofocus="true">JSON</button>
    <button class="btn btn-default">XML</button>
</div>

<pre id="error-json" class="hidden"><code class="language-json">{
  "ErrorCode": STATUS_CODE,
  "Description": ERROR_MSG
}</code>```

<error>
  <ErrorCode>STATUS_CODE</ErrorCode>
  <Description>ERROR_MSG</Description>
</error>
```
</code>```

答:
I think this can be accomplished with css dependencies. You can use the css selector #error-json + #error-xml {
/*something here*/
}

Bootstrap has pre-builtin classes to show/hide elements. You find the classes in the documentation:
http://getbootstrap.com/css/#helper-classes-show-hide

Maybe this thread helps out:
On a CSS hover event, can I change another div's styling?

Why do you dont want to use javascript/jQuery to add the desired behaviour?

Regards

ContentLicense: CC BY-SA 3.0

Title: Bootstrap Button Group Show/Hide Div

Body:
I've got a Bootstrap button group that has 2 buttons (JSON and XML) with JSON being active when the page is loaded.  Pressing the XML button will automatically change focus to it.

Now, I'd like to attach some behavior to these buttons so that clicking the XML button hides the error-json pre element and shows the error-xml pre element.

Is there a Bootstrap-native way to accomplish this?

    <button class="btn btn-default" autofocus="true">JSON</button>
    <button class="btn btn-default">XML</button>

{
  "ErrorCode": STATUS_CODE,
  "Description": ERROR_MSG
}

<error>
  <ErrorCode>STATUS_CODE</ErrorCode>
  <Description>ERROR_MSG</Description>
</error>


问:
How to add
 with  link into a textarea as simple text?
I would like to be able to add links with an  tag based on user input.

HTML

```<code><div id="linkRef">
  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>
  <ul class="main_ul">
  </ul>
</div>

<div id="linkData">
  <textarea></textarea>
</div>
</code>```

JS

```<code>$('body').on('click', 'button.link-list', function() {
  $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('<li><div class="form-group"><input  placeholder="Dai un nome al link...." class="link_name form-control" type="text"></div><div class="form-group"><input placeholder="inserisci il link..." class="form-control" type="text"></div></li>')
  );
});

function updateTree() {
   var myLinks = $("#linkRef ul");
   $("#linkData textarea").val(myLinks.html() + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);
</code>```

The above inserts the added list but it inserts the inputs and buttons and all the html in it too, yet not the actual values, i didn't insert the  code as i was trying to work out the basic first.

The output within the textarea that I am expecting would be:

```<code><ul>
   <li>
     <a href="www.example.com">Example</a>
   </li>
   <li>
     <a href="www.example2.com">Example2</a>
   </li>
</ul>
</code>```

I made a JsFiddle playground

And this is another JsFiddle for another case I had and I was trying to work this new question out based on that but i didn't manage it

答:
This is how I resolved it:

```<code><div id="myList">
  <ul>
    <li><button class="btn btn-default ul-appending">+ Node</button>      </li>
  </ul>
</div>

<div id="listData">
  <textarea col="10" rows="10"></textarea>
</div>

$('body').on('click', 'button.ul-appending', function() {
    $(this).parent().append(
    $('<ul class="main_ul">').addClass('newul sortable').append(
    $('<li><div class="form-group"><input placeholder="Link title" class="nome_link form-control" type="text"></div><div class="form-group"><input placeholder="Link" class="form-control link_url" type="text"></div></li>')
    )
    );
});

$('body').on('click', 'button.removeThis', function() {
    $(this).parent().parent().parent().remove();
});

function updateTree() {
   $("#listData textarea").text('<li><a href="' + $("#myList input.link_url").val() + '">' + $("#myList input.nome_link").val() + '</a></li>');
 }

$("#myList").on("DOMSubtreeModified", updateTree);
$("#myList").on('keyup', 'input', updateTree);
</code>```

JsFiddle

Title: How to add <ul> with <a> link into a textarea as simple text?

Body:
I would like to be able to add links with an  tag based on user input.

HTML

  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>

  <textarea></textarea>

JS

$('body').on('click', 'button.link-list', function() {
  $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('

<input  placeholder="Dai un nome al link...." class="link_name form-control" type="text">

<input placeholder="inserisci il link..." class="form-control" type="text">

')
  );
});

function updateTree() {
   var myLinks = $("#linkRef ul");
   $("#linkData textarea").val(myLinks.html() + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);

The above inserts the added list but it inserts the inputs and buttons and all the html in it too, yet not the actual values, i didn't insert the  code as i was trying to work out the basic first.

The output within the textarea that I am expecting would be:

     Example

     Example2

I made a JsFiddle playground

And this is another JsFiddle for another case I had and I was trying to work this new question out based on that but i didn't manage it

Body:
This is how I resolved it:

<div id="myList">
  <ul>
    <li><button class="btn btn-default ul-appending">+ Node</button>      </li>
  </ul>
</div>

<div id="listData">
  <textarea col="10" rows="10"></textarea>
</div>

$('body').on('click', 'button.ul-appending', function() {
    $(this).parent().append(
    $('<ul class="main_ul">').addClass('newul sortable').append(
    $('<li><div class="form-group"><input placeholder="Link title" class="nome_link form-control" type="text"></div><div class="form-group"><input placeholder="Link" class="form-control link_url" type="text"></div></li>')
    )
    );
});

$('body').on('click', 'button.removeThis', function() {
    $(this).parent().parent().parent().remove();
});

function updateTree() {
   $("#listData textarea").text('<li><a href="' + $("#myList input.link_url").val() + '">' + $("#myList input.nome_link").val() + '</a></li>');
 }

$("#myList").on("DOMSubtreeModified", updateTree);
$("#myList").on('keyup', 'input', updateTree);

JsFiddle


问:
Clickatell HTTP API send message fails with Routing Error (Status 9)
I have recently converted a trial account into a paid starter package and, since I've been assigned a long number, my attempts to send messages via the HTTP API have failed with the following messages in the Message Reports console:

An error occurred while attempting to route the message

Routing error (status 9)

I have confirmed that my username, password, and api id are entered correctly and that the long number has been matched to the active API. I've tried the "Valid Sample Code" provided on the API management console, all with the same result. Below are a few failed message ids if that's helpful for anyone on the Clickatell team.

6d7868662782cfd7d1708996bca066b1
4f837467ed535521ef39d9d885f121f9
2be08f4663a3d9d7cf2e5b9e9cad2d5f

For what it's worth, my trial account worked fine and as expected, so I'm fairly certain that this is not (obvious) user error on my part. I also upgraded a few hours ago; I'm not sure if there is a wait period between account activation and functional service. Thanks for any help on this.

答:
make sure you dont add any programming symbols in the text message. i had an exclamation mark and it gave me a status 9 error.</p>

```<code>http://api.clickatell.com/http/sendmsg?api_id=xxxx&user=xxxx&from=13055140341&mo=1&password=xxxx&to=xxxx&text=xxxx
</code>```

Body:
make sure you dont add any programming symbols in the text message. i had an exclamation mark and it gave me a status 9 error.

http://api.clickatell.com/http/sendmsg?api_id=xxxx&user=xxxx&from=13055140341&mo=1&password=xxxx&to=xxxx&text=xxxx


问:
Using 'Lock' in web applications
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

```<code>lock(HitCounter)
{
   // Bla...
}
</code>```

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?

答: This code will create a bottleneck for your application since all incoming request will have to wait at this point before the previous went out of the lock.</p>

ContentLicense: CC BY-SA 2.5

Title: Using 'Lock' in web applications

Body:
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

lock(HitCounter)
{
   // Bla...
}

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?


问:
Output to a text file
I need to output lots of different datasets to different text files. The datasets share some common variables that need to be output but also have quite a lot of different ones. I have loaded these different ones into a macro variable separated by blanks so that I can macroize this.

So I created a macro which loops over the datasets and outputs each into a different text file.

For this purpose, I used a put statement inside a data step. The PUT statement looks like this:

```<code>PUT (all the common variables shared by all the datasets), (macro variable containing all the dataset-specific variables);
</code>```

E.g.:

```<code>%MACRO OUTPUT();
    %DO N=1 %TO &TABLES_COUNT;
        DATA _NULL_;
            SET &&TABLE&N;
            FILE 'PATH/&&TABLE&N..txt';
            PUT a b c d "&vars";
        RUN;
    %END;
%MEND OUTPUT;
</code>```

Where &vars is the macro variable containing all the variables needed for outputting for a dataset in the current loop.
Which gets resolved, for example, to:

```<code>PUT a b c d special1 special2 special5 ... special329;
</code>```

Now the problem is, the quoted string can only be 262 characters long. And some of my datasets I am trying to output have so many variables to be output that this macro variable which is a quoted string and holds all those variables will be much longer than that. Is there any other way how I can do this?

答:
Not sure why you're talking about quoted strings: you would not quote the &vars argument.

```<code>put a b c d &vars;
</code>```

not

```<code>put a b c d "&vars";
</code>```

There's a limit there, but it's much higher (64k).

That said, I would do this in a data driven fashion with CALL EXECUTE.  This is pretty simple and does it all in one step, assuming you can easily determine which datasets to output from the dictionary tables in a WHERE statement.  This has a limitation of 32kiB total, though if you're actually going to go over that you can work around it very easily (you can separate out various bits into multiple calls, and even structure the call so that if the callstr hits 32000 long you issue a call execute with it and then continue).

This avoids having to manage a bunch of large macro variables (your &VAR will really be &&VAR&N and will be many large macro variables).

```<code>data test;
  length vars callstr $32767;
  do _n_ = 1 by 1 until (last.memname);
    set sashelp.vcolumn;
    where memname in ('CLASS','CARS');
    by libname memname;
    vars = catx(' ',vars,name);
  end;
  callstr = catx(' ',
    'data _null_;',
    'set',cats(libname,'.',memname),';',
    'file',cats('"c:\temp\',memname,'.txt"'),';',
    'put',vars,';',
    'run;');
    call execute(callstr);
run;
</code>```

Title: Output to a text file

Body:
I need to output lots of different datasets to different text files. The datasets share some common variables that need to be output but also have quite a lot of different ones. I have loaded these different ones into a macro variable separated by blanks so that I can macroize this.

So I created a macro which loops over the datasets and outputs each into a different text file.

For this purpose, I used a put statement inside a data step. The PUT statement looks like this:

PUT (all the common variables shared by all the datasets), (macro variable containing all the dataset-specific variables);

E.g.:

%MACRO OUTPUT();
    %DO N=1 %TO &TABLES_COUNT;
        DATA _NULL_;
            SET &&TABLE&N;
            FILE 'PATH/&&TABLE&N..txt';
            PUT a b c d "&vars";
        RUN;
    %END;
%MEND OUTPUT;

Where &vars is the macro variable containing all the variables needed for outputting for a dataset in the current loop.
Which gets resolved, for example, to:

PUT a b c d special1 special2 special5 ... special329;

Now the problem is, the quoted string can only be 262 characters long. And some of my datasets I am trying to output have so many variables to be output that this macro variable which is a quoted string and holds all those variables will be much longer than that. Is there any other way how I can do this?

Body:
Not sure why you're talking about quoted strings: you would not quote the &vars argument.

put a b c d &vars;

not

put a b c d "&vars";

There's a limit there, but it's much higher (64k).

That said, I would do this in a data driven fashion with CALL EXECUTE.  This is pretty simple and does it all in one step, assuming you can easily determine which datasets to output from the dictionary tables in a WHERE statement.  This has a limitation of 32kiB total, though if you're actually going to go over that you can work around it very easily (you can separate out various bits into multiple calls, and even structure the call so that if the callstr hits 32000 long you issue a call execute with it and then continue).

This avoids having to manage a bunch of large macro variables (your &VAR will really be &&VAR&N and will be many large macro variables).

data test;
  length vars callstr $32767;
  do _n_ = 1 by 1 until (last.memname);
    set sashelp.vcolumn;
    where memname in ('CLASS','CARS');
    by libname memname;
    vars = catx(' ',vars,name);
  end;
  callstr = catx(' ',
    'data _null_;',
    'set',cats(libname,'.',memname),';',
    'file',cats('"c:\temp\',memname,'.txt"'),';',
    'put',vars,';',
    'run;');
    call execute(callstr);
run;


问:
Find the smallest area rectangle covering a query point
I'm working on a personal project to do with computational geometry. The question in the title is an abstraction of one of the small subproblems that I am trying, but struggling, to solve efficiently. Hopefully it's general enough to maybe be of use of more than just me!

The problem

Imagine we have a set S of rectangles in the plane, all of which have edges parallel to the coordinate axes (no rotations). For my problem we'll assume that rectangle intersections are very common. But they are also very nice: If two rectangles intersect, we can assume one of them always completely contains the other. So there's no "partial" overlaps.

I want to store these rectangles in a way that:

We can efficiently add new rectangles.

Given a query point (x,y) we can efficiently report back the
rectangle of smallest area that contains the point.

The illustration provides the motivation for the latter. We always want to find the most deeply nested rectangle that contains the query point, so that's always the one of smallest area.

My thoughts

So I know that both R-Trees and Quad-Trees are often used for spatial indexing problems, and indeed both can work well in some cases. The problem with R-Trees is that they can degrade to linear performance in the worst case.

I thought about building a set of balanced binary trees based on nestedness. The left subtree of node r contains all the rectangles that are inside rectangle r. The right subtree contains all the rectangles that r is inside of. The illustrated example would have three trees.

But what if none of the rectangles are nested? Then you need O(n) trees of 1 element and again we have something that performs just as poorly as a linear scan through the boxes.

How could I solve this in  a way that we have asymptotically sub linear time in the worst case? Even if that means sacrificing some performance in the best cases or storage requirements. (I assume for a problem like this, there may be a need to maintain two data structures and that's cool)

I am certain that the very specific way in which rectangles are allowed to intersect should help make this problem possible. In fact, it looks like a candidate for logarithmic performance to me but I'm just not getting anywhere.

Thanks in advance for any ideas you have!

答:
Pretty much any index can degrade to worst case O(n).

The question is whether you will ever have such harmful data, and whether you optimize for worst case, or for real data.

Consider n identical sized, overlapping rectangles, and a point in the intersection... you won't have much chance for optimization here.

The R tree is a quite good choice. You can do a priority search, and prefer the smaller rectangles.

But your sketches indicate that your rectangles may be usually nested, rather than overlapping. The standard R-tree does not handle this very well. Instead, you may need to modify the R tree to use exactly this structure, and store only the nested rectangles as part of the parent.


问:
How do I import a custom made icon in Android Studio?
I made my own icon for my Android app, but I am a beginner in Android Studio, and it is not importing into my already existing Android Studio project.

I read to just use the Android Launcher Icon Generator from Android Asset Studio, which then creates a zip file for you, which should be placed inside your project res folder. I basically replaced the old res folder with the new one, and I checked and all the new icons are in their right folders, i.e. drawable-hdpi, drawable-mdpi, etc within my project directory, but they are not in the res folder of my project pane of Android Studio.

However, I restarted Android Studio, and it did not refresh to show these new imports. When I run my project, it still shows the old standard ic-launcher.png files.

答:
Very easy.
Just copy your generated icon paste it in drawable folder as follows.

Suppose generated icons are in those folders:

Then go to every folder, copy the icon and paste in drawable folder. Android studio will ask to select a folder, paste it to corresponding folder.

Don't worry for first icon, after pasting second icon, android studio automatically create folder structure.

I know there are other proper ways to import custom icon, but this easy and not thinkable way


问:
right click context menu to select whole row
```<code>  Private Sub dgvDisplay_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvDisplay.CellMouseDown
        'If e.Button = Windows.Forms.MouseButtons.Right Then
        '    If e.RowIndex < 0 Or e.ColumnIndex < 0 Then Exit Sub
        '    dgvDisplay.CurrentCell = dgvDisplay(e.ColumnIndex, e.RowIndex)
        '    ' Maybe modify the text on your context menu options here?
        'Else
        '    ContextMenuStrip1.Hide()
        'End If

    End Sub
</code>```

I want to be able to show context menu only when the user clicks on a cell and take the whole row , otherwise do nothing and not show event the context menu option

答:
The simple answer is to just set the selection mode:

```<code>dgvDisplay.SelectionMode = DataGridViewSelectionMode.FullRowSelect
</code>```

If you don't want than mode and need to do this in your MouseDown event, then try it like this:

```<code>Private Sub dgvDisplay_CellMouseDown(sender As Object, _
                                     e As DataGridViewCellMouseEventArgs) _
                                     Handles dgvDisplay.CellMouseDown
  If e.Button = MouseButtons.Right Then
    Dim cell As DataGridViewCell = dgvDisplay.Rows(e.RowIndex).Cells(e.ColumnIndex)
    If cell.Value IsNot Nothing AndAlso Not String.IsNullOrEmpty(cell.Value.ToString) Then
      dgvDisplay.ClearSelection()
      For i As Integer = 0 To dgvDisplay.Columns.Count - 1
        dgvDisplay.Rows(e.RowIndex).Cells(i).Selected = True
      Next
      ContextMenuStrip1.Show(dgvDisplay, dgvDisplay.PointToClient(Cursor.Position))
    End If
  End If
End Sub
</code>```

In order to select more than one cell, the MultiSelect property needs to be set to true.

Body:
  Private Sub dgvDisplay_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvDisplay.CellMouseDown
        'If e.Button = Windows.Forms.MouseButtons.Right Then
        '    If e.RowIndex < 0 Or e.ColumnIndex < 0 Then Exit Sub
        '    dgvDisplay.CurrentCell = dgvDisplay(e.ColumnIndex, e.RowIndex)
        '    ' Maybe modify the text on your context menu options here?
        'Else
        '    ContextMenuStrip1.Hide()
        'End If

    End Sub

I want to be able to show context menu only when the user clicks on a cell and take the whole row , otherwise do nothing and not show event the context menu option

Body:
The simple answer is to just set the selection mode:

dgvDisplay.SelectionMode = DataGridViewSelectionMode.FullRowSelect

If you don't want than mode and need to do this in your MouseDown event, then try it like this:

Private Sub dgvDisplay_CellMouseDown(sender As Object, _
                                     e As DataGridViewCellMouseEventArgs) _
                                     Handles dgvDisplay.CellMouseDown
  If e.Button = MouseButtons.Right Then
    Dim cell As DataGridViewCell = dgvDisplay.Rows(e.RowIndex).Cells(e.ColumnIndex)
    If cell.Value IsNot Nothing AndAlso Not String.IsNullOrEmpty(cell.Value.ToString) Then
      dgvDisplay.ClearSelection()
      For i As Integer = 0 To dgvDisplay.Columns.Count - 1
        dgvDisplay.Rows(e.RowIndex).Cells(i).Selected = True
      Next
      ContextMenuStrip1.Show(dgvDisplay, dgvDisplay.PointToClient(Cursor.Position))
    End If
  End If
End Sub

In order to select more than one cell, the MultiSelect property needs to be set to true.


问:
If statement in function error
How can I fork if a function gives me an error?
In C I used to attach it to the if statement(i.e scanf if succeed returns a 1 otherwise 0)

But here doesn't work here is the example:

```<code>if((htmlTreeParse(doc, useInternal = TRUE)))
{
    #DO
}else #DO SOMETHING ELSE
</code>```

答:
Found </p>

```<code>if(class(try(htmlTreeParse(doc, useInternal = TRUE), silent=T))!="try-error")
</code>```

Title: If statement in function error

Body:
How can I fork if a function gives me an error?
In C I used to attach it to the if statement(i.e scanf if succeed returns a 1 otherwise 0)

But here doesn't work here is the example:

if((htmlTreeParse(doc, useInternal = TRUE)))
{
    #DO
}else #DO SOMETHING ELSE

Body:
Found

if(class(try(htmlTreeParse(doc, useInternal = TRUE), silent=T))!="try-error")


问:
Batch - Trouble with Redirect within For Loop
I'm having difficulty getting a command to run in a For Loop.  From a cmd prompt this works fine:

```<code>"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" -r info | find "E:"
</code>```

But, the following seems to have a syntax problem

```<code>for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:"') do (set _DRVID=%%A)
</code>```

Yielding an error - C:\Program' is not recognized as an internal or external command, operable program or batch file.

Just for reference, I found a way to get my desired result with the following:
I can get the following code to work in Batch as well generating the desired output:

```<code>for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info') do (IF %%G=="E:" set _DRVID=%%A)
</code>```

What am I doing wrong?

答:
The best work-around in my opinion is to place a pair of quoted quotation marks around the expression:

for /f "tokens=1-7 delims=," %%A in ('^""C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:"^"') do (set "_DRVID=%%~A")
```

<p>After <code>for /F</code> consumes the enclosing <code>''</code>, the <code>cmd</code> instance executing the expression removes the outer-most <code>""</code>, so the remaining command line appears odd and therefore fails to be executed:</p>

<pre class="lang-cmd prettyprint-override"><code>C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:
</code>```

An extra pair of "" fixed that, but then you need to change escaping. Adding a pair of escaped quotes ^"^" lets the code work without having to change escaping. This is therefore the most general solution.

Body:
I'm having difficulty getting a command to run in a For Loop.  From a cmd prompt this works fine:

"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" -r info | find "E:"

But, the following seems to have a syntax problem

for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:"') do (set _DRVID=%%A)

Yielding an error - C:\Program' is not recognized as an internal or external command, operable program or batch file.

Just for reference, I found a way to get my desired result with the following:
I can get the following code to work in Batch as well generating the desired output:

for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info') do (IF %%G=="E:" set _DRVID=%%A)

What am I doing wrong?

Body:
The best work-around in my opinion is to place a pair of quoted quotation marks around the expression:

for /f "tokens=1-7 delims=," %%A in ('^""C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:"^"') do (set "_DRVID=%%~A")

After for /F consumes the enclosing '', the cmd instance executing the expression removes the outer-most "", so the remaining command line appears odd and therefore fails to be executed:

C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:

An extra pair of "" fixed that, but then you need to change escaping. Adding a pair of escaped quotes ^"^" lets the code work without having to change escaping. This is therefore the most general solution.


问:
I can't figure out how to count an alias [mysql]
I have to find the difference between two(2) dates and count how many time the results duplicate

```<code>SELECT DATEDIFF(name.shipped, name.order) AS 'days', COUNT(*)
FROM name
Group by 'days'
ORDER BY count(*) DESC
</code>```

however; instead of having multiple rows, I only get one(1) row with the count of the other rows.

```<code>days | count(*)
  4     16
</code>```

答: Unless you're wanting to group by the static string 'days' (you don't!), you want GROUP BY days, not GROUP BY 'days'.

Body:
I have to find the difference between two(2) dates and count how many time the results duplicate

SELECT DATEDIFF(name.shipped, name.order) AS 'days', COUNT(*)
FROM name
Group by 'days'
ORDER BY count(*) DESC

however; instead of having multiple rows, I only get one(1) row with the count of the other rows.

days | count(*)
  4     16


问:
How to begin with jar file in java code?
I am beginner for using java. Actually, what means by "make sure that weka.jar, common math.jar and etc. directory was in your classpath"? I already installed jar file and follow instruction from other source to change at classpath at the environment variable in control panel. However, I am still cannot call that function in my java code.  </p>

答:
You only need to import external jars to your project, try this:

First, select properties:

Second, select Java Build Path:

Third, select libraries:

And finally, add jar:


问:
Why the carriage return character is not considered as a white space character by the preprocessor
In the section 6.4 Lexical elements of the C Standard there is written

... Preprocessing tokens can be separated by white space; this consists of
  comments (described later), or white-space characters
  (space, horizontal tab, new-line, vertical tab, and form-feed), or
  both.

As it is seen the carriage return character is not included in the notion of the white space characters.

On the other hand in the description of the standard C function isspace there is written (7.4.1.10 The isspace function)

...The standard white-space characters are the following: space (''), form feed ('\f'), new-line ('\n'), carriage return ('\r'),
  horizontal tab ('\t'), and vertical tab ('\v'). In the "C" locale,
  isspace returns true only for the standard white-space characters.

Is it intentionally that the carriage return character is not mentioned in the section describing preprocessing and if so what is the reason?

Or is it  just a Standard's defect?

The same questions are valid for the C++ Standard.

答:
See N1570 5.2.1 paragraph 3.

The carriage return character is a member of the basic execution character set (and it treated by isspace() as a white-space character), but it's not part of the basic source character set.

The source and execution basic character sets both include "the space character, and control characters representing horizontal tab, vertical tab, and form feed". In addition, "In the basic execution character set, there shall be control characters representing alert, backspace, carriage return, and new line".

On some systems, the carriage return character is part of the indication of an end-of-line; any such indication is treated as a single new-line. A carriage return character that's not part of an end-of-line indicator in a source file causes undefined behavior.

ContentLicense: CC BY-SA 4.0


问:
JQuery switch class based on value
I Need a little JQuery Help.

HTML

```<code><body
<div id="mnRow" class="mnRow">
    <columns.Column field="Title" />
    <columns.Column field="AlertLevel" />
    <columns.Column field="Body" />
</div>
</code>```

CSS

```<code>    .low-risk{
     background-color: green;}

   .medium-risk{
    background-color: orange;}

  .high-risk{
   background-color: red;}
</code>```

I'd like to add the class' from the CSS when Column field equals low, medium and high.

Any help is appreciated.

thanks

答:
You can use custom attribute selector of Jquery and add class dynamically.

```<code>$("columns.Column[field='low']").addClass("low-risk")
</code>```

Ideally you should create a mapping object key as field name (like "low") and value as class name (like "low-risk") and loop through that object to perform addClass.

Title: JQuery switch class based on value

Body:
I Need a little JQuery Help.

HTML

<body

    <columns.Column field="Title" />
    <columns.Column field="AlertLevel" />
    <columns.Column field="Body" />

CSS

    .low-risk{
     background-color: green;}

   .medium-risk{
    background-color: orange;}

  .high-risk{
   background-color: red;}

I'd like to add the class' from the CSS when Column field equals low, medium and high.

Any help is appreciated.

thanks

Body:
You can use custom attribute selector of Jquery and add class dynamically.

$("columns.Column[field='low']").addClass("low-risk")

Ideally you should create a mapping object key as field name (like "low") and value as class name (like "low-risk") and loop through that object to perform addClass.


答:
Use positive lookbehind and lookahead regex search:

```<code>import re

def digest_fragment_with_enzyme(sequences, enzymes):
    pattern = '|'.join('((?<={})(?={}))'.format(strs[:ind], strs[ind:]) for strs, ind in enzymes)
    print pattern  # prints ((?<=T)(?=C))|((?<=G)(?=C))
    for seq in sequences:
        indices = [0] + [m.start() for m in re.finditer(pattern, seq)] + [len(seq)]
        yield [seq[start: end] for start, end in zip(indices, indices[1:])]

seq = ["AATTCCGGTCGGGGCTCGGGGG", "AAAGCAAAATCAAAAAAGCAAAAAATC"]
enzymes = [["TC", 1], ["GC", 1]]
print list(digest_fragment_with_enzyme(seq, enzymes))
</code>```

Output:

```<code>[['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'],
 ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAAAAAAT', 'C']]
</code>```

Title: python string splitting with multiple splitting points

Body:
Ok so ill get straight to the point here is my code

def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment

Input for this function is a list of multiple strings (seq) e.g. :

List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]

And enzymes as input:

[["TC", 1],["GC",1]]

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

Body:
Use positive lookbehind and lookahead regex search:

import re

def digest_fragment_with_enzyme(sequences, enzymes):
    pattern = '|'.join('((?<={})(?={}))'.format(strs[:ind], strs[ind:]) for strs, ind in enzymes)
    print pattern  # prints ((?<=T)(?=C))|((?<=G)(?=C))
    for seq in sequences:
        indices = [0] + [m.start() for m in re.finditer(pattern, seq)] + [len(seq)]
        yield [seq[start: end] for start, end in zip(indices, indices[1:])]

seq = ["AATTCCGGTCGGGGCTCGGGGG", "AAAGCAAAATCAAAAAAGCAAAAAATC"]
enzymes = [["TC", 1], ["GC", 1]]
print list(digest_fragment_with_enzyme(seq, enzymes))

Output:

[['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'],
 ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAAAAAAT', 'C']]


答:
The source file input gets translated into the source character set (translation phase 1 in §5.1.1.2 of the standard). The source character set is described in §5.2.1.

In C.2011, §5.2.1¶3:

In source files, there shall be some way of indicating the end of
  each line of text; this International Standard treats such an end-of-line indicator as if it were a single new-line character.

A bare carriage return is not part of the source character set. If it appears as part of a line termination sequence, it gets translated into a single new-line before the C preprocessor begins to do its work.

Title: Why the carriage return character is not considered as a white space character by the preprocessor

Body:
In the section 6.4 Lexical elements of the C Standard there is written

... Preprocessing tokens can be separated by white space; this consists of
  comments (described later), or white-space characters
  (space, horizontal tab, new-line, vertical tab, and form-feed), or
  both.

As it is seen the carriage return character is not included in the notion of the white space characters.

On the other hand in the description of the standard C function isspace there is written (7.4.1.10 The isspace function)

...The standard white-space characters are the following: space (''), form feed ('\f'), new-line ('\n'), carriage return ('\r'),
  horizontal tab ('\t'), and vertical tab ('\v'). In the "C" locale,
  isspace returns true only for the standard white-space characters.

Is it intentionally that the carriage return character is not mentioned in the section describing preprocessing and if so what is the reason?

Or is it  just a Standard's defect?

The same questions are valid for the C++ Standard.


问:
Unable to extract object values in Typescript
I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to deal with the following (which works in JavaScript):

```<code>let fieldValues = JSON.parse(cookieData);

let keys = Object.keys(fieldValues);

let values = Object.values(fieldValues);
</code>```

Visual Studio tells me:

Error TS2339  Property 'values' does not exist on type
  'ObjectConstructor'.

What can I do?

答:
The Object.values(..) is not stabilized, so it is unsupported in many browsers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)

Use map instead:

```<code>let values = Object.keys(fieldValues).map(key => fieldValues[key]);
</code>```

If you really want to use this function you need to add the "es2017.object" lib on your tsconfig.json. Make sure you are using a polyfill or if your final platform support this feature.

Body:
I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to deal with the following (which works in JavaScript):

let fieldValues = JSON.parse(cookieData);

let keys = Object.keys(fieldValues);

let values = Object.values(fieldValues);

Visual Studio tells me:

Error TS2339  Property 'values' does not exist on type
  'ObjectConstructor'.

What can I do?

Body:
The Object.values(..) is not stabilized, so it is unsupported in many browsers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)

Use map instead:

let values = Object.keys(fieldValues).map(key => fieldValues[key]);

If you really want to use this function you need to add the "es2017.object" lib on your tsconfig.json. Make sure you are using a polyfill or if your final platform support this feature.


问:
Unable to fire process
I have application which loads images like this:

```<code>someImage = Image.FromFile(@"picture.png");
</code>```

and another application which fires the previous one like this:

```<code>Process.Start(@"C:\dev\gallery.exe");
</code>```

and if I do like this I get an Exception: "picture.png", nothing more, but if I run this first gallery application normally using the icon or cmd then it works ok.

EDIT: I have just noticed that if I put these applications in the same folder then it works properly, why? what I can do then?

答:
I had a similar problem, but, in a different context. I used to use the command

```<code>Image.FromFile(@"picture.png");
</code>```

twice in my code. Between the two commands the image was supposed to be overwritten. But, it failed. The problem was tracked to the way Image.FromFile works. It does not close the handle of file after reading from it.

I used an workaround posted here to resolve this problem.

Let me know if your issue gets resolved.

Thanks

Vamyip

Title: Unable to fire process

Body:
I have application which loads images like this:

someImage = Image.FromFile(@"picture.png");

and another application which fires the previous one like this:

Process.Start(@"C:\dev\gallery.exe");

and if I do like this I get an Exception: "picture.png", nothing more, but if I run this first gallery application normally using the icon or cmd then it works ok.

EDIT: I have just noticed that if I put these applications in the same folder then it works properly, why? what I can do then?

Body:
I had a similar problem, but, in a different context. I used to use the command

Image.FromFile(@"picture.png");

twice in my code. Between the two commands the image was supposed to be overwritten. But, it failed. The problem was tracked to the way Image.FromFile works. It does not close the handle of file after reading from it.

I used an workaround posted here to resolve this problem.

Let me know if your issue gets resolved.

Thanks

Vamyip


问:
Rails - document.ready not working in specific JavaScript file
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:

```<code>$(document).ready(function() {
  console.log("Test");
});
</code>```

When I refresh the page nothing is logged to the console.

If I remove the console.log from within the document.ready then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready function that causes it not to work. Any ideas why?

Note: I'm not using Turbolinks.

Thanks

答:
Unless you've removed it, you will by default have Turbolinks running.

Instead of doing a full page load when you click links, it'll be doing XHR requests and replacing the body using javascript.

Because of this, you don't experience any document.ready events. Instead you should be using one of these, depending on which version you are running:

```<code>$(document).ready(myFunc); // What you're currently doing, but isn't working
$(document).on('page:load', myFunc); // Classic Turbolinks (Rails 4)
$(document).on('turbolinks:load', myFunc); // Turbolinks 5 (Rails 5)
</code>```

Body:
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:

$(document).ready(function() {
  console.log("Test");
});

When I refresh the page nothing is logged to the console.

If I remove the console.log from within the document.ready then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready function that causes it not to work. Any ideas why?

Note: I'm not using Turbolinks.

Thanks

Body:
Unless you've removed it, you will by default have Turbolinks running.

Instead of doing a full page load when you click links, it'll be doing XHR requests and replacing the body using javascript.

Because of this, you don't experience any document.ready events. Instead you should be using one of these, depending on which version you are running:

$(document).ready(myFunc); // What you're currently doing, but isn't working
$(document).on('page:load', myFunc); // Classic Turbolinks (Rails 4)
$(document).on('turbolinks:load', myFunc); // Turbolinks 5 (Rails 5)


问:
How to achieve MVC pattern in sails?
I'm wondering what is the best way to achieve the MVC pattern is sails.js.

Now I have the following structure: I have a route which redirects the request to the controller:

```<code>'POST /api/user/...': {controller: 'UserController', action: 'someFunction'},
</code>```

My user model:

```<code>module.exports = {
    ...
    attributes: {...}
}
</code>```

I have the controller:

```<code>someFunction: function(req, res) {
    let param = req.body.param;
    let userId = req.session.userId;
    userService.someFunction(userId, param, function (result) {
        return res.json({result});
    });
},
</code>```

And in the userService I have methods for manipulating the database, for example:

```<code>someFunction: function(userId, param, callback){
    User.findOne(userId).exec(function (err, user){
                    if (err) {
                        callback(false);
                    } else {
                        // find the user's additional info
                        User.update({name: param}, { ... })
}
</code>```

My real question is that is this a good pattern to follow or I'm on the wrong path.

Thanks for any kind of response.

答:
Note: Answer to this question can be opinion-based. Here is my opinion.

Sails project is scaffolded in MVC pattern. There are separate folders for Models (api/models), Controllers (api/controllers), and Views (views).

You're doing right thing having database methods in Services.

Anything that can be required by more than one controller action should go into services.

Other thoughts:

Any logic which deals with a single model should be in that Model

Prefer to apply constraints, foreign keys at database level as well

With Node.js v7.6+, you can use async/await. Sails (Waterline) methods return Bluebird promises which works well with async/await.

Title: How to achieve MVC pattern in sails?

Body:
I'm wondering what is the best way to achieve the MVC pattern is sails.js.

Now I have the following structure: I have a route which redirects the request to the controller:

'POST /api/user/...': {controller: 'UserController', action: 'someFunction'},

My user model:

module.exports = {
    ...
    attributes: {...}
}

I have the controller:

someFunction: function(req, res) {
    let param = req.body.param;
    let userId = req.session.userId;
    userService.someFunction(userId, param, function (result) {
        return res.json({result});
    });
},

And in the userService I have methods for manipulating the database, for example:

someFunction: function(userId, param, callback){
    User.findOne(userId).exec(function (err, user){
                    if (err) {
                        callback(false);
                    } else {
                        // find the user's additional info
                        User.update({name: param}, { ... })
}

My real question is that is this a good pattern to follow or I'm on the wrong path.

Thanks for any kind of response.


问:
XCUI tests failing on iOS 10 but not iOS 9 due to ""Error -25204 getting snapshot for element"
I have created a test suite for XCUItesting for my app...However since the upgrade (unsure if relevant) to xcode 8 and the use of ios10 simulator my test cases will only run in the ios9 and not in the 10. When I run the tests in the ios 10 simulator I get the error Assertion Failure: <unknown>:0: UI Testing Failure - Failure getting snapshot Error Domain=XCTestManagerErrorDomain Code=9 "Error -25204 getting snapshot for element <AXUIElement 0x7fe2a6614ad0> {pid=7751}" UserInfo={NSLocalizedDescription=Error -25204 getting snapshot for element <AXUIElement 0x7fe2a6614ad0> {pid=7751}}

Is anyone experincing this also?
Or
Does anyone know where I am going wrong?

Many thanks

答:
Root cause

I have run into the same issue. The test was failing with the same error but the root cause was that the app was crashing. I set up an exception breakpoint and printed the backtrace out to see where.

In the end, it was a crash caused by implicitly unwrapped optional in one of the uitableviewdelegate's method signatures:

public func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool

This method was called by the system during the UI tests with indexPath parameter being nil, causing the app to hang.

The backtrace showed this:

```<code>(lldb) thread backtrace
* thread #1: tid = 0x128eaa, 0x000000010c776c3a libswiftFoundation.dylib`static Foundation.IndexPath._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSIndexPath>) -> Foundation.IndexPath + 42, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  * frame #0: 0x000000010c776c3a libswiftFoundation.dylib`static Foundation.IndexPath._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSIndexPath>) -> Foundation.IndexPath + 42
    frame #1: 0x0000000108443241 Static`@objc DataSource.tableView(UITableView, canPerformAction : Selector, forRowAt : IndexPath, withSender : Any?) -> Bool + 97 at DataSource.swift:0
    frame #2: 0x00000001095aea31 UIKit`-[UITableView _canPerformAction:forCell:sender:] + 169
    frame #3: 0x00000001098017c6 UIKit`-[UITableViewCell canPerformAction:withSender:] + 86
    frame #4: 0x00000001210a5fc9 UIKit`-[UIResponder(UITextAccessibilityUtilities) _accessibilityHasTextOperations] + 100
    frame #5: 0x000000012107bb7c UIKit`-[UITableViewCellAccessibilityElement _accessibilityHasTextOperations] + 48
    frame #6: 0x00000001211f09ec UIAccessibility`-[NSObject(AXPrivCategory) accessibilityAttributeValue:] + 5945
    frame #7: 0x000000012120bc04 UIAccessibility`_accessibilityAttributesForObject + 767
    frame #8: 0x000000012120b5e8 UIAccessibility`-[NSObject(UIAccessibilityAutomation) _accessibilityUserTestingSnapshotDescendantsWithAttributes:maxDepth:maxChildren:maxArrayCount:] + 1736
    frame #9: 0x000000012120cf96 UIAccessibility`-[NSObject(UIAccessibilityAutomation) _accessibilityUserTestingSnapshotWithOptions:] + 557
    frame #10: 0x00000001211eec0a UIAccessibility`-[NSObject(AXPrivCategory) accessibilityAttributeValue:forParameter:] + 7903
    frame #11: 0x00000001211d8856 UIAccessibility`_copyParameterizedAttributeValueCallback + 211
    frame #12: 0x0000000120869532 AXRuntime`_AXXMIGCopyParameterizedAttributeValue + 216
    frame #13: 0x0000000120863f1c AXRuntime`_XCopyParameterizedAttributeValue + 440
    frame #14: 0x0000000120872de5 AXRuntime`mshMIGPerform + 266
    frame #15: 0x00000001064e93d9 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
    frame #16: 0x00000001064e9351 CoreFoundation`__CFRunLoopDoSource1 + 465
    frame #17: 0x00000001064e1435 CoreFoundation`__CFRunLoopRun + 2389
    frame #18: 0x00000001064e0884 CoreFoundation`CFRunLoopRunSpecific + 420
    frame #19: 0x000000010e5bda6f GraphicsServices`GSEventRunModal + 161
    frame #20: 0x000000010943dc68 UIKit`UIApplicationMain + 159
    frame #21: 0x000000010462c95f GoOut`main + 111 at AppDelegate.swift:47
    frame #22: 0x000000010cb7e68d libdyld.dylib`start + 1
    frame #23: 0x000000010cb7e68d libdyld.dylib`start + 1
</code>```

Solution

After knowing which method was causing it, the fix is quite simple -- just replace the indexPath type with optional IndexPath? (add the question mark):

public func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath?, withSender sender: Any?) -> Bool

Then the method gets called properly with nil and does not cause crashes.

For more info see: https://openradar.appspot.com/31375101 and feel free to dupe the radar.

Body:
Root cause

I have run into the same issue. The test was failing with the same error but the root cause was that the app was crashing. I set up an exception breakpoint and printed the backtrace out to see where.

In the end, it was a crash caused by implicitly unwrapped optional in one of the uitableviewdelegate's method signatures:

public func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool

This method was called by the system during the UI tests with indexPath parameter being nil, causing the app to hang.

The backtrace showed this:

(lldb) thread backtrace
* thread #1: tid = 0x128eaa, 0x000000010c776c3a libswiftFoundation.dylib`static Foundation.IndexPath._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSIndexPath>) -> Foundation.IndexPath + 42, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  * frame #0: 0x000000010c776c3a libswiftFoundation.dylib`static Foundation.IndexPath._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSIndexPath>) -> Foundation.IndexPath + 42
    frame #1: 0x0000000108443241 Static`@objc DataSource.tableView(UITableView, canPerformAction : Selector, forRowAt : IndexPath, withSender : Any?) -> Bool + 97 at DataSource.swift:0
    frame #2: 0x00000001095aea31 UIKit`-[UITableView _canPerformAction:forCell:sender:] + 169
    frame #3: 0x00000001098017c6 UIKit`-[UITableViewCell canPerformAction:withSender:] + 86
    frame #4: 0x00000001210a5fc9 UIKit`-[UIResponder(UITextAccessibilityUtilities) _accessibilityHasTextOperations] + 100
    frame #5: 0x000000012107bb7c UIKit`-[UITableViewCellAccessibilityElement _accessibilityHasTextOperations] + 48
    frame #6: 0x00000001211f09ec UIAccessibility`-[NSObject(AXPrivCategory) accessibilityAttributeValue:] + 5945
    frame #7: 0x000000012120bc04 UIAccessibility`_accessibilityAttributesForObject + 767
    frame #8: 0x000000012120b5e8 UIAccessibility`-[NSObject(UIAccessibilityAutomation) _accessibilityUserTestingSnapshotDescendantsWithAttributes:maxDepth:maxChildren:maxArrayCount:] + 1736
    frame #9: 0x000000012120cf96 UIAccessibility`-[NSObject(UIAccessibilityAutomation) _accessibilityUserTestingSnapshotWithOptions:] + 557
    frame #10: 0x00000001211eec0a UIAccessibility`-[NSObject(AXPrivCategory) accessibilityAttributeValue:forParameter:] + 7903
    frame #11: 0x00000001211d8856 UIAccessibility`_copyParameterizedAttributeValueCallback + 211
    frame #12: 0x0000000120869532 AXRuntime`_AXXMIGCopyParameterizedAttributeValue + 216
    frame #13: 0x0000000120863f1c AXRuntime`_XCopyParameterizedAttributeValue + 440
    frame #14: 0x0000000120872de5 AXRuntime`mshMIGPerform + 266
    frame #15: 0x00000001064e93d9 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
    frame #16: 0x00000001064e9351 CoreFoundation`__CFRunLoopDoSource1 + 465
    frame #17: 0x00000001064e1435 CoreFoundation`__CFRunLoopRun + 2389
    frame #18: 0x00000001064e0884 CoreFoundation`CFRunLoopRunSpecific + 420
    frame #19: 0x000000010e5bda6f GraphicsServices`GSEventRunModal + 161
    frame #20: 0x000000010943dc68 UIKit`UIApplicationMain + 159
    frame #21: 0x000000010462c95f GoOut`main + 111 at AppDelegate.swift:47
    frame #22: 0x000000010cb7e68d libdyld.dylib`start + 1
    frame #23: 0x000000010cb7e68d libdyld.dylib`start + 1

Solution

After knowing which method was causing it, the fix is quite simple -- just replace the indexPath type with optional IndexPath? (add the question mark):

public func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath?, withSender sender: Any?) -> Bool

Then the method gets called properly with nil and does not cause crashes.

For more info see: https://openradar.appspot.com/31375101 and feel free to dupe the radar.


问:
Determining when a UIPageViewController scrolls past last page
I'm attempting to dismiss a UIPageViewController which is presented modally when the user scrolls past the last page. Is there a way to tell when this happens?
viewControllerAfterViewController is called when the last view controller is shown.

Edit: I've also tried to add UISwipeGestureRecognizers but they are not being called.  I think this is because the UIPageViewController's gesture recognizer's disable them.

答: UIViewController:viewWillAppear:animated will get called when the user swipes to that page.  So you could add a dummy last page, and dismiss the pageViewController when that gets called.


问:
Datatable fixed header with buttons

I have Color Admin Template

I m using fixed header table to display data : Fixed Header Table

I wanna use button(print,excel,csv,etc...) in fixed header table mentioned in following table Button Table

What should i do?

答:
I added a second tr tag inside my thead tag with id="th-buttons"

```<code><thead>
    <tr style="background-color: #99b3ff">
        <th id="th-buttons" class="dt-buttons table-header-buttons" colspan="6" rowspan="1"></th>
    </tr>
     <tr>
        <th></th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Salary</th>
     </tr>
</thead>
</code>```

Then in my JS I initiated the buttons using the direct insertion with a new constructor.

You can see the Demo here: http://codepen.io/sshel/pen/xqmQqM

Title: Datatable fixed header with buttons

Body:
I added a second tr tag inside my thead tag with id="th-buttons"

<thead>
    <tr style="background-color: #99b3ff">
        <th id="th-buttons" class="dt-buttons table-header-buttons" colspan="6" rowspan="1"></th>
    </tr>
     <tr>
        <th></th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Salary</th>
     </tr>
</thead>

Then in my JS I initiated the buttons using the direct insertion with a new constructor.

You can see the Demo here: http://codepen.io/sshel/pen/xqmQqM


问:
Button aligned to bottom of RelativeLayout is cut off
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
</code>```

答:
```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Some Title" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:layout_below="@+id/section_label"
    android:layout_alignParentStart="true"
    android:layout_marginTop="42dp"
    android:hint="Some hint"
    android:id="@+id/emailTB" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:ems="10"
    android:layout_below="@+id/emailTB"
    android:layout_alignParentStart="true"
    android:layout_marginTop="45dp"
    android:hint="Some hint"
    android:maxLines="10"
    android:id="@+id/messageTB" />

<RelativeLayout
    android:layout_below="@+id/messageTB"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:gravity="bottom"
    android:layout_height="wrap_content">
    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_centerInParent="true"/>
</RelativeLayout>
</code>```

Body:
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>


问:
Obtaining the Build ID in a Java Application
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime? </p>

<p>Building from within Eclipse, all I need is the ID, I can then pass it up to the title.  </p>

答: If you are completely building within Eclipse, you need to create a build action which generates a resource in your source folder with the information you need - a property file will do nicely - which then propagates to your binary output and can be read at runtime after which you can do what you need to show it.</p>

Body:
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime?

Building from within Eclipse, all I need is the ID, I can then pass it up to the title.


问:
Angular 2 how to ignore .map.js files?
I would like to now how to ignore all .js.map files in angular 2. In my .gitignore file all I have already tried all the possibilities but did not work yet. </p>

```<code>*.log
typings
src/app/**/*.js
src/app/**/*.map
node_modules
.idea/
src/app/**/**/*.map
src/app/*.map
src/app/**/*.js.map
src/app/**/*.js
</code>```

Title: Angular 2 how to ignore .map.js files?

Body:
I would like to now how to ignore all .js.map files in angular 2. In my .gitignore file all I have already tried all the possibilities but did not work yet.

*.log
typings
src/app/**/*.js
src/app/**/*.map
node_modules
.idea/
src/app/**/**/*.map
src/app/*.map
src/app/**/*.js.map
src/app/**/*.js

Body:
USE THESE

**/*.map
**/app/**/*.js


问:
Launch app on voice command (android)
I need an example of how I could launch my app on a voice command (trigger word).
So some sort of a service running in the background listening to everything and if the word matches a set textual value (I guess this can be done through Voice Recognition), app will open. I know this is possible, but I've no clue where to start...

I see other apps are able to establish this. I've close to 1 million users and this is one of the most often requested features.

答:
On Android 6 and later, you can just say "Ok Google" or click on the microphone icon, then say "launch YourAppName", and your app will be launched.

If Google voice search cannot recognize your app's name, try to spell it out.

To turn on "Ok Google" voice search:
https://support.google.com/websearch/answer/2940021?hl=en

Hope that helps!

Title: Launch app on voice command (android)


问:
Jquery Cycle Plugin - webkit browsers start a paused cycle on refresh
This is my code

```<code>$('#gallery-photos').cycle({
            fx:     'fade',
            speed:   500,
            timeout: 3000,
            pager:  '#gallery-navigation',
            requeueOnImageNotLoaded: true,
            after:  onAfter
        }).cycle('pause');
</code>```

As you can see the cycle will stop after init, as Malsup itself showed in some posts around the internet... but when i refresh page with Chrome or Safari, the cycle starts, ignoring the pause command.

I have another slideshow in the same page that autostarts as default, but it is not involved with the previous one

```<code>$(document).ready(function() {
    $('#header-gallery-conteiner').cycle({
         fx:'scrollUp',
         speed:  888,
         timeout: 4000,
         requeueOnImageNotLoaded: true
     });
 });
</code>```

How can i make it able to pause correctly even after refresh with webkit browsers?

答:
move you first block of code inside the $(document).ready() event like this:

```<code>$(document).ready(function() {
    $('#header-gallery-conteiner').cycle({
         fx:'scrollUp',
         speed:  888,
         timeout: 4000,
         requeueOnImageNotLoaded: true
     });
     $('#gallery-photos').cycle({
         fx:     'fade',
         speed:   500,
         timeout: 3000,
         pager:  '#gallery-navigation',
         requeueOnImageNotLoaded: true,
         after:  onAfter
     }).cycle('pause');
 });
</code>```

You should only have one function assigned to $(document).ready(), so if you have it also somewere else on your page get rid of it, and add the code to to the function above

Body:
This is my code

$('#gallery-photos').cycle({
            fx:     'fade',
            speed:   500,
            timeout: 3000,
            pager:  '#gallery-navigation',
            requeueOnImageNotLoaded: true,
            after:  onAfter
        }).cycle('pause');

As you can see the cycle will stop after init, as Malsup itself showed in some posts around the internet... but when i refresh page with Chrome or Safari, the cycle starts, ignoring the pause command.

I have another slideshow in the same page that autostarts as default, but it is not involved with the previous one

$(document).ready(function() {
    $('#header-gallery-conteiner').cycle({
         fx:'scrollUp',
         speed:  888,
         timeout: 4000,
         requeueOnImageNotLoaded: true
     });
 });

How can i make it able to pause correctly even after refresh with webkit browsers?

Body:
move you first block of code inside the $(document).ready() event like this:

$(document).ready(function() {
    $('#header-gallery-conteiner').cycle({
         fx:'scrollUp',
         speed:  888,
         timeout: 4000,
         requeueOnImageNotLoaded: true
     });
     $('#gallery-photos').cycle({
         fx:     'fade',
         speed:   500,
         timeout: 3000,
         pager:  '#gallery-navigation',
         requeueOnImageNotLoaded: true,
         after:  onAfter
     }).cycle('pause');
 });

You should only have one function assigned to $(document).ready(), so if you have it also somewere else on your page get rid of it, and add the code to to the function above


问:
Exposing a method which is inside a closure
When we are creating a method inside a closure it becomes private to that closure and can't be accessed until we expose it in some way.

How can it be exposed?

答:
For performance purposes you can invoke it this way:</p>

```<code>var a = (function(){
   function _a(){}
   _a.prototype = (function(){
     var _test = function(){ console.log("test"); };
     return {
       test: _test
     }
   }());

  return new _a();
}());

// usage
var x = a;
x.test(); // "test"
</code>```

Body:
For performance purposes you can invoke it this way:

var a = (function(){
   function _a(){}
   _a.prototype = (function(){
     var _test = function(){ console.log("test"); };
     return {
       test: _test
     }
   }());

  return new _a();
}());

// usage
var x = a;
x.test(); // "test"


问:
wordpress Async-upload.php diverts me to login page
I am using wp media upload on frond end  to upload image, but when i upload image from front end and upload gives me error can not uploaded i see that when ajax make call to <code>'async-upload.php'</code> it logout me and divert to wp dashboard login page </p>

答:
If you have already tried disabling all plugins, modifying role capabilities, and adding the suggested lines to your .htaccess file, the following actions worked for me. Go to /wp-admin/admin.php. Locate the line that says:

```<code>    auth_redirect();
</code>```

And replace it with:

```<code>    if (!defined("DOING_AJAX"))
        auth_redirect();
</code>```

This solution worked for me, but note that these changes will most likely be overwritten when you update your version of Wordpress.

EDIT:
After some Wordpress updates, I have had to change the way I go about solving this, instead of including the /wp-admin/admin.php, I had to copy the file into async-uploads.

I also had to go into ajax-actions.php and include the following lines at the top of the file:

```<code>    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');
</code>```

Body: I am using wp media upload on frond end  to upload image, but when i upload image from front end and upload gives me error can not uploaded i see that when ajax make call to 'async-upload.php' it logout me and divert to wp dashboard login page

Body:
If you have already tried disabling all plugins, modifying role capabilities, and adding the suggested lines to your .htaccess file, the following actions worked for me. Go to /wp-admin/admin.php. Locate the line that says:

    auth_redirect();

And replace it with:

    if (!defined("DOING_AJAX"))
        auth_redirect();

This solution worked for me, but note that these changes will most likely be overwritten when you update your version of Wordpress.

EDIT:
After some Wordpress updates, I have had to change the way I go about solving this, instead of including the /wp-admin/admin.php, I had to copy the file into async-uploads.

I also had to go into ajax-actions.php and include the following lines at the top of the file:

    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');


问:
add values with one another with input field submit in php calculator
I want a calculator with my PHP code that adds values with one after one with submit button.like when I input a number then submit it and show it on the page then and input other, it should add previous number.and then enter another then submit.like these, numbers are adding with one another after submitting.

<?php
session_start();

?>

<?php
error_reporting(0);
?>

<title>adding input single values</title>

<form method="post">

    <input type="text"  name='number'  method="post"/>
    <input type="submit" />
</form>
<?php
if(!isset($_POST['number']))
{

}
else
{
$sum += $_POST['number'];
echo ++$sum;

}
?>

```

here is the output

答:
You could use a hidden field instead of storing in the session.</p>

<p> </p>

```<code>    <input type="text"  name='number'  method="post"/>

    <?php
    if(!isset($_POST['number'])) {
        echo "<input type='hidden' name='prev_number' value=0 />";
    } else {
        $sum = $_POST['number'] + $_POST['prev_number'];
        echo "<input type='hidden' name='prev_number' value=" . $sum . " />";
        echo $sum;

    }
    ?>
        <input type="submit" />
    </form>
</code>```

Body:
I want a calculator with my PHP code that adds values with one after one with submit button.like when I input a number then submit it and show it on the page then and input other, it should add previous number.and then enter another then submit.like these, numbers are adding with one another after submitting.

<?php
session_start();

?>

<?php
error_reporting(0);
?>

<title>adding input single values</title>

<form method="post">

    <input type="text"  name='number'  method="post"/>
    <input type="submit" />
</form>
<?php
if(!isset($_POST['number']))
{

}
else
{
$sum += $_POST['number'];
echo ++$sum;

}
?>

here is the output

Body:
You could use a hidden field instead of storing in the session.

    <input type="text"  name='number'  method="post"/>

    <?php
    if(!isset($_POST['number'])) {
        echo "<input type='hidden' name='prev_number' value=0 />";
    } else {
        $sum = $_POST['number'] + $_POST['prev_number'];
        echo "<input type='hidden' name='prev_number' value=" . $sum . " />";
        echo $sum;

    }
    ?>
        <input type="submit" />
    </form>


问:
Porting cURL -F into RestSharp
I'm trying to upload local file(s) using the 3rd party API (actually Zendesk), could someone please help me understand how to port the example cURL that was provided into RestSharp

cURL example that's provided:

```<code>curl https://{subdomain}.zendesk.com/api/v2/help_center/articles/{id}/attachments.json \ -F "inline=true" -F "file=@drawing.png" \ -v -u {email_address}:{password} -X POST
</code>```

I've been trying to add it with AddFile, also as parameter, but I keep running into 500 Internal Server Error.

My code that's trying to accomplish the same thing as above cURL is basically this:

```<code>var attachmentRequest = new RestRequest();

var attachmentURL = "api/v2/help_center/articles/" + article.id + "/attachments.json";
var attachmentPath = articlePath + "\\" + attachment.file_name;

attachmentRequest.Resource = attachmentURL;
attachmentRequest.Method = Method.POST;
attachmentRequest.AddParameter("inline", attachment.inline);
attachmentRequest.AddFile(attachment.file_name, attachmentPath);

var attachmentResponse = client.Execute(attachmentRequest); // returns status code 500
</code>```

Any help is greatly appreciated, I searched through a lot of information about porting these requests, as well as both cURL and RestSharp documentation and I simply cannot figure this one out.

Update Feb 20th: I still cannot figure this out. In the meantime since I need a solution I'm actually calling the curl executable to accomplish this. Naturally, I'd be extremely grateful if someone had any insight in figuring this out through RestSharp instead.

答:
the cUrl idicates this to be a multipart/form request. see the following for a bit of detail

https://blog.tyrsius.com/restsharp-file-upload/

i believe the line of code you are looking to use is

```<code>request.AlwaysMultipartFormData = true;
</code>```

Im fiddling with a similar request right now, so ill post with my results.

Title: Porting cURL -F into RestSharp

Body:
I'm trying to upload local file(s) using the 3rd party API (actually Zendesk), could someone please help me understand how to port the example cURL that was provided into RestSharp

cURL example that's provided:

curl https://{subdomain}.zendesk.com/api/v2/help_center/articles/{id}/attachments.json \ -F "inline=true" -F "file=@drawing.png" \ -v -u {email_address}:{password} -X POST

I've been trying to add it with AddFile, also as parameter, but I keep running into 500 Internal Server Error.

My code that's trying to accomplish the same thing as above cURL is basically this:

var attachmentRequest = new RestRequest();

var attachmentURL = "api/v2/help_center/articles/" + article.id + "/attachments.json";
var attachmentPath = articlePath + "\\" + attachment.file_name;

attachmentRequest.Resource = attachmentURL;
attachmentRequest.Method = Method.POST;
attachmentRequest.AddParameter("inline", attachment.inline);
attachmentRequest.AddFile(attachment.file_name, attachmentPath);

var attachmentResponse = client.Execute(attachmentRequest); // returns status code 500

Any help is greatly appreciated, I searched through a lot of information about porting these requests, as well as both cURL and RestSharp documentation and I simply cannot figure this one out.

Update Feb 20th: I still cannot figure this out. In the meantime since I need a solution I'm actually calling the curl executable to accomplish this. Naturally, I'd be extremely grateful if someone had any insight in figuring this out through RestSharp instead.

Body:
the cUrl idicates this to be a multipart/form request. see the following for a bit of detail

https://blog.tyrsius.com/restsharp-file-upload/

i believe the line of code you are looking to use is

request.AlwaysMultipartFormData = true;

Im fiddling with a similar request right now, so ill post with my results.


问:
How to grant privilege for an Oracle trigger to access a function from other schema
I have a problem that I try to call functions from a trigger. This function is from a different schema. I granted privileges for the user of the trigger to access the functions:

```<code>select 'GRANT EXECUTE ON VARTABLE.SEATS TO OWNER_OF_TRIGGER;' from all_objects where owner = 'xxx' and object_type='FUNCTION';
</code>```

However, this does not work. Is this somehow possible or do I need to copy the functions to the schema of the trigger?

```<code>create or replace TRIGGER CALCULATOR
AFTER INSERT ON PEOPLE
FOR EACH ROW
DECLARE
BEGIN
<<VARTABLE>> DECLARE
SEATS NUMBER;
INCOME NUMBER;
CANNOT_CHANGE_VALUE EXCEPTION;
  BEGIN
    SELECT COMPANY.SEAT(5,0.5,3.5) INTO VARTABLE.SEATS FROM DUAL;
    SELECT COMPANY.INCOME(3,360,500) INTO VARTABLE.INCOME FROM DUAL;
    IF INSERTING THEN
      INSERT INTO CALCULATIONS (cd_id,
      SITTING_PLACE,
      INCOME) VALUES (:NEW.CD_ID,
      VARTABLE.SEATS,
      VARTABLE.INCOME);
    END IF;
  END;
END;
</code>```

答:
Kinda calling back to my Oracle days, but you should be able to create a Synonym to handle the link.

https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_7001.htm

Body:
I have a problem that I try to call functions from a trigger. This function is from a different schema. I granted privileges for the user of the trigger to access the functions:

select 'GRANT EXECUTE ON VARTABLE.SEATS TO OWNER_OF_TRIGGER;' from all_objects where owner = 'xxx' and object_type='FUNCTION';

However, this does not work. Is this somehow possible or do I need to copy the functions to the schema of the trigger?

create or replace TRIGGER CALCULATOR
AFTER INSERT ON PEOPLE
FOR EACH ROW
DECLARE
BEGIN
<<VARTABLE>> DECLARE
SEATS NUMBER;
INCOME NUMBER;
CANNOT_CHANGE_VALUE EXCEPTION;
  BEGIN
    SELECT COMPANY.SEAT(5,0.5,3.5) INTO VARTABLE.SEATS FROM DUAL;
    SELECT COMPANY.INCOME(3,360,500) INTO VARTABLE.INCOME FROM DUAL;
    IF INSERTING THEN
      INSERT INTO CALCULATIONS (cd_id,
      SITTING_PLACE,
      INCOME) VALUES (:NEW.CD_ID,
      VARTABLE.SEATS,
      VARTABLE.INCOME);
    END IF;
  END;
END;


问:
Scraping a Forum with Beautiful Soup - How to exclude Quoted Replies?
it's my first time using Beautiful Soup or doing Web Scraping for that matter. I have been happy enough with how far I've gotten so far but I have come to a bit of an obstacle.

I am trying to scrape all the posts on a particular thread. However, I want to exclude the text from quoted replies.

An example:

I would like scrape the text from these postings without scraping the text within the area indicated in the red box.

In the html, the part I want to exclude is within the section I need to select for the message which is why I am having difficulty. I have included a screenshot of the html

HTML image

```<code><div id="post_message_39096267"><!-- google_ad_section_start --><div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody><tr>
    <td class="alt2" style="border:1px inset">

            <div>
                Originally Posted by <strong>SAAN</strong>
                <a href="http://www.city-data.com/forum/economics/2056372-minimum-wage-vs-liveable-wage-post33645660.html#post33645660" rel="nofollow"><img class="inlineimg li fs-viewpost" src="http://pics3.city-data.com/trn.gif" border="0" alt="View Post" title="View Post"></a>
            </div>
            <div style="font-style:italic">I agree with trying to buy a
cheap car outright, the problem is everyone I know that has done that $2-
5000 car, always ended up with these huge repair bills that are equivalent
to car payments.  Most cars after 100K will need all sort of regulatr
maintance that is easily a $200 repair to go along with anything that may
break which is common with cars as they age.<br>
<br>
I have a 2yr old im making payments on and 14yr old car that is paid off,
but needs $2000 in maintenance.  When car shopping this summer, I saw many
cars i could buy outright, but after adding u everything needed to make sure
it needs nothing, your back into the price range of a car payment.</div>

    </td>
</tr>
</tbody></table>
</div>Depends on how long the car loan would be stretched. Just because you
can get an 8 year loan and reduce payments to a level like the repairs on
your old car doesn't make it a good idea, especially for new cars that <a
href="/knowledge/Depreciation.html" title="View 'depreciate' definition from
Wikipedia" class="knldlink" rel="nofollow">depreciate</a> quickly. You'd
just be putting yourself into negative equity territory.<!--
google_ad_section_end --></div>
</code>```

I have included my code below: Hopefully this will help you understand what I am talking about.

```<code>from bs4 import BeautifulSoup
import urllib2

num_pages = 101
page_range = range(1,num_pages+1)
clean_posts = []

for page in page_range:
  print("Reading page: ", page, "...")
  if page == 1:
    page_url = urllib2.urlopen('http://www.city-data.com/forum/economics/2056372-minimum-wage-vs-liveable-wage.html')
  else:
    page_url = urllib2.urlopen('http://www.city-data.com/forum/economics/2056372-minimum-wage-vs-liveable-wage'+'-'+str(page)+'.html')

soup = BeautifulSoup(page_url)

postData = soup.find_all("div", id=lambda value: value and value.startswith("post_message_"))

posts = []
for post in postData:
    posts.append(BeautifulSoup(str(post)).get_text().encode("utf-8").strip().replace("\t", ""))

posts_stripped = [x.replace("\n","") for x in posts]

clean_posts.append(posts_stripped)
</code>```

Finally, I would hugely appreciate it if you could give me code examples of what would work and explain what things to me as if I were literally 9 years old!

Cheers
Diarmaid

答:
Check if your post_message_ div has another div inside (The quote div). If so extract it. Append the original div (post_message_) text into your list. Replace your for post in postData with this one.

```<code>posts = []
for post in postData:
    hasQuote = post.find("div")
     if not hasQuote is None:
        hasQuote.extract()
    posts.append(post.get_text(strip=True))
</code>```

Body:
it's my first time using Beautiful Soup or doing Web Scraping for that matter. I have been happy enough with how far I've gotten so far but I have come to a bit of an obstacle.

I am trying to scrape all the posts on a particular thread. However, I want to exclude the text from quoted replies.

An example:

I would like scrape the text from these postings without scraping the text within the area indicated in the red box.

In the html, the part I want to exclude is within the section I need to select for the message which is why I am having difficulty. I have included a screenshot of the html

HTML image

Quote:

                Originally Posted by SAAN

I agree with trying to buy a
cheap car outright, the problem is everyone I know that has done that $2-
5000 car, always ended up with these huge repair bills that are equivalent
to car payments.  Most cars after 100K will need all sort of regulatr
maintance that is easily a $200 repair to go along with anything that may
break which is common with cars as they age.

I have a 2yr old im making payments on and 14yr old car that is paid off,
but needs $2000 in maintenance.  When car shopping this summer, I saw many
cars i could buy outright, but after adding u everything needed to make sure
it needs nothing, your back into the price range of a car payment.

Depends on how long the car loan would be stretched. Just because you
can get an 8 year loan and reduce payments to a level like the repairs on
your old car doesn't make it a good idea, especially for new cars that depreciate quickly. You'd
just be putting yourself into negative equity territory.

I have included my code below: Hopefully this will help you understand what I am talking about.

from bs4 import BeautifulSoup
import urllib2

num_pages = 101
page_range = range(1,num_pages+1)
clean_posts = []

for page in page_range:
  print("Reading page: ", page, "...")
  if page == 1:
    page_url = urllib2.urlopen('http://www.city-data.com/forum/economics/2056372-minimum-wage-vs-liveable-wage.html')
  else:
    page_url = urllib2.urlopen('http://www.city-data.com/forum/economics/2056372-minimum-wage-vs-liveable-wage'+'-'+str(page)+'.html')

soup = BeautifulSoup(page_url)

postData = soup.find_all("div", id=lambda value: value and value.startswith("post_message_"))

posts = []
for post in postData:
    posts.append(BeautifulSoup(str(post)).get_text().encode("utf-8").strip().replace("\t", ""))

posts_stripped = [x.replace("\n","") for x in posts]

clean_posts.append(posts_stripped)

Finally, I would hugely appreciate it if you could give me code examples of what would work and explain what things to me as if I were literally 9 years old!

Cheers
Diarmaid

Body:
Check if your post_message_ div has another div inside (The quote div). If so extract it. Append the original div (post_message_) text into your list. Replace your for post in postData with this one.

posts = []
for post in postData:
    hasQuote = post.find("div")
     if not hasQuote is None:
        hasQuote.extract()
    posts.append(post.get_text(strip=True))


问:
2 layouts in a CardView ListView that extends 1 layout only?
So I've been searching this for days scouring this forum and other sites for answers/tutorials and still can't figure out if this is even possible.

I want to know if its possible to use a cardview listview that has a date as a "key" and is a header and the rows below populate according to that date key.

Users will be able to populate 2 fields each day. One for an exercise called Burpees and how many they did, as well as how much sets.

That data will be saved into SQLite and will be used to retrieve/populate their progress by day.

Here is a simple scheme that I want to implement in SQLite.

I would like to create a "history page" that displays a listview that uses a cardview theme. The header will be the date. And the amount of burpees they did ACCORDING to that date.

Here is a template I did in android studio to show how i'd like it to look.

答:
Yes, you should be able to do this.  You would just need to first get a list of all available dates

```<code>SELECT DISTINCT Date FROM BurpeeHistory
</code>```

Then you will need to query the records by date for each card

```<code>SELECT * FROM BurpeeHistory WHERE BurpeeHistory.Date = --Card Date Here
</code>```

Body:
Yes, you should be able to do this.  You would just need to first get a list of all available dates

SELECT DISTINCT Date FROM BurpeeHistory

Then you will need to query the records by date for each card

SELECT * FROM BurpeeHistory WHERE BurpeeHistory.Date = --Card Date Here