问:
How can I customise the language of the JSON response in Rails?
I have a controller that has a mobile client. The response is currently in English; however, I'm questioning if there is a way to customise the language of the response.

For example:

English: {   "success": false,   "message": "Error with your login or
password" }

Spanish:{   "success": false,   "message": "Error con tu usuario o
contraseña" }

And, of course, the content of the "message" is going to be located in the language configuration file that Rails has, as follows.

en.yml

or

es.yml

The following is the function from where the response is generated.

```<code>def invalid_login_attempt
    warden.custom_failure!
    render :json => { :success => false, :message=> "Error with your login or password" }, :status => 401
  end
</code>```

答:
Have you tried I18n.t?

```<code>render :json => { :success => false, :message=> I18n.t('your_key') }, :status => 401
</code>```

Based on certain criteria, you can set the locale for every request in the ApplicationController; for example:

```<code>before_action :set_locale

def set_locale
  I18n.locale = request.headers["X-Lang"] || I18n.default_locale
end
</code>```

Body:
I have a controller that has a mobile client. The response is currently in English; however, I'm questioning if there is a way to customise the language of the response.

For example:

English: {   "success": false,   "message": "Error with your login or
password" }

Spanish:{   "success": false,   "message": "Error con tu usuario o
contraseña" }

And, of course, the content of the "message" is going to be located in the language configuration file that Rails has, as follows.

en.yml

or

es.yml

The following is the function from where the response is generated.

def invalid_login_attempt
    warden.custom_failure!
    render :json => { :success => false, :message=> "Error with your login or password" }, :status => 401
  end

Body:
Have you tried I18n.t?

render :json => { :success => false, :message=> I18n.t('your_key') }, :status => 401

Based on certain criteria, you can set the locale for every request in the ApplicationController; for example:

before_action :set_locale

def set_locale
  I18n.locale = request.headers["X-Lang"] || I18n.default_locale
end


来源: stackexchange

问:
How to hide a border?
I have a div class .text-center and I'm trying to hide the border for a button.

The css is:

```<code>.text-center:nth-of-type(even){border-radius: 10px; box-shadow: 0px 0px 10px; border: none;}
</code>```

This gives it a 10px border radius, but won't allow 20px border-radius or allow me to hide the border which is obscuring the button.

Also tried:

```<code>.text-center a {border: none !important; box-shadow : none;}
</code>```

But this hides the border for other buttons. How is that possible when the a is only listed under that div class?

Could this be a specificity issue? Tried framing .text-center within the div class above it-nothing

Html:

```<code>    <div class="event_registration registration">

    <input type="button" class="registration_button button" value="Register for event" />

    <div class="registration_details">
        <p>To register for this event please visit the following URL: <a href="https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779" target="_blank" rel="nofollow">https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779 →</a></p>     </div>
        </div>
                 <!-- For more details information start -->
                          <div class="text-center">
                <a class="link-button" data-toggle="modal" href="https://www.theunderworldcamden.co.uk/event/camden-rocks-festival-2019/"  target="_blank" >View More Details</a>
              </div>

         <!-- For more details infomation end-->
         <!-- Video popup box section start -->
                     <!-- Video popup box section end -->

 <!-- Event Location and Time start-->

    <h3 class="section-title">When & Where</h3>
      <ul class="when-where">
        <li class="event-start-date">
         From:2019-06-01   12:00 PM            </li>
        <li class="event-end-date">
         To:2019-06-02 12:00 AM            </li>
        <li class="event-location">
         Location:
                       <span class="venue-name">
            The Underworld
</code>```

https://adsler.co.uk/event/camden-rocks-festival/

答:
Your A link has a shadow and border on it </p>

```<code>a.link-button {
display: inline-block;
border-radius: 4px;
margin: 0 0 10px;
padding: 8px 7px;
border: none;
box-shadow: none;
float: left;
width: 100%;
}
</code>```

<p>Place this in your CSS and it should remove it from that link button. I would suggest giving the link and ID and remove it only from that link as to not affect any others. </p>

ContentLicense: CC BY-SA 4.0

Title: How to hide a border?

Body:
I have a div class .text-center and I'm trying to hide the border for a button.

The css is:

.text-center:nth-of-type(even){border-radius: 10px; box-shadow: 0px 0px 10px; border: none;}

This gives it a 10px border radius, but won't allow 20px border-radius or allow me to hide the border which is obscuring the button.

Also tried:

.text-center a {border: none !important; box-shadow : none;}

But this hides the border for other buttons. How is that possible when the a is only listed under that div class?

Could this be a specificity issue? Tried framing .text-center within the div class above it-nothing

Html:

    <input type="button" class="registration_button button" value="Register for event" />

To register for this event please visit the following URL: https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779 →

                View More Details

When & Where

         From:2019-06-01   12:00 PM

         To:2019-06-02 12:00 AM

         Location:

            The Underworld

https://adsler.co.uk/event/camden-rocks-festival/

Body:
Your A link has a shadow and border on it

a.link-button {
display: inline-block;
border-radius: 4px;
margin: 0 0 10px;
padding: 8px 7px;
border: none;
box-shadow: none;
float: left;
width: 100%;
}

Place this in your CSS and it should remove it from that link button. I would suggest giving the link and ID and remove it only from that link as to not affect any others.


问:
How to get directory name from path in Java?
I'm listing all the folders that are in a Server.
All the folders are located like this :

=> Ex1 : "C:\A\AB\ABC\FolderToListA-someText"

=> Ex2 : "C:\D\DE\DEF\FolderToListB-someText"

I would like to get the FolderToLists but only returning it once. And not the number of times that are subdirectories.

I've listed every folder and tried using String [] parts, but the problem is that when I list every folder in the parent directory I get duplicate "FolderToList"

Ex: FolderToList contains 2 directories it will return twice de FolderToList.

```<code>for(int j = 0 ; j < folderOrigin.length; j++)
{
    if(folderOrigin[j].toString().contains("-") && folderOrigin[j].length() > 29)
    {
        String fds = folderOrigin[j].toString();;
        fds = fds.substring(0,29);

        String [] parts = fds.split("\\\\");
        String designation = parts[parts.length-1];
    }
}
</code>```

I expect the output to be "FolderToListA","FolderToListB", and not "FolderToListA" "FolderToListA" depending on the subdirectories in FolderA same thing for FolderB

答:
If i understood correctly you just don't want doubles?
If so, you just need to add every designation in your for loop in a Set, to avoid doubles.

Like this:

```<code>Set<String> designations = new HashSet<String>();

for(int j = 0 ; j < folderOrigin.length; j++) {

  if(folderOrigin[j].toString().contains("-") && folderOrigin[j].length() > 29){

    String fds = folderOrigin[j].toString();;
    fds = fds.substring(0,29);

    String [] parts = fds.split("\\\\");
    String designation = parts[parts.length-1];
    designations.add(parts[parts.length-1]);
   }
}
</code>```

Body:
I'm listing all the folders that are in a Server.
All the folders are located like this :

=> Ex1 : "C:\A\AB\ABC\FolderToListA-someText"

=> Ex2 : "C:\D\DE\DEF\FolderToListB-someText"

I would like to get the FolderToLists but only returning it once. And not the number of times that are subdirectories.

I've listed every folder and tried using String [] parts, but the problem is that when I list every folder in the parent directory I get duplicate "FolderToList"

Ex: FolderToList contains 2 directories it will return twice de FolderToList.

for(int j = 0 ; j < folderOrigin.length; j++)
{
    if(folderOrigin[j].toString().contains("-") && folderOrigin[j].length() > 29)
    {
        String fds = folderOrigin[j].toString();;
        fds = fds.substring(0,29);

        String [] parts = fds.split("\\\\");
        String designation = parts[parts.length-1];
    }
}

I expect the output to be "FolderToListA","FolderToListB", and not "FolderToListA" "FolderToListA" depending on the subdirectories in FolderA same thing for FolderB

Body:
If i understood correctly you just don't want doubles?
If so, you just need to add every designation in your for loop in a Set, to avoid doubles.

Like this:

Set<String> designations = new HashSet<String>();

for(int j = 0 ; j < folderOrigin.length; j++) {

  if(folderOrigin[j].toString().contains("-") && folderOrigin[j].length() > 29){

    String fds = folderOrigin[j].toString();;
    fds = fds.substring(0,29);

    String [] parts = fds.split("\\\\");
    String designation = parts[parts.length-1];
    designations.add(parts[parts.length-1]);
   }
}


问:
Is there a way to loop over cells of a particular color in a column?
I have a column (column L) in a spreadsheet in which there are many entries with some duplicate values in that column. Each "group" of duplicate values is colored in a unique color. So i have many colors in my column each of which refers to one group of duplicate values. I have to go through every "Group" so all the cells colored with the same color and do some computation. However, i don't know how to loop through all the cells that are from the same color in a column.

I would really be happy if you could help me with that :)

答:
You could try:

```<code>Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, j As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        'Find Last row of column L
        LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row

        'Set array starting from row 2 to LastRow of column L
        arr = .Range("L2:L" & LastRow)

        For i = LBound(arr) To UBound(arr)

            If .Range("L" & i).Interior.Pattern <> xlNone Then

                For j = LBound(arr) To UBound(arr)

                    If (.Range("L" & j).Interior.Pattern <> xlNone) And (i <> j) Then

                        If .Range("L" & i).Interior.Color = .Range("L" & j).Interior.Color Then

                            If .Range("N" & i).Value = "" Then
                                .Range("N" & i).Value = "Cell L" & i & " has the same background color with cell/s L" & j
                            Else
                                .Range("N" & i).Value = .Range("N" & i).Value & ", L" & j
                            End If

                        End If

                    End If

                Next j

            End If

        Next i

    End With

End Sub
</code>```

Results:

Body:
You could try:

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, j As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        'Find Last row of column L
        LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row

        'Set array starting from row 2 to LastRow of column L
        arr = .Range("L2:L" & LastRow)

        For i = LBound(arr) To UBound(arr)

            If .Range("L" & i).Interior.Pattern <> xlNone Then

                For j = LBound(arr) To UBound(arr)

                    If (.Range("L" & j).Interior.Pattern <> xlNone) And (i <> j) Then

                        If .Range("L" & i).Interior.Color = .Range("L" & j).Interior.Color Then

                            If .Range("N" & i).Value = "" Then
                                .Range("N" & i).Value = "Cell L" & i & " has the same background color with cell/s L" & j
                            Else
                                .Range("N" & i).Value = .Range("N" & i).Value & ", L" & j
                            End If

                        End If

                    End If

                Next j

            End If

        Next i

    End With

End Sub

Results:


问:
Flutter: showDatePicker: Is alternative text for cancel button possible?
I've got an app where the date field can be either a valid date or null. I find the showDatePicker description of "cancel" for the cancel button confusing. Just what does a user expect it to do? It could mean no change or it could mean no date. This is especially so in my case where I want it to mean "No Date". I've copied "date_picker.dart" and changed it to provide an optional alternative text for the "cancel" button.

I originally changed date_picker.dart to allow multiple buttons and clicking a button other than "ok" would return the text of the button. That however meant returning a var (dynamic), and I thought that's probably not acceptable. I then realised that just changing the text of the cancel button would suffice, and all that was required to change "date_picker.dart" was to provide an optional parameter for the alternative text in place of "cancel". There is only a few lines of code involved. The change is very simple. Clicking the cancel button returns null. Changing the text of the cancel button to "no date" will make the result obvious to the user.

If there is no way to achieve this without a program change, then I'll make a request for a change on Github.

Is there currently any way to achieve an alternative text for cancel button in showDatePicker / date_picker.dart?

答:
showDatePicker presents a modal with the child being _DatePickerDialog class, which itself uses localizations.cancelButtonLabel for the Cancel button label.

We can override the cancelButtonLabel property by creating a custom localization delegate based on original English localization.

e.g. This is a delegate that returns default English localization except that cancelButtonLabel property is redefined:

class CancelButtonLocalizationDelegate extends LocalizationsDelegate<MaterialLocalizations> {
  const CancelButtonLocalizationDelegate();

  @override
  bool isSupported(Locale locale) => locale.languageCode == 'en';

  @override
  Future<MaterialLocalizations> load(Locale locale) => Future.value(CancelButtonLocalization());

  @override
  bool shouldReload(CancelButtonLocalizationDelegate old) => false;
}

class CancelButtonLocalization extends DefaultMaterialLocalizations {
  const CancelButtonLocalization();

  @override
  String get cancelButtonLabel => 'Custom Cancel';
}
```

<p>Use <code>Localizations.override</code> to apply changes to the date picker child in the builder, e.g.</p>

<pre class="lang-dart prettyprint-override"><code>showDatePicker(
  context: context,
  // ...,
  builder: (context, child) {
    return Localizations.override(
      context: context,
      delegates: [
        CancelButtonLocalizationDelegate(),
      ],
      child: child,
    );
  }
);
</code>```

Body:
showDatePicker presents a modal with the child being _DatePickerDialog class, which itself uses localizations.cancelButtonLabel for the Cancel button label.

We can override the cancelButtonLabel property by creating a custom localization delegate based on original English localization.

e.g. This is a delegate that returns default English localization except that cancelButtonLabel property is redefined:

class CancelButtonLocalizationDelegate extends LocalizationsDelegate<MaterialLocalizations> {
  const CancelButtonLocalizationDelegate();

  @override
  bool isSupported(Locale locale) => locale.languageCode == 'en';

  @override
  Future<MaterialLocalizations> load(Locale locale) => Future.value(CancelButtonLocalization());

  @override
  bool shouldReload(CancelButtonLocalizationDelegate old) => false;
}

class CancelButtonLocalization extends DefaultMaterialLocalizations {
  const CancelButtonLocalization();

  @override
  String get cancelButtonLabel => 'Custom Cancel';
}

Use Localizations.override to apply changes to the date picker child in the builder, e.g.

showDatePicker(
  context: context,
  // ...,
  builder: (context, child) {
    return Localizations.override(
      context: context,
      delegates: [
        CancelButtonLocalizationDelegate(),
      ],
      child: child,
    );
  }
);


问:
Initialize state with a Spring TestExecutionListener before JUnit rules run
I want to initialize state before each Spring Boot JUnit test case with a TestExecutionListener. This initialization needs to run before the respective callback of JUnit @Rules is called.

I would have expected that the beforeTestMethod would be right for this because its JavaDoc comment says

Pre-processes a test before execution of before lifecycle callbacks of the underlying test framework

Rules contribute "before" callbacks to a test, so I would have expected that beforeTestMethod is executed before the rule. However, the debugger shows that this is not the case!

This is the structure of my code:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners(listeners = MyTestExecutionListener.class, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class MyTest {

    @Autowired
    @Rule
    public MyRule rule;

    @Test
    public void test1() {
        // ...
    }

    // ... more tests
}
</code>```

```<code>public class MyTestExecutionListener implements TestExecutionListener {

    @Override
    public void beforeTestMethod(TestContext testContext) {
        // ...
    }
}
</code>```

```<code>@Component
public class AutoLogin extends ExternalResource {

    @Override
    protected void before() {
        // ...
    }
}
</code>```

I want the methods to execute in the order

beforeTestMethod()

rule.before()

test1()

but the actual order is

rule.before()

beforeTestMethod()

test1()

Any ideas what I'm doing wrong, or which other TestExecutionListener method I should use instead?

答:
In case you want to initialise the state for every test just before the Rule is executed, you should use the prepareTestInstance method of the TestExecutionListener interface.

```<code>@Override
public void prepareTestInstance(TestContext testContext) {
    System.out.println("inside prepareTestInstance");
}
</code>```

That way you will have the methods executed in below order:

prepareTestInstance()

rule.before()

test1()

Do note that prepareTestInstance will be executed before every test method

Body:
I want to initialize state before each Spring Boot JUnit test case with a TestExecutionListener. This initialization needs to run before the respective callback of JUnit @Rules is called.

I would have expected that the beforeTestMethod would be right for this because its JavaDoc comment says

Pre-processes a test before execution of before lifecycle callbacks of the underlying test framework

Rules contribute "before" callbacks to a test, so I would have expected that beforeTestMethod is executed before the rule. However, the debugger shows that this is not the case!

This is the structure of my code:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners(listeners = MyTestExecutionListener.class, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class MyTest {

    @Autowired
    @Rule
    public MyRule rule;

    @Test
    public void test1() {
        // ...
    }

    // ... more tests
}

public class MyTestExecutionListener implements TestExecutionListener {

    @Override
    public void beforeTestMethod(TestContext testContext) {
        // ...
    }
}

@Component
public class AutoLogin extends ExternalResource {

    @Override
    protected void before() {
        // ...
    }
}

I want the methods to execute in the order

beforeTestMethod()

rule.before()

test1()

but the actual order is

rule.before()

beforeTestMethod()

test1()

Any ideas what I'm doing wrong, or which other TestExecutionListener method I should use instead?

Body:
In case you want to initialise the state for every test just before the Rule is executed, you should use the prepareTestInstance method of the TestExecutionListener interface.

@Override
public void prepareTestInstance(TestContext testContext) {
    System.out.println("inside prepareTestInstance");
}

That way you will have the methods executed in below order:

prepareTestInstance()

rule.before()

test1()

Do note that prepareTestInstance will be executed before every test method


问:
Get Data from Stored Procedure to Model EF6 MVC
I have been reading how to use stored procedures in EF6

https://www.entityframeworktutorial.net/entityframework6/code-first-insert-update-delete-stored-procedure-mapping.aspx

But it doesn't show how can i actually get data from a procedure to a model.

For example i have this query

```<code>CREATE PROCEDURE Abastecimentos_Select

AS
BEGIN
    SELECT * FROM OpenQuery(MACPAC, 'SELECT RD6001 as Referencia, RD6002 as UAP, RD6030 as QTD_AB_PDP_W01 FROM D805DATPOR.TRP060D WHERE RD6001 not like ''%OP%'' and RD6001 not like ''%PT%'' ')
END
</code>```

I want to populate my model with it, the properties are the tables returned from the procedure

```<code>public class Abastecimentos
{
    public string Referencia { get; set; }
    public string UAP { get; set; }
    public float QTD_AB_PDP_W01 { get; set; }
}
</code>```

I tried using Fluent API but there is no select option

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Abastecimentos>().MapToStoredProcedures(a => a.//No select)
}
</code>```

I'm using Code First approach.

答:
I decided to use Dapper when mapping SP's to models

public async Task OnGetListAsync()
    {
        IDbConnection con = new SqlConnection(_config.GetConnectionString("DefaultConnection"));

```<code>    var query = await con.QueryAsync<ConsumoViewModel>("GetConsumoCalculado", commandType: CommandType.StoredProcedure);

    return new JsonResult(query.ToList());
}
</code>```

Body:
I have been reading how to use stored procedures in EF6

https://www.entityframeworktutorial.net/entityframework6/code-first-insert-update-delete-stored-procedure-mapping.aspx

But it doesn't show how can i actually get data from a procedure to a model.

For example i have this query

CREATE PROCEDURE Abastecimentos_Select

AS
BEGIN
    SELECT * FROM OpenQuery(MACPAC, 'SELECT RD6001 as Referencia, RD6002 as UAP, RD6030 as QTD_AB_PDP_W01 FROM D805DATPOR.TRP060D WHERE RD6001 not like ''%OP%'' and RD6001 not like ''%PT%'' ')
END

I want to populate my model with it, the properties are the tables returned from the procedure

public class Abastecimentos
{
    public string Referencia { get; set; }
    public string UAP { get; set; }
    public float QTD_AB_PDP_W01 { get; set; }
}

I tried using Fluent API but there is no select option

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Abastecimentos>().MapToStoredProcedures(a => a.//No select)
}

I'm using Code First approach.

Body:
I decided to use Dapper when mapping SP's to models

public async Task OnGetListAsync()
    {
        IDbConnection con = new SqlConnection(_config.GetConnectionString("DefaultConnection"));

    var query = await con.QueryAsync<ConsumoViewModel>("GetConsumoCalculado", commandType: CommandType.StoredProcedure);

    return new JsonResult(query.ToList());
}


问:
How can I pass a parameter to a setTimeout() callback?
I have some JavaScript code that looks like:

```<code>function statechangedPostQuestion()
{
  //alert("statechangedPostQuestion");
  if (xmlhttp.readyState==4)
  {
    var topicId = xmlhttp.responseText;
    setTimeout("postinsql(topicId)",4000);
  }
}

function postinsql(topicId)
{
  //alert(topicId);
}
</code>```

I get an error that topicId is not defined
Everything was working before I used the setTimeout() function.

I want my postinsql(topicId) function to be called after some time.
What should I do?

答:
You can pass the parameter to the setTimeout callback function as:

setTimeout(function, milliseconds, param1, param2, ...)

eg.

```<code>function myFunction() {
  setTimeout(alertMsg, 3000, "Hello");
}

function alertMsg(message) {
    alert(message)
}
</code>```

Body:
I have some JavaScript code that looks like:

function statechangedPostQuestion()
{
  //alert("statechangedPostQuestion");
  if (xmlhttp.readyState==4)
  {
    var topicId = xmlhttp.responseText;
    setTimeout("postinsql(topicId)",4000);
  }
}

function postinsql(topicId)
{
  //alert(topicId);
}

I get an error that topicId is not defined
Everything was working before I used the setTimeout() function.

I want my postinsql(topicId) function to be called after some time.
What should I do?

Body:
You can pass the parameter to the setTimeout callback function as:

setTimeout(function, milliseconds, param1, param2, ...)

eg.

function myFunction() {
  setTimeout(alertMsg, 3000, "Hello");
}

function alertMsg(message) {
    alert(message)
}


问:
download a file to project resources
i use Visual Basic 2008.
hello is it possible to download a file directly to project resources, or to import file to resources on running vb 2008 application.

for example

i have : www.example.com/file.ext

and i want to download it, but not to C:\ or C:\ drives, but to My.Resources.file... is it possible?

thank you

答:
This isn’t possible. Resources in your program are fixed: once your program is running, it cannot modify its resources.

Apart from that you can use the WebClient.DownloadData method to download data into a variable without saving it to disc.

ContentLicense: CC BY-SA 3.0

Title: download a file to project resources


答:
If this button is unique then you should target it with an #id.

However if this was me I would make a borderless class and apply it only to the buttons I want to omit borders from.

As long as this class is listed after your other button styles it will overide any noted stylings.

.borderless {
  border: none;
  box-shadow: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>View More Details</code>```

NOTE

Ensure the specificity of this style is greater than your other classes to ensure it is applied and to avoid using !important

If this will only be applied to anchor tags for example use:

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

Title: How to hide a border?

Body:
If this button is unique then you should target it with an #id.

However if this was me I would make a borderless class and apply it only to the buttons I want to omit borders from.

As long as this class is listed after your other button styles it will overide any noted stylings.

.borderless {
  border: none;
  box-shadow: none;
}

<a class="link-button borderless" data-toggle="modal" href="https://www.theunderworldcamden.co.uk/event/camden-rocks-festival-2019/" target="_blank">View More Details</a>

NOTE

Ensure the specificity of this style is greater than your other classes to ensure it is applied and to avoid using !important

If this will only be applied to anchor tags for example use:

a.borderless{}


问:
List View \ Database \ ComboBox , c#
On my form there is 6 Combo-Boxes. I have stored their values in a table "TableauCombo" to use again. I set a "for" to browse the table and for each step, the program has to write in the variable "query" all the values that are in the table. ( To create the SQL query). Next, I launch the SQL Request and have to write the values in the list view. I have some errors, but I'm unable to resolve them. Can you help me?

I put the code and the errors underneath

```<code> string[] TableauCombo = new string[7];
                {
                    TableauCombo[0] = "ID_Rad=@" + CatégorieRadiologique_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[1] = "Code_Etat=@" + CodeEtatFS_ComboBox_Home.SelectedIndex.ToString(); ;
                    TableauCombo[2] = "Code_Producteur=@" + Producteur_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[3] = "Code_Centre=@" + Centre_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[4] = "Code_StationdeDestination=@" + StationDestination_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[5] = "Code_Conditionnement=@" + Conditionnement_ComboBox_Home.SelectedIndex.ToString();
                };

                string requery = "";
                for (int i = 0; i < TableauCombo.Length; i++)
                {
                    requery = requery + TableauCombo[i];
                }
                LW_FS_Home.Items.Clear();
                MySqlCommand cmd = new MySqlCommand("SELECT FS FROM cdh.fiche WHERE " + requery + " ", connection);            // Requète SQL SELECT
                MessageBox.Show("Requery" + requery + "");
                cmd.Parameters.AddWithValue("@ID_Rad", CatégorieRadiologique_ComboBox_Home.SelectedIndex.ToString());          //Récupération du ID_Rad souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Etat", CodeEtatFS_ComboBox_Home.ToString());                                //Récupération du Code_Etat souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Producteur", Producteur_ComboBox_Home.ToString());                          //Récupération du Code_Producteur souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Centre", Centre_ComboBox_Home.ToString());                                  //Récupération du Code_Centre souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_StationdeDestination", StationDestination_ComboBox_Home.ToString());        //Récupération du Code_StationdeDestination souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Conditionnement", Conditionnement_ComboBox_Home.Text);                      //Récupération du Code_Conditionnement souhaité par l'utilisateur

                if (Connecté)
                {
                    using (MySqlDataReader Lire = cmd.ExecuteReader())
                    {
                        while (Lire.Read())  // Boucle While qui regarde toutes les infos que l'on souhaite voir avec la méthode "lire"
                        {
                            string FS = Lire["@FS"].ToString();                                                               // Declaration des colonnes et leurs équivalents (remplacants)
                            string ID_Rad = Lire["@ID_Rad"].ToString();
                            string Code_Etat = Lire["@Code_Etat"].ToString();
                            string Code_Producteur = Lire["@Code_Producteur"].ToString();
                            string Code_Centre = Lire["@Code_Centre"].ToString();
                            string Code_StationdeDestination = Lire["@Code_StationdeDestination"].ToString();
                            string Code_Conditionnement = Lire["@Code_Conditionnement"].ToString();

                            LW_FS_Home.Items.Add(new ListViewItem(new[] { FS, ID_Rad, Code_Etat, Code_Producteur, Code_Centre, Code_StationdeDestination, Code_Conditionnement }));// Ajout des nouvelles valeurs dans la list view
                        }
                    }
                    connection.Close();
                }
                else
                {
                    MessageBox.Show("Erreur de connexion");
                }
}
</code>```

The error :

"MySqlException : Parameter '@1' must be defined."

But the program can run itself. (Comment : test for the end) The value who is returned is : "RequeryID_Rad=@1+..........". (Picture) ERROR

Just to be explicit, all combobox has declared like that :

```<code>try //Début Try/Catch pour le ComboBox des catégorie Radiologiqque
{
    connection.Open();
    CatégorieRadiologique_ComboBox_Home.DropDownStyle = ComboBoxStyle.DropDownList; //ReadOnly sur la comboBox
    string selectQuery = "SELECT ID_Rad , Radiologique FROM cdh.ctg_rad";
    MySqlCommand command = new MySqlCommand(selectQuery, connection);
    MySqlDataReader reader = command.ExecuteReader();

    while (reader.Read()) {
        CatégorieRadiologique_ComboBox_Home.Items.Add(reader.GetString("Radiologique"));
        string[, ] TableauRad = new string[1, 2] {
            {
                "ID_Rad", "Radiologique"
            },

        };
    }
    connection.Close();
} catch (MySqlException cn)

{
    MessageBox.Show(cn.Message);
    connection.Close();
}
</code>```

I think my "for" it's wrong or the link with the listview idk..

答:
Please replace code to</p>

```<code>string[] TableauCombo = new string[6];
            {
                TableauCombo[0] = "ID_Rad=@ID_Rad";
                TableauCombo[1] = "Code_Etat=@Code_Etat";
                TableauCombo[2] = "Code_Producteur=@Code_Producteur";
                TableauCombo[3] = "Code_Centre=@Code_Centre";
                TableauCombo[4] = "Code_StationdeDestination=@Code_StationdeDestination";
                TableauCombo[5] = "Code_Conditionnement=@Code_Conditionnement";
            };
</code>```

Title: List View \ Database \ ComboBox , c#

Body:
On my form there is 6 Combo-Boxes. I have stored their values in a table "TableauCombo" to use again. I set a "for" to browse the table and for each step, the program has to write in the variable "query" all the values that are in the table. ( To create the SQL query). Next, I launch the SQL Request and have to write the values in the list view. I have some errors, but I'm unable to resolve them. Can you help me?

I put the code and the errors underneath

 string[] TableauCombo = new string[7];
                {
                    TableauCombo[0] = "ID_Rad=@" + CatégorieRadiologique_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[1] = "Code_Etat=@" + CodeEtatFS_ComboBox_Home.SelectedIndex.ToString(); ;
                    TableauCombo[2] = "Code_Producteur=@" + Producteur_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[3] = "Code_Centre=@" + Centre_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[4] = "Code_StationdeDestination=@" + StationDestination_ComboBox_Home.SelectedIndex.ToString();
                    TableauCombo[5] = "Code_Conditionnement=@" + Conditionnement_ComboBox_Home.SelectedIndex.ToString();
                };

                string requery = "";
                for (int i = 0; i < TableauCombo.Length; i++)
                {
                    requery = requery + TableauCombo[i];
                }
                LW_FS_Home.Items.Clear();
                MySqlCommand cmd = new MySqlCommand("SELECT FS FROM cdh.fiche WHERE " + requery + " ", connection);            // Requète SQL SELECT
                MessageBox.Show("Requery" + requery + "");
                cmd.Parameters.AddWithValue("@ID_Rad", CatégorieRadiologique_ComboBox_Home.SelectedIndex.ToString());          //Récupération du ID_Rad souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Etat", CodeEtatFS_ComboBox_Home.ToString());                                //Récupération du Code_Etat souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Producteur", Producteur_ComboBox_Home.ToString());                          //Récupération du Code_Producteur souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Centre", Centre_ComboBox_Home.ToString());                                  //Récupération du Code_Centre souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_StationdeDestination", StationDestination_ComboBox_Home.ToString());        //Récupération du Code_StationdeDestination souhaité par l'utilisateur
                cmd.Parameters.AddWithValue("@Code_Conditionnement", Conditionnement_ComboBox_Home.Text);                      //Récupération du Code_Conditionnement souhaité par l'utilisateur

                if (Connecté)
                {
                    using (MySqlDataReader Lire = cmd.ExecuteReader())
                    {
                        while (Lire.Read())  // Boucle While qui regarde toutes les infos que l'on souhaite voir avec la méthode "lire"
                        {
                            string FS = Lire["@FS"].ToString();                                                               // Declaration des colonnes et leurs équivalents (remplacants)
                            string ID_Rad = Lire["@ID_Rad"].ToString();
                            string Code_Etat = Lire["@Code_Etat"].ToString();
                            string Code_Producteur = Lire["@Code_Producteur"].ToString();
                            string Code_Centre = Lire["@Code_Centre"].ToString();
                            string Code_StationdeDestination = Lire["@Code_StationdeDestination"].ToString();
                            string Code_Conditionnement = Lire["@Code_Conditionnement"].ToString();

                            LW_FS_Home.Items.Add(new ListViewItem(new[] { FS, ID_Rad, Code_Etat, Code_Producteur, Code_Centre, Code_StationdeDestination, Code_Conditionnement }));// Ajout des nouvelles valeurs dans la list view
                        }
                    }
                    connection.Close();
                }
                else
                {
                    MessageBox.Show("Erreur de connexion");
                }
}

The error :

"MySqlException : Parameter '@1' must be defined."

But the program can run itself. (Comment : test for the end) The value who is returned is : "RequeryID_Rad=@1+..........". (Picture) ERROR

Just to be explicit, all combobox has declared like that :

try //Début Try/Catch pour le ComboBox des catégorie Radiologiqque
{
    connection.Open();
    CatégorieRadiologique_ComboBox_Home.DropDownStyle = ComboBoxStyle.DropDownList; //ReadOnly sur la comboBox
    string selectQuery = "SELECT ID_Rad , Radiologique FROM cdh.ctg_rad";
    MySqlCommand command = new MySqlCommand(selectQuery, connection);
    MySqlDataReader reader = command.ExecuteReader();

    while (reader.Read()) {
        CatégorieRadiologique_ComboBox_Home.Items.Add(reader.GetString("Radiologique"));
        string[, ] TableauRad = new string[1, 2] {
            {
                "ID_Rad", "Radiologique"
            },

        };
    }
    connection.Close();
} catch (MySqlException cn)

{
    MessageBox.Show(cn.Message);
    connection.Close();
}

I think my "for" it's wrong or the link with the listview idk..

Body:
Please replace code to

string[] TableauCombo = new string[6];
            {
                TableauCombo[0] = "ID_Rad=@ID_Rad";
                TableauCombo[1] = "Code_Etat=@Code_Etat";
                TableauCombo[2] = "Code_Producteur=@Code_Producteur";
                TableauCombo[3] = "Code_Centre=@Code_Centre";
                TableauCombo[4] = "Code_StationdeDestination=@Code_StationdeDestination";
                TableauCombo[5] = "Code_Conditionnement=@Code_Conditionnement";
            };


问:
Bash script and escaping special characters in password
I have a shell script which is trying to login into a box with password having special character.

```<code>sshpass  -p"\"$Passw\"" ssh -tt -o StrictHostKeyChecking=no root@"${Hostname}"
</code>```

I am passing Hostname and Password parameter from Jenkins. Password conatins $ characater for example n$1sachin .  But I am not able to login. Can anyone please help?

I tried different option but its not working for me.

答:
I have encounter similar problem, finally using \ to escape special char in password is work for me, such as:

from xxx)xxx#?xxx to xxx\)xxx\#\?xxx

full command like this:

sshpass -p xxx\)xxx\#\?xxx rsync -avzh ...

Body:
I have a shell script which is trying to login into a box with password having special character.

sshpass  -p"\"$Passw\"" ssh -tt -o StrictHostKeyChecking=no root@"${Hostname}"

I am passing Hostname and Password parameter from Jenkins. Password conatins $ characater for example n$1sachin .  But I am not able to login. Can anyone please help?

I tried different option but its not working for me.


问:
How to make If Statement inside foreach in ASP.Net view page in my case?
I am trying to display 4 columns in a single row. So after every 4 data there will be one opening
 and at the end closing

```<code>@{
    int i = 1;
}
@{
    foreach (var item in ViewBag.Prod)
    {
        if (i <= 4)
        {
            if (i == 1)
            {
                <div class="row mobile-bg-pic" id="sale-pic">  //OPENING div
                  }

                    <div class="col-6 col-md-3 col-nopadding">
                        <div class="card" data-itmid="@item.ProductID">
                            <img class="card-img-top" src="~/@(item.ImageLocation)/@(item.ImageName)" alt="Card image cap">
                            <div class="card-body">
                                <div class="card-title"><a>@item.Name</a></div>
                                <div class="card-text card-price">RM @item.Price <del class="without-offer-price"> RM @(item.FakePrice)</del><span class="discount">@(item.Discount)% offer</span></div>
                            </div>
                        </div>
                    </div>
                    if (i == 1)
                    {
                </div>    //ENDING div
                i++;
            }
            else if (i <= 3)
            {
                i++;
            }
            if (i == 4)
            {
                i = 0;
            }
        }

    }
}
</code>```

but it doesn't work as I expected it to. Actual rendered html code in the browser is below:

```<code><div class="row mobile-bg-pic" id="sale-pic">
        }

            <div class="col-6 col-md-3 col-nopadding">
                    <div class="card" data-itmid="5ddc742f-df82-43d7-ab3d-073c7dfdb587">
                        <img class="card-img-top loading" src="~/Content/images/Batch17/22-D.jpg" alt="Card image cap" data-was-processed="true">
                        <div class="card-body">
                            <div class="card-title"><a>Diamond songket</a></div>
                            <div class="card-text card-price">US 45 <del class="without-offer-price"> RM 65</del><span class="discount">20% offer</span></div>
                        </div>
                    </div>
                </div>
        if (i == 1)
        {
            </div>
</code>```

I see this stackoverflow link, But I don't understand. But this is the one I want

答:
You can achieve what you want using the razor @helper syntax without changing your logic too much :</p>

```<code>@{
    int i = 1;
}
@{
    foreach (var item in ViewBag.Prod)
    {
        if (i <= 4)
        {
            if (i == 1)
            {
                <div class="row mobile-bg-pic" id="sale-pic">
                    @DisplayItem(item)
                </div>
                i++;
            }
            else
            {
                @DisplayItem(item)
                if (i <= 3)
                {
                    i++;
                }
            }
            if (i == 4)
            {
                i = 0;
            }
        }
    }
}

@helper DisplayItem(dynamic item)
{
    <div class="col-6 col-md-3 col-nopadding">
        <div class="card" data-itmid="@item.ProductID">
            <img class="card-img-top" src="~/@(item.ImageLocation)/@(item.ImageName)" alt="Card image cap">
            <div class="card-body">
                <div class="card-title"><a>@item.Name</a></div>
                <div class="card-text card-price">RM @item.Price <del class="without-offer-price"> RM @(item.FakePrice)</del><span class="discount">@(item.Discount)% offer</span></div>
            </div>
        </div>
    </div>
}
</code>```

Body:
I am trying to display 4 columns in a single row. So after every 4 data there will be one opening
 and at the end closing

@{
    int i = 1;
}
@{
    foreach (var item in ViewBag.Prod)
    {
        if (i <= 4)
        {
            if (i == 1)
            {

  //OPENING div
                  }

@item.Name

RM @item.Price  RM @(item.FakePrice)@(item.Discount)% offer

                    if (i == 1)
                    {

    //ENDING div
                i++;
            }
            else if (i <= 3)
            {
                i++;
            }
            if (i == 4)
            {
                i = 0;
            }
        }

    }
}

but it doesn't work as I expected it to. Actual rendered html code in the browser is below:

        }

Diamond songket

US 45  RM 6520% offer

        if (i == 1)
        {

I see this stackoverflow link, But I don't understand. But this is the one I want

Body:
You can achieve what you want using the razor @helper syntax without changing your logic too much :

@{
    int i = 1;
}
@{
    foreach (var item in ViewBag.Prod)
    {
        if (i <= 4)
        {
            if (i == 1)
            {
                <div class="row mobile-bg-pic" id="sale-pic">
                    @DisplayItem(item)
                </div>
                i++;
            }
            else
            {
                @DisplayItem(item)
                if (i <= 3)
                {
                    i++;
                }
            }
            if (i == 4)
            {
                i = 0;
            }
        }
    }
}

@helper DisplayItem(dynamic item)
{
    <div class="col-6 col-md-3 col-nopadding">
        <div class="card" data-itmid="@item.ProductID">
            <img class="card-img-top" src="~/@(item.ImageLocation)/@(item.ImageName)" alt="Card image cap">
            <div class="card-body">
                <div class="card-title"><a>@item.Name</a></div>
                <div class="card-text card-price">RM @item.Price <del class="without-offer-price"> RM @(item.FakePrice)</del><span class="discount">@(item.Discount)% offer</span></div>
            </div>
        </div>
    </div>
}


问:
Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)
I am developing a web page using JavaScript and HTML, everything was working
good when I have received this list of errors from my HTML page:

The resource from “https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
```

These errors appeared after an automatic browser update (Mozilla Firefox), may
be something has been changed in the set up. Do you know any way to solve this
problem?

答:
It might be a wrong path.
Ensure in your main app file you have:

```<code>app.use(express.static(path.join(__dirname,"public")));
</code>```

Example link to your css as:

```<code><link href="/css/clean-blog.min.css" rel="stylesheet">
</code>```

similar for link to js files:

```<code><script src="/js/clean-blog.min.js"></script>
</code>```

Body:
I am developing a web page using JavaScript and HTML, everything was working
good when I have received this list of errors from my HTML page:

The resource from “https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

These errors appeared after an automatic browser update (Mozilla Firefox), may
be something has been changed in the set up. Do you know any way to solve this
problem?

Body:
It might be a wrong path.
Ensure in your main app file you have:

app.use(express.static(path.join(__dirname,"public")));

Example link to your css as:

<link href="/css/clean-blog.min.css" rel="stylesheet">

similar for link to js files:

<script src="/js/clean-blog.min.js"></script>


问:
count items in an one array, if the number of instances is the same as the length of a different array, return the item, javascript
I have two arrays, id like to return the items from array1 if they appear as much as the length of array2

I understand how to do this in python, but I cant figure out how to do it in javascript

arr1 = ['a', 'b', 'c', 'c']
arr2 = ['one', 'two']
arr3 = []
```

<pre class="lang-py prettyprint-override"><code>for i in arr1:
    if arr1.count(i) == len(arr2):
    arr3.append(i)
</code>```

desired result would be ['c']

Can someone please help me write this in javascript?

答:
Nested loops could do that. One for the for, and one for the count:

var arr1 = ['a', 'b', 'c', 'c'];
var arr2 = ['one', 'two'];
var arr3 = [];

var unique = new Set(arr1);
var len2 = arr2.length;
for(var i of unique){
  var count = 0;
  for(var j of arr1)
    if(j === i)
      count++;
  if(count == len2)
    arr3.push(i);
}

console.log(arr3);```

Side remark: I think that Python code would result in ['c','c'], though I have not actually tried.

Body:
I have two arrays, id like to return the items from array1 if they appear as much as the length of array2

I understand how to do this in python, but I cant figure out how to do it in javascript

arr1 = ['a', 'b', 'c', 'c']
arr2 = ['one', 'two']
arr3 = []

for i in arr1:
    if arr1.count(i) == len(arr2):
    arr3.append(i)

desired result would be ['c']

Can someone please help me write this in javascript?

Body:
Nested loops could do that. One for the for, and one for the count:

var arr1 = ['a', 'b', 'c', 'c'];
var arr2 = ['one', 'two'];
var arr3 = [];

var unique = new Set(arr1);
var len2 = arr2.length;
for(var i of unique){
  var count = 0;
  for(var j of arr1)
    if(j === i)
      count++;
  if(count == len2)
    arr3.push(i);
}

console.log(arr3);

Side remark: I think that Python code would result in ['c','c'], though I have not actually tried.


问:
rxjs - simple from / start / duration problem
I'm trying to implement a simple from / to / duration form in rxjs to learn.

It would be much simpler to just use getter / setters but I want to learn it.

Can someone help me find a simple solution with rxjs to solve this problem?

```<code>From : Start time of day
To : End time of day
Time : Duration between to and from
</code>```

If user changes To, Time should update, unless From is empty

If user changes Time, To should update, unless From is empty

I believe that my current implementation has many problems because it results in an infinite loop. Also, it seems like because I subscribe many times, I receive observable values in a deferred way.

```<code>import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { distinct, distinctUntilChanged, filter, map } from 'rxjs/operators';

export class Clock implements OnInit {

  fromSubject: BehaviorSubject<string> = new BehaviorSubject('');
  toSubject: BehaviorSubject<string> = new BehaviorSubject('');
  timeSubject: BehaviorSubject<string> = new BehaviorSubject('');

  from$: Observable<string>;
  to$: Observable<string>;
  time$: Observable<string>;
  seconds$: BehaviorSubject<number> = new BehaviorSubject(0);

  _from: string;
  _to: string;
  _time: string;

  get from(): string {
    return this._from;
  }
  set from(value: string) {
    this.fromSubject.next(value);
  }
  get to(): string {
    return this._to;
  }
  set to(value: string) {
    this.toSubject.next(value);
  }
  get time(): string {
    return this._time;
  }
  set time(value: string) {
    this.timeSubject.next(value);
  }

  ngOnInit() {

    this.from$ = this.fromSubject.pipe(
      distinctUntilChanged(),
      map(from => {
        if (!from) {
          return from;
        } else if (!isNaN(+from)) {
          return from + ':00';
        } else {
          const seconds = this.convertTimeToSeconds(from);
          return this.convertSecondsToTime(seconds);
        }
      })
    );

    this.to$ = this.toSubject.pipe(
      distinctUntilChanged(),
      map(to => {
        if (!to) {
          return to;
        } else if (!isNaN(+to)) {
          return to + ':00';
        } else {
          const seconds = this.convertTimeToSeconds(to);
          const txt = this.convertSecondsToTime(seconds);
          return txt;
        }
      })
    );

    this.time$ = this.timeSubject.pipe(
      distinctUntilChanged(),
      map(time => {
        if (!time) {
          return time;
        } else if (!isNaN(+time)) {
          return time + 'h';
        } else {
          const seconds = this.convertDurationToSeconds(time);
          console.log('TimeSeconds ' + seconds);
          return this.convertSecondsToDuration(seconds);
        }
      })
    );

    this.from$.subscribe(f => {
      this._from = f;
    });

    this.to$.subscribe(t => {
      this._to = t;
    });

    this.time$.subscribe(t => {
      this._time = t;
      const seconds = this.convertDurationToSeconds(t);
      this.seconds$.next(seconds);
    });

    combineLatest(this.from$, this.seconds$)
      .pipe(filter(([from, seconds]) => !!from && !!seconds))
      .subscribe(([from, seconds]) => {
        if (!from) {
          return;
        }
        const fromHours = this.getHours(from);
        const fromMins = this.getMinutes(from);

        const fromSeconds = fromHours * 3600 + fromMins * 60;
        const toSeconds = fromSeconds + seconds;

        const to = this.convertSecondsToTime(toSeconds);
        const time = this.convertSecondsToDuration(toSeconds - fromSeconds);

        this.toSubject.next(to);
        this.timeSubject.next(time);
      });

    combineLatest(this.from$, this.to$).subscribe(([from, to]) => {
      if (!from || !to) {
        return;
      }
      const fromHours = this.getHours(from);
      const toHours = this.getHours(to);
      const fromMins = this.getMinutes(from);
      const toMins = this.getMinutes(to);
      const seconds = (toHours - fromHours) * 3600 + (toMins - fromMins) * 60;
      this.seconds$.next(seconds);
    });

    const now = new Date();
    const hours = now.getHours();
    let minutes = now.getMinutes();
    minutes = minutes - (minutes % 15);
    this.to = hours + ':' + minutes;
    this.from = '8:00';
    this.to = '10:00';
  }

  convertDurationToSeconds = str => {
    let seconds = 0;
    const hours = str.match(/^(\d+)\s*(?:h|hours)/);
    const minutes = str.match(/^(?:\d+h)?(\d+)\s*(?:(?:m)|(?:min))?$/);
    if (hours) {
      seconds += parseInt(hours[1], 10) * 3600;
    }
    if (minutes) {
      seconds += parseInt(minutes[1], 10) * 60;
    }
    return seconds;
  }

  convertTimeToSeconds = str => {
    let seconds = 0;
    const hours = this.getHours(str);
    const minutes = this.getMinutes(str);
    if (hours) {
      seconds += hours * 3600;
    }
    if (minutes) {
      seconds += minutes * 60;
    }
    return seconds;
  }

  convertSecondsToDuration(seconds: number) {
    const durationHours = Math.floor(seconds / 3600);
    const durationMinutes = Math.floor((seconds - durationHours * 3600) / 60);
    let durationStr = '';
    if (durationHours > 0) {
      durationStr = durationHours + 'h';
    }
    if (durationMinutes > 0) {
      durationStr = durationStr + durationMinutes + 'm';
    }
    if (!durationStr) {
      durationStr = '0h';
    }
    console.log('durationStr ' + durationStr + ' seconds : ' + seconds);
    return durationStr;
  }

  convertSecondsToTime(seconds: number) {
    const durationHours = Math.floor(seconds / 3600);
    const durationMinutes = Math.floor((seconds - durationHours * 3600) / 60);
    const durationHoursStr = durationHours.toString();
    const durationMinutesStr =
      durationMinutes < 10 ? '0' + durationMinutes : durationMinutes;
    const timeStr = durationHoursStr + ':' + durationMinutesStr;
    console.log(seconds, durationHours, durationMinutes, timeStr);
    return timeStr;
  }

  getHours = str => {
    const hours = str.match(/^((?:(2[0-3])|(1[0-9])|0?[0-9])):(?:[0-5][0-9])/);
    if (hours) {
      return parseInt(hours[1], 10);
    }
    return 0;
  }

  getMinutes = str => {
    const minutes = str.match(
      /^(?:(?:2[0-3])|(?:1[0-9])|0?[0-9]):((?:[0-5][0-9])|[0-9])/
    );
    if (minutes) {
      return parseInt(minutes[1], 10);
    }
    return 0;
  }
}

</code>```

答:
I do have to say, as a "simple example" of RxJS you sure picked one with some awkward business logic. :) (For example, another edge case is if the user changes "from" and has already changed time, does time stay the same and "to" update?).

I try to avoid BehaviorSubjects until I absolutely have to use them, so for now let's start with Subjects and see if that works:

```<code>from = new Subject<string>();
to = new Subject<string>();
time = new Subject<string>();
</code>```

from is only ever set from its input (the UI, I'm guessing). So let's just define it as an Observable with no additional handling:

from$ = this.from.asObservable()

to is set from its input or from the "timeFrom" stream (sorry, couldn't up with a better name):

```<code>timeFrom$ = combineLatest(this.time, this.from).pipe(
    map([time, from] => time - from) // I'm leaving out formatting in this example
)
</code>```

The beauty of combineLatest is it satisfies your requirement that we only use timeFrom if "from" has a value, since combineLatest doesn't emit unless both streams have emitted. So our to$ stream becomes:

```<code>to$ = merge(
    this.to,
    this.timeFrom$
)
</code>```

Similarly, we can define time as coming from either its input or the "toFrom" stream:

```<code>toFrom$ = combineLatest(this.to, this.from).pipe(
    map([to, from] => from - to)
)
</code>```

And that results in:

```<code>time$ = merge(
    this.time,
    this.toFrom$
)
</code>```

By breaking apart the problem into 5 streams instead of 3, we've now avoiding the endless loop you mention.

I'm hoping this made sense. For simplicity, I left out the time formatting you had in place.

Body:
I'm trying to implement a simple from / to / duration form in rxjs to learn.

It would be much simpler to just use getter / setters but I want to learn it.

Can someone help me find a simple solution with rxjs to solve this problem?

From : Start time of day
To : End time of day
Time : Duration between to and from

If user changes To, Time should update, unless From is empty

If user changes Time, To should update, unless From is empty

I believe that my current implementation has many problems because it results in an infinite loop. Also, it seems like because I subscribe many times, I receive observable values in a deferred way.

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { distinct, distinctUntilChanged, filter, map } from 'rxjs/operators';

export class Clock implements OnInit {

  fromSubject: BehaviorSubject<string> = new BehaviorSubject('');
  toSubject: BehaviorSubject<string> = new BehaviorSubject('');
  timeSubject: BehaviorSubject<string> = new BehaviorSubject('');

  from$: Observable<string>;
  to$: Observable<string>;
  time$: Observable<string>;
  seconds$: BehaviorSubject<number> = new BehaviorSubject(0);

  _from: string;
  _to: string;
  _time: string;

  get from(): string {
    return this._from;
  }
  set from(value: string) {
    this.fromSubject.next(value);
  }
  get to(): string {
    return this._to;
  }
  set to(value: string) {
    this.toSubject.next(value);
  }
  get time(): string {
    return this._time;
  }
  set time(value: string) {
    this.timeSubject.next(value);
  }

  ngOnInit() {

    this.from$ = this.fromSubject.pipe(
      distinctUntilChanged(),
      map(from => {
        if (!from) {
          return from;
        } else if (!isNaN(+from)) {
          return from + ':00';
        } else {
          const seconds = this.convertTimeToSeconds(from);
          return this.convertSecondsToTime(seconds);
        }
      })
    );

    this.to$ = this.toSubject.pipe(
      distinctUntilChanged(),
      map(to => {
        if (!to) {
          return to;
        } else if (!isNaN(+to)) {
          return to + ':00';
        } else {
          const seconds = this.convertTimeToSeconds(to);
          const txt = this.convertSecondsToTime(seconds);
          return txt;
        }
      })
    );

    this.time$ = this.timeSubject.pipe(
      distinctUntilChanged(),
      map(time => {
        if (!time) {
          return time;
        } else if (!isNaN(+time)) {
          return time + 'h';
        } else {
          const seconds = this.convertDurationToSeconds(time);
          console.log('TimeSeconds ' + seconds);
          return this.convertSecondsToDuration(seconds);
        }
      })
    );

    this.from$.subscribe(f => {
      this._from = f;
    });

    this.to$.subscribe(t => {
      this._to = t;
    });

    this.time$.subscribe(t => {
      this._time = t;
      const seconds = this.convertDurationToSeconds(t);
      this.seconds$.next(seconds);
    });

    combineLatest(this.from$, this.seconds$)
      .pipe(filter(([from, seconds]) => !!from && !!seconds))
      .subscribe(([from, seconds]) => {
        if (!from) {
          return;
        }
        const fromHours = this.getHours(from);
        const fromMins = this.getMinutes(from);

        const fromSeconds = fromHours * 3600 + fromMins * 60;
        const toSeconds = fromSeconds + seconds;

        const to = this.convertSecondsToTime(toSeconds);
        const time = this.convertSecondsToDuration(toSeconds - fromSeconds);

        this.toSubject.next(to);
        this.timeSubject.next(time);
      });

    combineLatest(this.from$, this.to$).subscribe(([from, to]) => {
      if (!from || !to) {
        return;
      }
      const fromHours = this.getHours(from);
      const toHours = this.getHours(to);
      const fromMins = this.getMinutes(from);
      const toMins = this.getMinutes(to);
      const seconds = (toHours - fromHours) * 3600 + (toMins - fromMins) * 60;
      this.seconds$.next(seconds);
    });

    const now = new Date();
    const hours = now.getHours();
    let minutes = now.getMinutes();
    minutes = minutes - (minutes % 15);
    this.to = hours + ':' + minutes;
    this.from = '8:00';
    this.to = '10:00';
  }

  convertDurationToSeconds = str => {
    let seconds = 0;
    const hours = str.match(/^(\d+)\s*(?:h|hours)/);
    const minutes = str.match(/^(?:\d+h)?(\d+)\s*(?:(?:m)|(?:min))?$/);
    if (hours) {
      seconds += parseInt(hours[1], 10) * 3600;
    }
    if (minutes) {
      seconds += parseInt(minutes[1], 10) * 60;
    }
    return seconds;
  }

  convertTimeToSeconds = str => {
    let seconds = 0;
    const hours = this.getHours(str);
    const minutes = this.getMinutes(str);
    if (hours) {
      seconds += hours * 3600;
    }
    if (minutes) {
      seconds += minutes * 60;
    }
    return seconds;
  }

  convertSecondsToDuration(seconds: number) {
    const durationHours = Math.floor(seconds / 3600);
    const durationMinutes = Math.floor((seconds - durationHours * 3600) / 60);
    let durationStr = '';
    if (durationHours > 0) {
      durationStr = durationHours + 'h';
    }
    if (durationMinutes > 0) {
      durationStr = durationStr + durationMinutes + 'm';
    }
    if (!durationStr) {
      durationStr = '0h';
    }
    console.log('durationStr ' + durationStr + ' seconds : ' + seconds);
    return durationStr;
  }

  convertSecondsToTime(seconds: number) {
    const durationHours = Math.floor(seconds / 3600);
    const durationMinutes = Math.floor((seconds - durationHours * 3600) / 60);
    const durationHoursStr = durationHours.toString();
    const durationMinutesStr =
      durationMinutes < 10 ? '0' + durationMinutes : durationMinutes;
    const timeStr = durationHoursStr + ':' + durationMinutesStr;
    console.log(seconds, durationHours, durationMinutes, timeStr);
    return timeStr;
  }

  getHours = str => {
    const hours = str.match(/^((?:(2[0-3])|(1[0-9])|0?[0-9])):(?:[0-5][0-9])/);
    if (hours) {
      return parseInt(hours[1], 10);
    }
    return 0;
  }

  getMinutes = str => {
    const minutes = str.match(
      /^(?:(?:2[0-3])|(?:1[0-9])|0?[0-9]):((?:[0-5][0-9])|[0-9])/
    );
    if (minutes) {
      return parseInt(minutes[1], 10);
    }
    return 0;
  }
}

Body:
I do have to say, as a "simple example" of RxJS you sure picked one with some awkward business logic. :) (For example, another edge case is if the user changes "from" and has already changed time, does time stay the same and "to" update?).

I try to avoid BehaviorSubjects until I absolutely have to use them, so for now let's start with Subjects and see if that works:

from = new Subject<string>();
to = new Subject<string>();
time = new Subject<string>();

from is only ever set from its input (the UI, I'm guessing). So let's just define it as an Observable with no additional handling:

from$ = this.from.asObservable()

to is set from its input or from the "timeFrom" stream (sorry, couldn't up with a better name):

timeFrom$ = combineLatest(this.time, this.from).pipe(
    map([time, from] => time - from) // I'm leaving out formatting in this example
)

The beauty of combineLatest is it satisfies your requirement that we only use timeFrom if "from" has a value, since combineLatest doesn't emit unless both streams have emitted. So our to$ stream becomes:

to$ = merge(
    this.to,
    this.timeFrom$
)

Similarly, we can define time as coming from either its input or the "toFrom" stream:

toFrom$ = combineLatest(this.to, this.from).pipe(
    map([to, from] => from - to)
)

And that results in:

time$ = merge(
    this.time,
    this.toFrom$
)

By breaking apart the problem into 5 streams instead of 3, we've now avoiding the endless loop you mention.

I'm hoping this made sense. For simplicity, I left out the time formatting you had in place.


问:
How to fix the "undefined" return from my mongoose/mongodb search function
I'm attempting to get the result from mongodb and then pass it to a const, but getting return vale of "undfined" where did I go wrong?

I made sure that the code works without the return and prints to console and made sure the data set is present in my mongodb.

```<code>const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));
</code>```

when the above is ran I get the following outputs on command line

undefined

Connected to DB

Then it prints the following which is the data in Mongodb

```<code>{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }
</code>```

I want to be able to get the data via the return and not inside the function.

答:
```<code>const mongoose = require('mongoose');

function search(query) {
   return db.collection('spells').find({
    "name": query
  })
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");
  search("Blight").then(console.log);
});
</code>```

Body:
I'm attempting to get the result from mongodb and then pass it to a const, but getting return vale of "undfined" where did I go wrong?

I made sure that the code works without the return and prints to console and made sure the data set is present in my mongodb.

const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));

when the above is ran I get the following outputs on command line

undefined

Connected to DB

Then it prints the following which is the data in Mongodb

{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }

I want to be able to get the data via the return and not inside the function.


问:
Is UIScreen.main.bounds edge to edge?
I have a relatively simple question but I can't seem to find the answer anywhere. When I use:

```<code>UIScreen.main.bounds.height
</code>```

Does this give me the height from the bottom edge of the screen all the way to the top or only till the safe area? For eg. is the height only until the notch for the iPhone X or does it go all that way up past the notch.

答:
is the height only until the notch for the iPhone X or does it go all that way up past the notch

You can easily check this yourself. Set a breakpoint somewhere in any iOS project, and see what rectangles are returned by bounds or nativeBounds for the main screen when the app runs on the device you're interested in, e.g. iPhone X:

```<code>(lldb) po [[UIScreen mainScreen] bounds]
(origin = (x = 0, y = 0), size = (width = 375, height = 812))

(lldb) po [[UIScreen mainScreen] nativeBounds]
(origin = (x = 0, y = 0), size = (width = 1125, height = 2436))
</code>```

You can check that against the dimensions reported for the screen in Apple's documentation:

I'd assume from that that the rectangle returned by bounds for the main screen represents the entire screen, not just the safe area. But if you're still not convinced, you could write a few lines of code that draws a rectangle with those dimensions, and you'll see that the notch and corners occlude parts of the rectangle:

Title: Is UIScreen.main.bounds edge to edge?

Body:
I have a relatively simple question but I can't seem to find the answer anywhere. When I use:

UIScreen.main.bounds.height

Does this give me the height from the bottom edge of the screen all the way to the top or only till the safe area? For eg. is the height only until the notch for the iPhone X or does it go all that way up past the notch.

Body:
is the height only until the notch for the iPhone X or does it go all that way up past the notch

You can easily check this yourself. Set a breakpoint somewhere in any iOS project, and see what rectangles are returned by bounds or nativeBounds for the main screen when the app runs on the device you're interested in, e.g. iPhone X:

(lldb) po [[UIScreen mainScreen] bounds]
(origin = (x = 0, y = 0), size = (width = 375, height = 812))

(lldb) po [[UIScreen mainScreen] nativeBounds]
(origin = (x = 0, y = 0), size = (width = 1125, height = 2436))

You can check that against the dimensions reported for the screen in Apple's documentation:

I'd assume from that that the rectangle returned by bounds for the main screen represents the entire screen, not just the safe area. But if you're still not convinced, you could write a few lines of code that draws a rectangle with those dimensions, and you'll see that the notch and corners occlude parts of the rectangle:


问:
Calculated field Sub total in pivot table is not displaying correct value
I am working on QuickSight in AWS. I am trying to achieve weighted average value in a Pivot table.

I am using SPICE data to create this analysis.

I have created a calculate field (WAM) in analysis with formula "percentOfTotal(sum(upb),[{pool_num}]) * sum({remaining_terms})".

This gives me the desired value on each row level, but the sub total of a particular column is not reflecting the total of values in the calculate field, rather it displays the sum of original values in the "remaining_terms" field.

Please see below image for the same. Can some one please through some light on this ?

Thanks in advance for your help

Please note that I have tried the same in Excel pivot table and it works perfectly.

答:
I have solved the problem in a different way. See below what I have done.

WAM = percentOfTotal(sum(upb),[{pool_num}]) * sum({remaining_terms}).

It looks like QuickSight treats the subtotal as a row and the above function is applied on the subtotal, hence it is converted as

(1186272.5 / 1186272.5) * 31 = 31.

I have tried to produce the desired result by introducing another custom field with formula

SUM_WAM = sumOver({WAM},[{pool_num}]).

This gives me the output I need, but in a column. See the screen shot attached


问:
ASP.NET Page_Load values are lagging one postback behind
I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.

Code:

```<code>foreach (var class in classes)
{
    for (var i = studentsList.Count - 1; i >= 0; i--)
    {
        if (studentsList[i].Id == class.student_id)
            studenstList.Remove(studentsList[i]);
    }
}
if (studentsList.Count == 0)
{
    button1.Enabled = false;
    button1.Text = "a";
}
else
{
    button1.Enabled = true;
    button1.Text = "b";
}
if (Page.IsPostBack) { return; }
</code>```

The issue:

The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.

答:
I guess the student list is updated by clicking a button on the page.

Put the code that enables button1 on the button_click event of that button.

Body:
I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.

Code:

foreach (var class in classes)
{
    for (var i = studentsList.Count - 1; i >= 0; i--)
    {
        if (studentsList[i].Id == class.student_id)
            studenstList.Remove(studentsList[i]);
    }
}
if (studentsList.Count == 0)
{
    button1.Enabled = false;
    button1.Text = "a";
}
else
{
    button1.Enabled = true;
    button1.Text = "b";
}
if (Page.IsPostBack) { return; }

The issue:

The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.


问:
TypeError: 'cmp' is an invalid keyword argument for this function-Python
I am new to python and i am having a script which i try to run it with Python 3.5 and i got this error

```<code>priorities[i].sort(cmp=comparer)
TypeError: 'cmp' is an invalid keyword argument for this function
</code>```

Here is the function that has the error from the script

```<code>def comparer(first, second):
    """Compare function for message priorities in maintenance mode"""
    return cmp(int(first["Priority"]), int(second["Priority"]))

def get_sequence(inputs, fcm):
"""Creates right sequence for the maintenance mode"""
flags = count_flags(inputs)
sequence = []
for index, where in [(0, '"Axis"="Elevator"'),
                     (1, '"Axis"="Aileron"'),
                     (2, '"Axis"="Rudder" or "Axis"="HS-ACE"')]:
    if len(flags[index]) == 0:
        sequence += WRITE_SEQUENCE_MAINT_0.Get(where)
    elif len(flags[index]) == 1:
        sequence += WRITE_SEQUENCE_MAINT_1.Get(where)
    elif len(flags[index]) > 1:
        sequence += WRITE_SEQUENCE_MAINT_2.Get(where)
    else:
        raise NotImplementedError("This number of flags does not make sense")

priorities = [[], [], []]
for flag in flags[0] + flags[1] + flags[2]:
    lines = WRITE_PROCESSING_MSGPRIORITY.Get('"Message Enable Flag"="%s" and "FCM Instance"="%s"' % (flag, fcm))
    if len(lines) > 0:
        priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[lines[0]["Axis"]]].append(lines[0])
for i in range(3):
    priorities[i].sort(cmp=comparer)

for message in sequence:
    if "Second Highest Priority" in message["Message"]:
        new_m = priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[message["Axis"]]][1]
        message["Message"] = new_m["Message"]
        message["Lane"] = new_m["Lane"]
        message["EP Bit"] = new_m["EP Bit"]
    elif "Highest Priority" in message["Message"]:
        priorities_for_rudder = priorities[{"Elev":0, "Ail":1, "Rud":2}[message["Axis"]]]
        if len(priorities_for_rudder) > 0: # This rudder message does not exist
            new_m = priorities_for_rudder[0]
            message["Message"] = new_m["Message"]
            message["Lane"] = new_m["Lane"]
            message["EP Bit"] = new_m["EP Bit"]
        else:
            message["Message"] = "Rudder Filler Message"
            message["Lane"] = "COM"
            message["EP Bit"] = "0"
return sequence
</code>```

This script was written in python 2.7.

答:
There is no longer a cmp argument for sorting in python 3.

Use a key, and a function that returns a single value to be mapped for comparison.

Instead of comparer, you can use this function.

```<code>def comparer_key(item):
    """Compare keys for message priorities in maintenance mode. Returns a key."""
    return int(item["Priority"])
</code>```

And then,

```<code>for i in range(3):
    priorities[i].sort(key=comparer_key)
</code>```

Body:
I am new to python and i am having a script which i try to run it with Python 3.5 and i got this error

priorities[i].sort(cmp=comparer)
TypeError: 'cmp' is an invalid keyword argument for this function

Here is the function that has the error from the script

def comparer(first, second):
    """Compare function for message priorities in maintenance mode"""
    return cmp(int(first["Priority"]), int(second["Priority"]))

def get_sequence(inputs, fcm):
"""Creates right sequence for the maintenance mode"""
flags = count_flags(inputs)
sequence = []
for index, where in [(0, '"Axis"="Elevator"'),
                     (1, '"Axis"="Aileron"'),
                     (2, '"Axis"="Rudder" or "Axis"="HS-ACE"')]:
    if len(flags[index]) == 0:
        sequence += WRITE_SEQUENCE_MAINT_0.Get(where)
    elif len(flags[index]) == 1:
        sequence += WRITE_SEQUENCE_MAINT_1.Get(where)
    elif len(flags[index]) > 1:
        sequence += WRITE_SEQUENCE_MAINT_2.Get(where)
    else:
        raise NotImplementedError("This number of flags does not make sense")

priorities = [[], [], []]
for flag in flags[0] + flags[1] + flags[2]:
    lines = WRITE_PROCESSING_MSGPRIORITY.Get('"Message Enable Flag"="%s" and "FCM Instance"="%s"' % (flag, fcm))
    if len(lines) > 0:
        priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[lines[0]["Axis"]]].append(lines[0])
for i in range(3):
    priorities[i].sort(cmp=comparer)

for message in sequence:
    if "Second Highest Priority" in message["Message"]:
        new_m = priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[message["Axis"]]][1]
        message["Message"] = new_m["Message"]
        message["Lane"] = new_m["Lane"]
        message["EP Bit"] = new_m["EP Bit"]
    elif "Highest Priority" in message["Message"]:
        priorities_for_rudder = priorities[{"Elev":0, "Ail":1, "Rud":2}[message["Axis"]]]
        if len(priorities_for_rudder) > 0: # This rudder message does not exist
            new_m = priorities_for_rudder[0]
            message["Message"] = new_m["Message"]
            message["Lane"] = new_m["Lane"]
            message["EP Bit"] = new_m["EP Bit"]
        else:
            message["Message"] = "Rudder Filler Message"
            message["Lane"] = "COM"
            message["EP Bit"] = "0"
return sequence

This script was written in python 2.7.

Body:
There is no longer a cmp argument for sorting in python 3.

Use a key, and a function that returns a single value to be mapped for comparison.

Instead of comparer, you can use this function.

def comparer_key(item):
    """Compare keys for message priorities in maintenance mode. Returns a key."""
    return int(item["Priority"])

And then,

for i in range(3):
    priorities[i].sort(key=comparer_key)


问:
Why do some elements remain even if the condition matches for each one?
I have created a small store application in Ruby. The concept is simple: I want to be able to add, remove, and view the 'database' in this example. The code seems to work; however, it does not behave like one would expect. I can add any product just fine, but when I try to remove them by a certain criterion that matches each item, only some are removed.

```<code>class Store
  PRODUCT = Struct.new(:identifier, :parameters)

  def initialize(database = [])
    @database = database
  end

  def increment
    # Increment the unique identifier if the database is not empty
    # Otherwise, set the initial value for the unique identifier
    @database.any? ? @database.map { |object| object[:identifier] }.max + 1 : 1
  end

  def add(product)
    @database.push(identifier: increment, parameters: product)
  end

  def remove(product)
    @database.each do |object|
      product.each do |key, value|
        @database.delete(object) if object[key] == value
        @database.delete(object) if object[:parameters][key] == value
      end
    end
  end

  def view
    puts @database
    puts "\n"
  end
end

store = Store.new

store.add(name: 'Fanta', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Sprite', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Coca-Cola', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')

store.view

store.remove(price: 9.95)

store.view
</code>```

This example will add three arbitrary items to the Store instance and list the contents found in the @database array. This array will of course hold the values:

```<code>{:identifier=>1, :parameters=>{:name=>"Fanta", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>3, :parameters=>{:name=>"Coca-Cola", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
</code>```

The code then proceeds to remove any product with a price of 9.95, which should match all the products in the @database array. However, when I list its contents once more, one product remains:

```<code>{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
</code>```

I cannot find any logic to this. Why does my remove method not remove all the elements if the condition holds true for each comparison?

答:
Let's focus on following looping,

```<code>@database.each do |object|
  product.each do |key, value|
    puts '-----------------'
    @database.delete(object) if object[key] == value
    @database.delete(object) if object[:parameters][key] == value
  end
end
</code>```

It is assumed to run 3 iteration on each loop for @database,

first iteration - it delete first with identifier = 1 for each loop counter 0

second iteration - it get modified @database as first get deleted, second become first and 3rd become 2nd and counter of each loop is at 1. So it delete new 2nd element of @database having identifier = 3.

third iteration - It will have each loop counter at 2 and new updated @database will have only 1 element having identifier = 2 (rescued in 2nd iteration) and there is no third element to proceed iteration further so nothing is iterated.

Correction needed:

```<code>def remove(product)
  @database.reject! do |object|
    product.map do |k,v|
      object[k] == v if object.has_key?(k)
      object[:parameters][k] == v if object[:parameters].has_key?(k)
    end.inject(&:|)
  end
end
</code>```

Body:
I have created a small store application in Ruby. The concept is simple: I want to be able to add, remove, and view the 'database' in this example. The code seems to work; however, it does not behave like one would expect. I can add any product just fine, but when I try to remove them by a certain criterion that matches each item, only some are removed.

class Store
  PRODUCT = Struct.new(:identifier, :parameters)

  def initialize(database = [])
    @database = database
  end

  def increment
    # Increment the unique identifier if the database is not empty
    # Otherwise, set the initial value for the unique identifier
    @database.any? ? @database.map { |object| object[:identifier] }.max + 1 : 1
  end

  def add(product)
    @database.push(identifier: increment, parameters: product)
  end

  def remove(product)
    @database.each do |object|
      product.each do |key, value|
        @database.delete(object) if object[key] == value
        @database.delete(object) if object[:parameters][key] == value
      end
    end
  end

  def view
    puts @database
    puts "\n"
  end
end

store = Store.new

store.add(name: 'Fanta', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Sprite', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Coca-Cola', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')

store.view

store.remove(price: 9.95)

store.view

This example will add three arbitrary items to the Store instance and list the contents found in the @database array. This array will of course hold the values:

{:identifier=>1, :parameters=>{:name=>"Fanta", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>3, :parameters=>{:name=>"Coca-Cola", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}

The code then proceeds to remove any product with a price of 9.95, which should match all the products in the @database array. However, when I list its contents once more, one product remains:

{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}

I cannot find any logic to this. Why does my remove method not remove all the elements if the condition holds true for each comparison?

Body:
Let's focus on following looping,

@database.each do |object|
  product.each do |key, value|
    puts '-----------------'
    @database.delete(object) if object[key] == value
    @database.delete(object) if object[:parameters][key] == value
  end
end

It is assumed to run 3 iteration on each loop for @database,

first iteration - it delete first with identifier = 1 for each loop counter 0

second iteration - it get modified @database as first get deleted, second become first and 3rd become 2nd and counter of each loop is at 1. So it delete new 2nd element of @database having identifier = 3.

third iteration - It will have each loop counter at 2 and new updated @database will have only 1 element having identifier = 2 (rescued in 2nd iteration) and there is no third element to proceed iteration further so nothing is iterated.

Correction needed:

def remove(product)
  @database.reject! do |object|
    product.map do |k,v|
      object[k] == v if object.has_key?(k)
      object[:parameters][k] == v if object[:parameters].has_key?(k)
    end.inject(&:|)
  end
end


问:
tFTPConnection setting password from context not working
I'm trying to set password of tFTPConnection component of Talend Open Studio using the context variable, but it's not working.

I'm getting this exception:

I've tried both reading context from file using context load and using context directly in the job

```<code>
Exception in component tFTPConnection_1 (read_file_from_sftp_using_context)
com.jcraft.jsch.JSchException: Auth cancel
    at com.jcraft.jsch.Session.connect(Session.java:511)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.tFTPConnection_1Process(read_file_from_sftp_using_context.java:2062)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.tFileInputDelimited_3Process(read_file_from_sftp_using_context.java:1776)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.tFileInputDelimited_2Process(read_file_from_sftp_using_context.java:1067)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.runJobInTOS(read_file_from_sftp_using_context.java:2550)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.main(read_file_from_sftp_using_context.java:2345)
[statistics] disconnected

</code>```

I expected that my connection will work but :(

答:
I found the solution to the passing of password which contained special character semicolon(;).
I was reading this, and found this statement:

Note the quotation marks around "noDatetimeStringSync=true" as it
  contains a Field Separator = character.

I tried that with the semicolon and it worked for me.

Thanks @Mo2s for your support as well.

Cheers, Ram

Body:
I'm trying to set password of tFTPConnection component of Talend Open Studio using the context variable, but it's not working.

I'm getting this exception:

I've tried both reading context from file using context load and using context directly in the job

Exception in component tFTPConnection_1 (read_file_from_sftp_using_context)
com.jcraft.jsch.JSchException: Auth cancel
    at com.jcraft.jsch.Session.connect(Session.java:511)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.tFTPConnection_1Process(read_file_from_sftp_using_context.java:2062)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.tFileInputDelimited_3Process(read_file_from_sftp_using_context.java:1776)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.tFileInputDelimited_2Process(read_file_from_sftp_using_context.java:1067)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.runJobInTOS(read_file_from_sftp_using_context.java:2550)
    at local_project.read_file_from_sftp_using_context_0_1.read_file_from_sftp_using_context.main(read_file_from_sftp_using_context.java:2345)
[statistics] disconnected

I expected that my connection will work but :(


问:
Accessing Amazon MWS inBound shipments
I want to access MWS Inbound Shipments API form C# in a similar way I do with the Amazon Reports using MarketplaceWebService

But I don't know how to to it.
For example how can I do this call form c# : https://docs.developer.amazonservices.com/en_US/fba_inbound/FBAInbound_ListInboundShipmentItems.html?

答:
The easiest and quickest approach is to download the C# SDK for MWS, where you can create a client and call the ListInboundShipmentItems method directly.  For this particular operation, ShipmentId is required.  All you need to do is add your AWS keys and token (if applicable) and make the call.   I noticed that the SDK used to be publicly available, but I think now you are required to log in with a seller account.

If you are not using the SDK, your request should look like this:

```<code>http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/
  ?Action=ListInboundShipmentItems
  &Version=2010-10-01
  &AWSAccessKeyId=1QZHP81EXAMPLEN5R44N
  &MWSAuthToken=amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE
  &SignatureVersion=2
  &SignatureMethod=HmacSHA256
  &Signature=VY6sqvdk01VeEXAMPLEG0Vh4oj3
  &Timestamp=2015-12-01T02:40:36Z
  &SellerId=1234567890
  &ShipmentId=SSF85DGIZZ3OF1
</code>```

Make sure you read the developer guide too.

Title: Accessing Amazon MWS inBound shipments

Body:
The easiest and quickest approach is to download the C# SDK for MWS, where you can create a client and call the ListInboundShipmentItems method directly.  For this particular operation, ShipmentId is required.  All you need to do is add your AWS keys and token (if applicable) and make the call.   I noticed that the SDK used to be publicly available, but I think now you are required to log in with a seller account.

If you are not using the SDK, your request should look like this:

http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/
  ?Action=ListInboundShipmentItems
  &Version=2010-10-01
  &AWSAccessKeyId=1QZHP81EXAMPLEN5R44N
  &MWSAuthToken=amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE
  &SignatureVersion=2
  &SignatureMethod=HmacSHA256
  &Signature=VY6sqvdk01VeEXAMPLEG0Vh4oj3
  &Timestamp=2015-12-01T02:40:36Z
  &SellerId=1234567890
  &ShipmentId=SSF85DGIZZ3OF1

Make sure you read the developer guide too.


问:
Kubernetes Container Command
I'm working with Neo4j in Kubernetes.
For a showcase, I want to fill the Neo4j in the Pods with initial data which i can do with a cypher-file, I'm having in the /bin folder using the cypher-shell.
So basically I start the container and run cat bin/initialData.cypher | bin/cypher-shell.
I've validated that this works by running it in the kubectl exec -it <pod> /bin/bash bash.
However, no matter how I try to map to the spec.container.command, it fails.
Currently my best guess is

```<code>spec:
  containers:
    command:
        - /bin/bash
        - -c
        - |
          cd bin
          ls
          cat initialData.cypher | cypher-shell
</code>```

which does not work. It displays the ls correctly but throws a connection refused afterwards, where I have no idea where its coming from.

edit: Updated

答: Exec seems like the better way to handle this but you wouldn’t usually use both command and args. In this case, probably just put the whole thing in command.</p>

Title: Kubernetes Container Command

Body:
I'm working with Neo4j in Kubernetes.
For a showcase, I want to fill the Neo4j in the Pods with initial data which i can do with a cypher-file, I'm having in the /bin folder using the cypher-shell.
So basically I start the container and run cat bin/initialData.cypher | bin/cypher-shell.
I've validated that this works by running it in the kubectl exec -it <pod> /bin/bash bash.
However, no matter how I try to map to the spec.container.command, it fails.
Currently my best guess is

spec:
  containers:
    command:
        - /bin/bash
        - -c
        - |
          cd bin
          ls
          cat initialData.cypher | cypher-shell

which does not work. It displays the ls correctly but throws a connection refused afterwards, where I have no idea where its coming from.

edit: Updated