问:
Netsuite: How can i get the field value from tab?
Netsuite Newbie here.
What i should do if i want to get the value of "AMOUNT INSURED" in tab Items?
I have tried something like this to get the employee email when i open a page of an employee.

function emailStatus(){
  var salesRep = nlapiGetFieldValue('salesrep');
  var salesRepEmail = nlapiLookupField('employee', salesRep, 'email',true);
  alert(salesRepEmail+statusV);
}
```

答:
Your screenshot looks like a sales order or some other transaction. 'Amount Insured' also appears to be a custom field on that record.  If so, you can get the value from a 'subtab', or ‘sublist’, using nlapiGetLineItemValue(type, fieldname, line).

‘type' is the sublist name

‘fieldname' is the name of the field value you want

‘line' is the line number on the transaction, starting with 1.

To do this, you will need the script id for that field.

To get the script ID, navigate to Customization -> Lists, Records & Fields -> Transaction Line Fields.  Find the field ‘Amount Insured’ and note the ID value in this list.  It will start with ‘custbody…'

With this information, you can use the following line to get the value in question:

```<code>var amountInsured = nlapiGetLineItemValue('item', 'custbody_amount_insured', 1);
</code>```

You can read more about this API in the NetSuite help documentation here.

Body:
Your screenshot looks like a sales order or some other transaction. 'Amount Insured' also appears to be a custom field on that record.  If so, you can get the value from a 'subtab', or ‘sublist’, using nlapiGetLineItemValue(type, fieldname, line).

‘type' is the sublist name

‘fieldname' is the name of the field value you want

‘line' is the line number on the transaction, starting with 1.

To do this, you will need the script id for that field.

To get the script ID, navigate to Customization -> Lists, Records & Fields -> Transaction Line Fields.  Find the field ‘Amount Insured’ and note the ID value in this list.  It will start with ‘custbody…'

With this information, you can use the following line to get the value in question:

var amountInsured = nlapiGetLineItemValue('item', 'custbody_amount_insured', 1);

You can read more about this API in the NetSuite help documentation here.


来源: stackexchange

问:
Retrieving series rows given a condition
Consider the following series which represents the distance between location a and locations b, c, d:

```<code>   a
a  0

b  10

c  12

d  21
</code>```

Now, what I'm trying to do is retrieve all location names that are within a certain distance from a.

For example, I would like to print out all variables that are within a 15 unit distance from a, excluding a, which would be b and c.

b

c

I've tried creating an empty list and then using a for loop to append to that list but to no avail, so I'm obviously missing something.

答:
You can do this, i assumed the first column is an index:</p>

```<code>print(df[(df['a'] < 15) & (df.index != 'a')])

      a
loc
b    10
c    12
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider the following series which represents the distance between location a and locations b, c, d:

   a
a  0

b  10

c  12

d  21

Now, what I'm trying to do is retrieve all location names that are within a certain distance from a.

For example, I would like to print out all variables that are within a 15 unit distance from a, excluding a, which would be b and c.

b

c

I've tried creating an empty list and then using a for loop to append to that list but to no avail, so I'm obviously missing something.

Body:
You can do this, i assumed the first column is an index:

print(df[(df['a'] < 15) & (df.index != 'a')])

      a
loc
b    10
c    12


问:
Spring Batch Tables Purging
What is the best way to purge Spring Tables?

Does Spring provides any APIS for purging? or, Do We need to execute delete statements on all Spring Batch Tables?

答:
I created  a procedure to clean Up data before a date given.

```<code>    DELIMITER $$

DROP PROCEDURE IF EXISTS purgeJobsTableBefore
$$

CREATE PROCEDURE purgeJobsTableBefore (
    IN createTime VARCHAR(100)
)
BEGIN

DELETE
FROM
   batch_job_execution_context
WHERE
   JOB_EXECUTION_ID IN
   (
      SELECT
         JOB_EXECUTION_ID
      FROM
         batch_job_execution
      WHERE
         create_time <= createTime
   );

DELETE
FROM
   batch_job_execution_params
WHERE
   JOB_EXECUTION_ID IN
   (
      SELECT
         JOB_EXECUTION_ID
      FROM
         batch_job_execution
      WHERE
         create_time <= createTime
   );

DELETE
FROM
   batch_step_execution_context
WHERE
   step_execution_id IN
   (
      SELECT
         step_execution_id
      FROM
         batch_step_execution
      WHERE
         JOB_EXECUTION_ID IN
         (
            SELECT
               JOB_EXECUTION_ID
            FROM
               batch_job_execution
            WHERE
               create_time <= createTime
         )
   );

DELETE
FROM
   batch_step_execution
WHERE
   JOB_EXECUTION_ID IN
   (
      SELECT
         JOB_EXECUTION_ID
      FROM
         batch_job_execution
      WHERE
         create_time <= createTime
   );

DELETE
FROM
   batch_job_execution
WHERE
   create_time <= createTime;

DELETE
FROM
   batch_job_instance
WHERE
   JOB_INSTANCE_ID < (
   SELECT
      MIN(JOB_INSTANCE_ID)
   FROM
      batch_job_execution
   WHERE
      create_time >= createTime);

END;
$$
</code>```

You just have to call the procedure with a date to clear up data before that date.

```<code>CALL purgeJobsTableBefore('2020-05-22');
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spring Batch Tables Purging

Body:
I created  a procedure to clean Up data before a date given.

    DELIMITER $$

DROP PROCEDURE IF EXISTS purgeJobsTableBefore
$$

CREATE PROCEDURE purgeJobsTableBefore (
    IN createTime VARCHAR(100)
)
BEGIN

DELETE
FROM
   batch_job_execution_context
WHERE
   JOB_EXECUTION_ID IN
   (
      SELECT
         JOB_EXECUTION_ID
      FROM
         batch_job_execution
      WHERE
         create_time <= createTime
   );

DELETE
FROM
   batch_job_execution_params
WHERE
   JOB_EXECUTION_ID IN
   (
      SELECT
         JOB_EXECUTION_ID
      FROM
         batch_job_execution
      WHERE
         create_time <= createTime
   );

DELETE
FROM
   batch_step_execution_context
WHERE
   step_execution_id IN
   (
      SELECT
         step_execution_id
      FROM
         batch_step_execution
      WHERE
         JOB_EXECUTION_ID IN
         (
            SELECT
               JOB_EXECUTION_ID
            FROM
               batch_job_execution
            WHERE
               create_time <= createTime
         )
   );

DELETE
FROM
   batch_step_execution
WHERE
   JOB_EXECUTION_ID IN
   (
      SELECT
         JOB_EXECUTION_ID
      FROM
         batch_job_execution
      WHERE
         create_time <= createTime
   );

DELETE
FROM
   batch_job_execution
WHERE
   create_time <= createTime;

DELETE
FROM
   batch_job_instance
WHERE
   JOB_INSTANCE_ID < (
   SELECT
      MIN(JOB_INSTANCE_ID)
   FROM
      batch_job_execution
   WHERE
      create_time >= createTime);

END;
$$

You just have to call the procedure with a date to clear up data before that date.

CALL purgeJobsTableBefore('2020-05-22');


问:
x.ToString() is not supported by the entity framework!
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

```<code>public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}
</code>```

Here is my Route entity:

```<code> public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }
</code>```

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?

答:
You cannot do this on client side (ToString).

You must create SQL function which will do your evaluation - it can either do only string concatenation of you locations (I believe it is related entity) or you can do the whole test in custom function. Then you can import that function into your entity model (EDMX) and create EdmFunctionAttribute to call it - MSDN.

Body:
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}

Here is my Route entity:

 public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?


问:
FInd .closest() fails
I have trouble understanding whys something like this wont work.
I have read jquery and W3 documentation and I don't see the mistake.

Code should look for a link and highlight the closest button.

The structure is simple:

$('#meni').find('a').each(function() {
console.log(this);
      $(this).closest("button").css("color","red !important");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="meni">
     <button>button</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
 </div></code>```

Also to note it this is part of bigger code, and the actual this-link will be in conditioned and return only one, so problem is not in that it sees multiple.

```<code>  var loc= window.location.href;
  //console.log(loc);

values=loc.split('/');
link=values[values.length-1];
//console.log(link);

    $('#meni').find('a').each(function() {
    //console.log($(this).attr('href').indexOf(link) >= 0);
    if ($(this).attr('href').indexOf(link) >= 0) {
      $(this).css({"color":"#87CEEB !important" , "font-weight":"bold" });
      $(this).closest("button").css({"color":"#87CEEB !important" , "font-weight":"bold", "border-bottom": "1px solid" });
    }
});
</code>```

答:
closest (both jQUery's and the DOM's) look at ancestor elements only. It doesn't look at sibling elements, the parent's sibling elements, etc.

In your example, the ancestry of the a elements is body > div > div > a, the button isn't in that ancestry.

To find that button in that structure starting from one of those a elements, you'd use closest to find the outer enclosing div (probably giving it a class to make that easy), then find on that enclsoing div:

$('.example').find('a').each(function() {
    const btn = $(this).closest(".example").find("button");
    console.log(btn.text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="example">
     <button>button 1</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>
<div class="example">
     <button>button 2</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

If you can't give it a class for some reason, $(this).parents("div").eq(1) will find it (eq is zero-based, so .eq(0) would be the nearest div parent, .eq(1) is the second-nearest):

$('body > div').find('a').each(function() {
    const btn = $(this).parents("div").eq(1).find("button");
    console.log(btn.text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="example">
     <button>button 1</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>
<div class="example">
     <button>button 2</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

...but it's fragile — a small change to the markup will break it.

But if #meni really is the only element where this is done, just use $("#meni button") instead:

$('#meni').find('a').each(function() {
    const btn = $("#meni button");
    console.log(btn.text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="meni">
     <button>button</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
 </div></code>```

Side note: $("#meni").find("a") can be more concisely written $("#meni a").

Title: FInd .closest() fails

Body:
I have trouble understanding whys something like this wont work.
I have read jquery and W3 documentation and I don't see the mistake.

Code should look for a link and highlight the closest button.

The structure is simple:

$('#meni').find('a').each(function() {
console.log(this);
      $(this).closest("button").css("color","red !important");
});

     <button>button</button>

         link1
         link2
         link3

Also to note it this is part of bigger code, and the actual this-link will be in conditioned and return only one, so problem is not in that it sees multiple.

  var loc= window.location.href;
  //console.log(loc);

values=loc.split('/');
link=values[values.length-1];
//console.log(link);

    $('#meni').find('a').each(function() {
    //console.log($(this).attr('href').indexOf(link) >= 0);
    if ($(this).attr('href').indexOf(link) >= 0) {
      $(this).css({"color":"#87CEEB !important" , "font-weight":"bold" });
      $(this).closest("button").css({"color":"#87CEEB !important" , "font-weight":"bold", "border-bottom": "1px solid" });
    }
});

Body:
closest (both jQUery's and the DOM's) look at ancestor elements only. It doesn't look at sibling elements, the parent's sibling elements, etc.

In your example, the ancestry of the a elements is body > div > div > a, the button isn't in that ancestry.

To find that button in that structure starting from one of those a elements, you'd use closest to find the outer enclosing div (probably giving it a class to make that easy), then find on that enclsoing div:

$('.example').find('a').each(function() {
    const btn = $(this).closest(".example").find("button");
    console.log(btn.text());
});

<div class="example">
     <button>button 1</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>
<div class="example">
     <button>button 2</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you can't give it a class for some reason, $(this).parents("div").eq(1) will find it (eq is zero-based, so .eq(0) would be the nearest div parent, .eq(1) is the second-nearest):

$('body > div').find('a').each(function() {
    const btn = $(this).parents("div").eq(1).find("button");
    console.log(btn.text());
});

<div class="example">
     <button>button 1</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>
<div class="example">
     <button>button 2</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

...but it's fragile — a small change to the markup will break it.

But if #meni really is the only element where this is done, just use $("#meni button") instead:

$('#meni').find('a').each(function() {
    const btn = $("#meni button");
    console.log(btn.text());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="meni">
     <button>button</button>
     <div>
         <a>link1</a>
         <a>link2</a>
         <a>link3</a>
     </div>
 </div>

Side note: $("#meni").find("a") can be more concisely written $("#meni a").


答:
Forget loops, pandas and numpy already have builtin functions that make the job. In this case you can use np.where.</p>

```<code>import pandas as pd
import numpy as np
df = pd.Series({'a':0, 'b':10, 'c':12, 'd':21}, index=['a', 'b', 'c', 'd'])
df.iloc[np.where((df<=15) & (df.index !='a'))]
</code>```

Title: Retrieving series rows given a condition

Body:
Forget loops, pandas and numpy already have builtin functions that make the job. In this case you can use np.where.

import pandas as pd
import numpy as np
df = pd.Series({'a':0, 'b':10, 'c':12, 'd':21}, index=['a', 'b', 'c', 'd'])
df.iloc[np.where((df<=15) & (df.index !='a'))]


问:
What / Where is the default Spark on Yarn Working directory?
When working on standalone, the working directory is basically $SPARK_HOME/work.

However i have no idea how to find that when working in Yarn mode ? Can someone else me find the working directory for spark or maybe application running on yarn ?

答: when spark run on yarn, the work dir locate at {yourYarnLocalDir}/usercache/{yourUserName}/appcache/{yourApplicationId}</p>


问:
Manipulating position of child div inside parent div and the problems they entail
I wanna position the h1 and button at around bottom: 40% and left: 20% i.e hovering over the bottom left side of the parent div(id="head). Using display: abolute; and positioning tags makes them go outside the screen when the screen size is changed. Is there any other way other than positiong method or without using flex or grid cause i have another div which gets affected when i change display to flex/grid. Thank You.

*{
    margin: 0;
    padding: 0;
}

body{
    background: #888;
    color: #fff;
    line-height: 1.5;
    font-family: 'Work Sans', sans-serif;
    overflow: hidden;
}

.button{
    font-size: 1.5rem;
    text-decoration: none;
    color: #fff;
    border: #fff 3px solid;
    padding: 1.3rem 2.3rem;
    border-radius: 10px;
    margin-top: 2.2rem;
    margin-left: 3rem;
    transition: all 0.6s ease;
}

.button:hover{
    font-size: 1.7rem;
    border: black 3px solid;
}

#head{
    position: relative;
    /* background-image: url(/images/snow-capped-mountains-under-the-cloudy-skies-1054289.jpg); */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 100vh;
    overflow: hidden;
}

#head .show-top {
    width: 90%;
    margin: auto;
    text-align: right;
    padding: 1.5rem;
    font-size: 1.2rem;
}

.show-top li{
    display: inline;
    padding: 0 1rem;
}

.show-top a{
    text-decoration: none;
    color: #333;
}

#head .showcase{
    position: absolute;
    top: 65%;
    left: 20%;
    transform: translate(-50%, -50%);
}

#head .showcase h1{
    font-weight: bold;
    font-size: 5rem;
    /* padding: 2rem; */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <header id="head" style="border: violet 5px solid;">
        <div class="show-top">
            <ul>
                <li>ABOUT</li>
                <li>PROGRAMS</li>
                <li>SPECIALS</li>
            </ul>
        </div>

        <div class="showcase" style="border: turquoise 5px solid;">
            <h1>Take a step</h1>
            Enter
        </div>

    </header>
</body>

</html></code>```

答:
Not quiet sure what your final desired outcome is. But this works at my end:

Making the parent absolute and the showcase relative to its parent. If you resize your window the measures/position ratio stays the same.

*{
    margin: 0;
    padding: 0;
}

body{
    background: #888;
    color: #fff;
    line-height: 1.5;
    font-family: 'Work Sans', sans-serif;
    overflow: hidden;
}

.button{
    font-size: 1.5rem;
    text-decoration: none;
    color: #fff;
    border: #fff 3px solid;
    padding: 1.3rem 2.3rem;
    border-radius: 10px;
    margin-top: 2.2rem;
    margin-left: 3rem;
    transition: all 0.6s ease;
}

.button:hover{
    font-size: 1.7rem;
    border: black 3px solid;
}

#head{
    position: absolute;
    /* background-image: url(/images/snow-capped-mountains-under-the-cloudy-skies-1054289.jpg); */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 100vh;
    width: 100%;
    overflow: hidden;
}

#head .show-top {
    width: 90%;
    margin: auto;
    text-align: right;
    padding: 1.5rem;
    font-size: 1.2rem;
}

.show-top li{
    display: inline;
    padding: 0 1rem;
}

.show-top a{
    text-decoration: none;
    color: #333;
}

.showcase{
    position: relative;
    top: 40%;
    left: 20%;
    width: 50vw;
}

.showcase h1{
    font-weight: bold;
    font-size: 2rem;
    width: 20vw;
    /* padding: 2rem; */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <header id="head" style="border: violet 5px solid;">
        <div class="show-top">
            <ul>
                <li>ABOUT</li>
                <li>PROGRAMS</li>
                <li>SPECIALS</li>
            </ul>
        </div>

        <div class="showcase" style="border: turquoise 5px solid;">
            <h1>Take a step</h1>
            Enter
        </div>

    </header>
</body>

</html></code>```

Body:
I wanna position the h1 and button at around bottom: 40% and left: 20% i.e hovering over the bottom left side of the parent div(id="head). Using display: abolute; and positioning tags makes them go outside the screen when the screen size is changed. Is there any other way other than positiong method or without using flex or grid cause i have another div which gets affected when i change display to flex/grid. Thank You.

*{
    margin: 0;
    padding: 0;
}

body{
    background: #888;
    color: #fff;
    line-height: 1.5;
    font-family: 'Work Sans', sans-serif;
    overflow: hidden;
}

.button{
    font-size: 1.5rem;
    text-decoration: none;
    color: #fff;
    border: #fff 3px solid;
    padding: 1.3rem 2.3rem;
    border-radius: 10px;
    margin-top: 2.2rem;
    margin-left: 3rem;
    transition: all 0.6s ease;
}

.button:hover{
    font-size: 1.7rem;
    border: black 3px solid;
}

#head{
    position: relative;
    /* background-image: url(/images/snow-capped-mountains-under-the-cloudy-skies-1054289.jpg); */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 100vh;
    overflow: hidden;
}

#head .show-top {
    width: 90%;
    margin: auto;
    text-align: right;
    padding: 1.5rem;
    font-size: 1.2rem;
}

.show-top li{
    display: inline;
    padding: 0 1rem;
}

.show-top a{
    text-decoration: none;
    color: #333;
}

#head .showcase{
    position: absolute;
    top: 65%;
    left: 20%;
    transform: translate(-50%, -50%);
}

#head .showcase h1{
    font-weight: bold;
    font-size: 5rem;
    /* padding: 2rem; */
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">
    <title>Document</title>

ABOUT

PROGRAMS

SPECIALS

Take a step

            Enter

Body:
Not quiet sure what your final desired outcome is. But this works at my end:

Making the parent absolute and the showcase relative to its parent. If you resize your window the measures/position ratio stays the same.

*{
    margin: 0;
    padding: 0;
}

body{
    background: #888;
    color: #fff;
    line-height: 1.5;
    font-family: 'Work Sans', sans-serif;
    overflow: hidden;
}

.button{
    font-size: 1.5rem;
    text-decoration: none;
    color: #fff;
    border: #fff 3px solid;
    padding: 1.3rem 2.3rem;
    border-radius: 10px;
    margin-top: 2.2rem;
    margin-left: 3rem;
    transition: all 0.6s ease;
}

.button:hover{
    font-size: 1.7rem;
    border: black 3px solid;
}

#head{
    position: absolute;
    /* background-image: url(/images/snow-capped-mountains-under-the-cloudy-skies-1054289.jpg); */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 100vh;
    width: 100%;
    overflow: hidden;
}

#head .show-top {
    width: 90%;
    margin: auto;
    text-align: right;
    padding: 1.5rem;
    font-size: 1.2rem;
}

.show-top li{
    display: inline;
    padding: 0 1rem;
}

.show-top a{
    text-decoration: none;
    color: #333;
}

.showcase{
    position: relative;
    top: 40%;
    left: 20%;
    width: 50vw;
}

.showcase h1{
    font-weight: bold;
    font-size: 2rem;
    width: 20vw;
    /* padding: 2rem; */
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <header id="head" style="border: violet 5px solid;">
        <div class="show-top">
            <ul>
                <li><a href="#">ABOUT</a></li>
                <li><a href="#">PROGRAMS</a></li>
                <li><a href="#">SPECIALS</a></li>
            </ul>
        </div>

        <div class="showcase" style="border: turquoise 5px solid;">
            <h1>Take a step</h1>
            <a href="#" class="button">Enter</a>
        </div>

    </header>
</body>

</html>


问:
how to validate enter button?
i had a functionality that in text box after entering a value when i pressed enter the value was validated.
Now i wanted to perform similar task by using enter button.
I had created an event for button click but not able to understand how to perform enter action.

i am sending code:

```<code><Button x:Name="BtnCancel" Content="CANCEL" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Center" Click="PlayerSwipeBtn_Click" Width="110" Height="55"  Margin="303,6,113,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" />
                <Button x:Name="BtnEntername" Content="Enter" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Stretch"  Width="110" Height="55"  Margin="113,6,303,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" Click="BtnEntername_Click" />

Xaml.cs code:
private void PlayerSwipeBtn_Click(object sender, RoutedEventArgs e)
        {
            Button btnAction = (Button)sender;
            ACTION = btnAction.Tag.ToString();
            if (ACTION == PLAYER_ACTIONS_CODE.CANCEL)
                this.DialogResult = false;
            else
                this.DialogResult = true;
        }
</code>```

what to do for enter button to validate entry.

答:
The code below might help you out.  </p>

```<code>SearcbTextBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + CancelButton.UniqueID + "').click();return false;}} else {return true}; ");
</code>```

Title: how to validate enter button?

Body:
i had a functionality that in text box after entering a value when i pressed enter the value was validated.
Now i wanted to perform similar task by using enter button.
I had created an event for button click but not able to understand how to perform enter action.

i am sending code:

<Button x:Name="BtnCancel" Content="CANCEL" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Center" Click="PlayerSwipeBtn_Click" Width="110" Height="55"  Margin="303,6,113,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" />
                <Button x:Name="BtnEntername" Content="Enter" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Stretch"  Width="110" Height="55"  Margin="113,6,303,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" Click="BtnEntername_Click" />

Xaml.cs code:
private void PlayerSwipeBtn_Click(object sender, RoutedEventArgs e)
        {
            Button btnAction = (Button)sender;
            ACTION = btnAction.Tag.ToString();
            if (ACTION == PLAYER_ACTIONS_CODE.CANCEL)
                this.DialogResult = false;
            else
                this.DialogResult = true;
        }

what to do for enter button to validate entry.

Body:
The code below might help you out.

SearcbTextBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + CancelButton.UniqueID + "').click();return false;}} else {return true}; ");


问:
Get pixel color from screenshot
I'm taking a screenshot and transform it to Bitmap

```<code>Bitmap bitmap = null;
while (bitmap == null) { bitmap = BitmapFactory.decodeFile(path/filename.png); }
</code>```

then i want to get pixel color

```<code> int pixel = bitmap.getPixel(x, y);
 Log.i("Main", "color: " + "#" + Integer.toHexString(pixel));
</code>```

and it works, but only when y<130. When y 140 and more i get only black color

```<code>2020-06-01 14:43:46.121 17451-17495/com. I/Main: color: #ff000000
</code>```

screenshot resolution is 1920*1080. When i try load it in ImageView all is OK

答:
for me works to take screenshot like this </p>

```<code>Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
</code>```

Title: Get pixel color from screenshot

Body:
I'm taking a screenshot and transform it to Bitmap

Bitmap bitmap = null;
while (bitmap == null) { bitmap = BitmapFactory.decodeFile(path/filename.png); }

then i want to get pixel color

 int pixel = bitmap.getPixel(x, y);
 Log.i("Main", "color: " + "#" + Integer.toHexString(pixel));

and it works, but only when y<130. When y 140 and more i get only black color

2020-06-01 14:43:46.121 17451-17495/com. I/Main: color: #ff000000

screenshot resolution is 1920*1080. When i try load it in ImageView all is OK

Body:
for me works to take screenshot like this

Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();


问:
hibernate spatial dialect for mysql 8
i use springboot 2.1 and use hibernate last version for orm.
when i want persist my data to db i have this error:

Data truncation: Cannot get geometry object from data you send to the GEOMETRY field

```<code>@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Province {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long Id;

    String name;

    @Column(nullable = false, columnDefinition = "MultiPolygon")
    MultiPolygon multiPolygon;

}
</code>```

i think problem is in mydialect.

```<code>server:
port: 8080

logging:
    level:
        com.mousavi007.serverhavadan: debug
spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username:********
    password: ******
    properties:
      mail:
            smtp:
              auth: true
              starttls:
                enable: true
    protocol: smtp
    default-encoding: utf-8

  datasource:
    url: jdbc:mysql://localhost:3306/havadan
    username: *************
    password: *************
    platform: mysql
  jpa:
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL8Dialect

    database: mysql
    show-sql: true
</code>```

what is spatial dilect for mysql 8 with hibernate last version?

答:
Please use

org.hibernate.spatial.dialect.mysql.MySQL8SpatialDialect

Title: hibernate spatial dialect for mysql 8

Body:
i use springboot 2.1 and use hibernate last version for orm.
when i want persist my data to db i have this error:

Data truncation: Cannot get geometry object from data you send to the GEOMETRY field

@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Province {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long Id;

    String name;

    @Column(nullable = false, columnDefinition = "MultiPolygon")
    MultiPolygon multiPolygon;

}

i think problem is in mydialect.

server:
port: 8080

logging:
    level:
        com.mousavi007.serverhavadan: debug
spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username:********
    password: ******
    properties:
      mail:
            smtp:
              auth: true
              starttls:
                enable: true
    protocol: smtp
    default-encoding: utf-8

  datasource:
    url: jdbc:mysql://localhost:3306/havadan
    username: *************
    password: *************
    platform: mysql
  jpa:
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL8Dialect

    database: mysql
    show-sql: true

what is spatial dilect for mysql 8 with hibernate last version?


问:
TestCafe - How to check if the value is greater than or equal in the assertion
I would like to check the value which appears in below selector if it is greater than or equal to 1

 0
```

<p>(In steps, the value "0" should change into "1" or "2"..)</p>

<p>I defined this selector in common.js</p>

<pre class="lang-js prettyprint-override"><code>this.pill = Selector('[class*=badge-white]');
</code>```

and wrote the following assertion:

await t.expect((common.pill).innerText).gte(1);
```

<p>I received the following error: " AssertionError: expected '1' to be a number or a date'. I do not know how to convert ((common.pill).innerText) to number? I tried sth like this:</p>

<pre class="lang-js prettyprint-override"><code>await t.expect(Number((common.pill).innerText)).gte(1);
</code>```

But it does not work.
When I check if the value is deep equal eg."3"i write:

await t.expect((common.pill).innerText).eql('3');
```

<p>And it works.
Could anybody help me how to check value greater than or equal?
I studied it thoroughly but I can't find a solution https://devexpress.github.io/testcafe/documentation/guides/basic-guides/assert.html :(</p>

<p>I found a solution when created const </p>

<pre class="lang-js prettyprint-override"><code>const number = await common.pill.innerText;

await t.expect(Number(number)).gte(1);
</code>```

It works!!!!!!!!!!!!!!!!!!

so my question is why below code did not work

await t.expect(Number((common.pill).innerText)).gte(1);
```

答:
Your code

```<code>await t.expect(Number((common.pill).innerText)).gte(1);
</code>```

does not work because ‘Number’ does not expect unresolved promises, so yes, you need to do this as follows:

```<code>const number = await common.pill.innerText;
await t.expect(Number(number)).gte(1);
</code>```

This code

```<code>await t.expect((common.pill).innerText).eql('3');
</code>```

works because ’expect’ supports awaiting promises automatically.

Body:
I would like to check the value which appears in below selector if it is greater than or equal to 1

 0

(In steps, the value "0" should change into "1" or "2"..)

I defined this selector in common.js

this.pill = Selector('[class*=badge-white]');

and wrote the following assertion:

await t.expect((common.pill).innerText).gte(1);

I received the following error: " AssertionError: expected '1' to be a number or a date'. I do not know how to convert ((common.pill).innerText) to number? I tried sth like this:

await t.expect(Number((common.pill).innerText)).gte(1);

But it does not work.
When I check if the value is deep equal eg."3"i write:

await t.expect((common.pill).innerText).eql('3');

And it works.
Could anybody help me how to check value greater than or equal?
I studied it thoroughly but I can't find a solution https://devexpress.github.io/testcafe/documentation/guides/basic-guides/assert.html :(

I found a solution when created const

const number = await common.pill.innerText;

await t.expect(Number(number)).gte(1);

It works!!!!!!!!!!!!!!!!!!

so my question is why below code did not work

await t.expect(Number((common.pill).innerText)).gte(1);

Body:
Your code

await t.expect(Number((common.pill).innerText)).gte(1);

does not work because ‘Number’ does not expect unresolved promises, so yes, you need to do this as follows:

const number = await common.pill.innerText;
await t.expect(Number(number)).gte(1);

This code

await t.expect((common.pill).innerText).eql('3');

works because ’expect’ supports awaiting promises automatically.


问:
Export xml from Excel
I want to export xml from the Excel table
but the number of columns are not fixed.
I think I need xsd
Can anybody share the xsd</p>

答:
This is how I learned to do it with VBA, verý simple and flexible...

Check:

```<code>    'lastCol = Range("a1").End(xlToRight).Column
</code>```

in Sub kurssitToXML (Kurssi = Courses in Finnish ):

```<code>Sub kurssitToXML()
    Dim Filename As Variant
    Dim Rng As Range
    Dim r As Long, c As Long
    Dim dRetVal As Variant

    Worksheets("Kurssiluettelo").Activate
    'Set the range

    ' IS THIS WHAT YOU ARE LOOKING FOR?
    'lastCol = Range("a1").End(xlToRight).Column
    'lastRow = Cells(65536, lastCol).End(xlUp).Row
    'Rng = Range("a1", Cells(lastRow, lastCol))

    lastCol = Range("a1").End(xlToRight).Column
    lastRow = Range("a1").End(xlDown).Row
    Set Rng = Range("a1", Cells(lastRow, lastCol))

    '   Get a file name
    Filename = Application.GetSaveAsFilename( _
        InitialFileName:="d:\kurssit.xml", _
        fileFilter:="XML Files(*.xml), *.xml")
    If Filename = False Then Exit Sub

'   Open the text file
    Open Filename For Output As #1

'   Write the <xml> tags
    Print #1, "<?xml version=""1.0"" encoding=""ISO-8859-1"" standalone=""yes""?>"
    Print #1, "<KurssitList xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">"

'   Loop through the cells
    For r = 2 To Rng.Rows.Count
        Print #1, "<Kurssi>"
        For c = 1 To Rng.Columns.Count
            Print #1, "<" & Rng.Cells(1, c) & ">";
            If IsDate(Rng.Cells(r, c)) Then
                Print #1, Format(Rng.Cells(r, c), "dd.mm.yyyy");
            Else
                Print #1, Rng.Cells(r, c).Text;
            End If
            Print #1, "</" & Rng.Cells(1, c) & ">"
        Next c
        Print #1, "</Kurssi>"
    Next r
'   Close the table
    Print #1, "</KurssitList>"

'   Close the file
    Close #1
...
</code>```

I hope this helps.

Title: Export xml from Excel

Body:
This is how I learned to do it with VBA, verý simple and flexible...

Check:

    'lastCol = Range("a1").End(xlToRight).Column

in Sub kurssitToXML (Kurssi = Courses in Finnish ):

Sub kurssitToXML()
    Dim Filename As Variant
    Dim Rng As Range
    Dim r As Long, c As Long
    Dim dRetVal As Variant

    Worksheets("Kurssiluettelo").Activate
    'Set the range

    ' IS THIS WHAT YOU ARE LOOKING FOR?
    'lastCol = Range("a1").End(xlToRight).Column
    'lastRow = Cells(65536, lastCol).End(xlUp).Row
    'Rng = Range("a1", Cells(lastRow, lastCol))

    lastCol = Range("a1").End(xlToRight).Column
    lastRow = Range("a1").End(xlDown).Row
    Set Rng = Range("a1", Cells(lastRow, lastCol))

    '   Get a file name
    Filename = Application.GetSaveAsFilename( _
        InitialFileName:="d:\kurssit.xml", _
        fileFilter:="XML Files(*.xml), *.xml")
    If Filename = False Then Exit Sub

'   Open the text file
    Open Filename For Output As #1

'   Write the <xml> tags
    Print #1, "<?xml version=""1.0"" encoding=""ISO-8859-1"" standalone=""yes""?>"
    Print #1, "<KurssitList xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">"

'   Loop through the cells
    For r = 2 To Rng.Rows.Count
        Print #1, "<Kurssi>"
        For c = 1 To Rng.Columns.Count
            Print #1, "<" & Rng.Cells(1, c) & ">";
            If IsDate(Rng.Cells(r, c)) Then
                Print #1, Format(Rng.Cells(r, c), "dd.mm.yyyy");
            Else
                Print #1, Rng.Cells(r, c).Text;
            End If
            Print #1, "</" & Rng.Cells(1, c) & ">"
        Next c
        Print #1, "</Kurssi>"
    Next r
'   Close the table
    Print #1, "</KurssitList>"

'   Close the file
    Close #1
...

I hope this helps.


问:
Remove square brackets from Select-Object result
So I have this Powershell-script that is supposed to get the status of all SQL Agent Jobs in my cluster.
The problem is that one of the objects value is withing square brackets, here is the code:

```<code>$output = ForEach ($instance in $instances)
{
    $instanceName = $instance.InstanceName
    Get-SqlAgentJob -ServerInstance "$env:computername\$instanceName" |
        Where-Object {$_.IsEnabled -eq "True" -and $_.LastRunDate -gt [DateTime]::Today.AddDays(-2)} |
            Select-Object Name,Description,Parent,LastRunOutcome,LastRunDate,LastRunDuration,HasSchedule,@{
                name='JobSchedules'
                expression={$_.JobSchedules -join ','}
                }
}
</code>```

This is the $output:

```<code>Name            : TestJob
Description     : No description available.
Parent          : [SERVER\INSTANCE]
LastRunOutcome  : Succeeded
LastRunDate     : 2020-06-01 05:30:00
LastRunDuration : 00:03:44
HasSchedule     : True
JobSchedules    : Daily
</code>```

As you can see, the "Parent" object is within square brackets [], how do I delete them in the end result?

答:
PowerShell has a feature called Calculated properties you can use to solve this.

It uses this syntax where Property1 and Property2 are normal properties:

```<code>Select-Object Property1,Property2, @{Name=‘NewColumn‘;Expression={<#code to calculate#>}}
</code>```

For instance, if you wanted to show the file size of each item in a directory in Megabytes, you could just add this column to your Select-Object command for Get-ChildItem.

```<code>dir | Select-Object Name,Length,@{Name='SizeMB';Exp={$_.Length/1mb -as [int]}}

Name                                                       Length SizeMB
----                                                       ------ ------
My Neighbor Totoro OST - 03 A Haunted House.mp4           4530480      4
myCoolBmp.bmp                                                1243      0
Ponyo Theme Song (with lyrics)-vUCnXCyUm7w.mp4            7884658      8
ResultUI.png                                                42887      0
shutUpandTakeMyMoney.png                                   575992      1
SomeNotes.txt                                                  14      0
SONIC • Chill Out Music Compilation (Part 1).mkv        168230106    160
The Village in May (My Neighbor Totoro)-5QXF2GeniSY.mp4   2686660      3
twimage.png                                                167827      0
Video Game Music for Studying 19-P-BqmegCUpA.webm       359146270    343
</code>```

So, to put it in practice for you, in the Select-Object statement simply remove Parent and replace it with

```<code>@{Name=‘Parent‘;Expression={$_.Parent.Replace('[','').Replace(']','')}}
</code>```

Body:
So I have this Powershell-script that is supposed to get the status of all SQL Agent Jobs in my cluster.
The problem is that one of the objects value is withing square brackets, here is the code:

$output = ForEach ($instance in $instances)
{
    $instanceName = $instance.InstanceName
    Get-SqlAgentJob -ServerInstance "$env:computername\$instanceName" |
        Where-Object {$_.IsEnabled -eq "True" -and $_.LastRunDate -gt [DateTime]::Today.AddDays(-2)} |
            Select-Object Name,Description,Parent,LastRunOutcome,LastRunDate,LastRunDuration,HasSchedule,@{
                name='JobSchedules'
                expression={$_.JobSchedules -join ','}
                }
}

This is the $output:

Name            : TestJob
Description     : No description available.
Parent          : [SERVER\INSTANCE]
LastRunOutcome  : Succeeded
LastRunDate     : 2020-06-01 05:30:00
LastRunDuration : 00:03:44
HasSchedule     : True
JobSchedules    : Daily

As you can see, the "Parent" object is within square brackets [], how do I delete them in the end result?

Body:
PowerShell has a feature called Calculated properties you can use to solve this.

It uses this syntax where Property1 and Property2 are normal properties:

Select-Object Property1,Property2, @{Name=‘NewColumn‘;Expression={<#code to calculate#>}}

For instance, if you wanted to show the file size of each item in a directory in Megabytes, you could just add this column to your Select-Object command for Get-ChildItem.

dir | Select-Object Name,Length,@{Name='SizeMB';Exp={$_.Length/1mb -as [int]}}

Name                                                       Length SizeMB
----                                                       ------ ------
My Neighbor Totoro OST - 03 A Haunted House.mp4           4530480      4
myCoolBmp.bmp                                                1243      0
Ponyo Theme Song (with lyrics)-vUCnXCyUm7w.mp4            7884658      8
ResultUI.png                                                42887      0
shutUpandTakeMyMoney.png                                   575992      1
SomeNotes.txt                                                  14      0
SONIC • Chill Out Music Compilation (Part 1).mkv        168230106    160
The Village in May (My Neighbor Totoro)-5QXF2GeniSY.mp4   2686660      3
twimage.png                                                167827      0
Video Game Music for Studying 19-P-BqmegCUpA.webm       359146270    343

So, to put it in practice for you, in the Select-Object statement simply remove Parent and replace it with

@{Name=‘Parent‘;Expression={$_.Parent.Replace('[','').Replace(']','')}}


问:
How to clean binary image using horizontal projection?
I want to remove anything other than text from a license plate with a binary filter.

I have the projections on each axis but I don't know how to apply it. My idea is to erase the white outlines.

This is the image I'm working for now:

This is the projection in Axis X:

```<code>from matplotlib import pyplot as plt
import pylab

(rows,cols)=img.shape
h_projection = np.array([ x/255/rows for x in img.sum(axis=0)])
plt.plot(range(cols), h_projection.T)
</code>```

And this is the result:

As you can see in the graph, at the end the line is shot by the white contour.

How can I erase everything that is at a certain threshold of the photo? Every help is appreciated

答:
So, you want to extract the black areas within the white characters.
For example, you can select the columns (or rows) in your histograms where the value is less than a certain threshold.

```<code>from matplotlib import pyplot as plt
import pylab
import numpy as np

img = plt.imread('binary_image/iXWgw.png')
(rows,cols)=img.shape
h_projection = np.array([ x/rows for x in img.sum(axis=0)])
threshold = (np.max(h_projection) - np.min(h_projection)) / 4
print("we will use threshold {} for horizontal".format(threshold))
# select the black areas
black_areas = np.where(h_projection < threshold)
fig = plt.figure(figsize=(16,8))
fig.add_subplot(121)
for j in black_areas:
    img[:, j] = 0
    plt.plot((j, j), (0, 1), 'g-')
plt.plot(range(cols), h_projection.T)

v_projection = np.array([ x/cols for x in img.sum(axis=1)])
threshold = (np.max(v_projection) - np.min(v_projection)) / 4
print("we will use threshold {} for vertical".format(threshold))
black_areas = np.where(v_projection < threshold)
fig.add_subplot(122)
for j in black_areas:
    img[j, :] = 0
    plt.plot((0,1), (j,j), 'g-')
plt.plot(v_projection, range(rows))
plt.show()

# obscurate areas on the image
plt.figure(figsize=(16,12))
plt.subplot(211)
plt.title("Image with the projection mask")
plt.imshow(img)

# erode the features
import scipy
plt.subplot(212)
plt.title("Image after erosion (suggestion)")
eroded_img = scipy.ndimage.morphology.binary_erosion(img,  structure=np.ones((5,5))).astype(img.dtype)
plt.imshow(eroded_img)
plt.show()
</code>```

So now you have the horizontal and vertical projections, that look like this

And after that you can apply the mask: there are several ways of doing this, in the code is already applied within the for loop, where we set img[:,j] = 0 for the columns, and img[j,:] = 0 for the rows. It was easy and I think intuitive, but you can look for other methods.
As a suggestion, I would say you can look into the morphological operator of erosion that can help to separate the white parts.
So the output would look like this.

Unfortunately, the upper and lower part still show white regions. You can manually set the rows to white img[:10,:] = 0, img[100:,:] = 0, but that probably would not work on all the images you have (if you are trying to train a neural network I assume you have lots of them, so you need to have a code that works on all of them.

So, since now you ask for segmentation also, this opens another topic. Segmentation is a complex task, and it is not as straightforward as a binary mask. I would strongly suggest you read some material on that before you just apply something without understanding. For example here a guide on image processing with scipy, but you may look for more.
As a suggestion and a small snippet to make it work, you can use the labeling from scipy.ndimage.
Here a small part of code (from the guide)

```<code>label_im, nb_labels = scipy.ndimage.label(eroded_img)
plt.figure(figsize=(16,12))
plt.subplot(211)
plt.title("Segmentation")
plt.imshow(label_im)
plt.subplot(212)
plt.title("One Object as an example")
plt.imshow(label_im == 6)   # change number for the others!
</code>```

Which will output:

As an example I showed the S letter. if you change label_im == 6 you will get the next letter. As you will see yourself, it is not always correct and other little pieces of the image are also considered as objects. So you will have to work a little bit more on that.

Body:
I want to remove anything other than text from a license plate with a binary filter.

I have the projections on each axis but I don't know how to apply it. My idea is to erase the white outlines.

This is the image I'm working for now:

This is the projection in Axis X:

from matplotlib import pyplot as plt
import pylab

(rows,cols)=img.shape
h_projection = np.array([ x/255/rows for x in img.sum(axis=0)])
plt.plot(range(cols), h_projection.T)

And this is the result:

As you can see in the graph, at the end the line is shot by the white contour.

How can I erase everything that is at a certain threshold of the photo? Every help is appreciated

Body:
So, you want to extract the black areas within the white characters.
For example, you can select the columns (or rows) in your histograms where the value is less than a certain threshold.

from matplotlib import pyplot as plt
import pylab
import numpy as np

img = plt.imread('binary_image/iXWgw.png')
(rows,cols)=img.shape
h_projection = np.array([ x/rows for x in img.sum(axis=0)])
threshold = (np.max(h_projection) - np.min(h_projection)) / 4
print("we will use threshold {} for horizontal".format(threshold))
# select the black areas
black_areas = np.where(h_projection < threshold)
fig = plt.figure(figsize=(16,8))
fig.add_subplot(121)
for j in black_areas:
    img[:, j] = 0
    plt.plot((j, j), (0, 1), 'g-')
plt.plot(range(cols), h_projection.T)

v_projection = np.array([ x/cols for x in img.sum(axis=1)])
threshold = (np.max(v_projection) - np.min(v_projection)) / 4
print("we will use threshold {} for vertical".format(threshold))
black_areas = np.where(v_projection < threshold)
fig.add_subplot(122)
for j in black_areas:
    img[j, :] = 0
    plt.plot((0,1), (j,j), 'g-')
plt.plot(v_projection, range(rows))
plt.show()

# obscurate areas on the image
plt.figure(figsize=(16,12))
plt.subplot(211)
plt.title("Image with the projection mask")
plt.imshow(img)

# erode the features
import scipy
plt.subplot(212)
plt.title("Image after erosion (suggestion)")
eroded_img = scipy.ndimage.morphology.binary_erosion(img,  structure=np.ones((5,5))).astype(img.dtype)
plt.imshow(eroded_img)
plt.show()

So now you have the horizontal and vertical projections, that look like this

And after that you can apply the mask: there are several ways of doing this, in the code is already applied within the for loop, where we set img[:,j] = 0 for the columns, and img[j,:] = 0 for the rows. It was easy and I think intuitive, but you can look for other methods.
As a suggestion, I would say you can look into the morphological operator of erosion that can help to separate the white parts.
So the output would look like this.

Unfortunately, the upper and lower part still show white regions. You can manually set the rows to white img[:10,:] = 0, img[100:,:] = 0, but that probably would not work on all the images you have (if you are trying to train a neural network I assume you have lots of them, so you need to have a code that works on all of them.

So, since now you ask for segmentation also, this opens another topic. Segmentation is a complex task, and it is not as straightforward as a binary mask. I would strongly suggest you read some material on that before you just apply something without understanding. For example here a guide on image processing with scipy, but you may look for more.
As a suggestion and a small snippet to make it work, you can use the labeling from scipy.ndimage.
Here a small part of code (from the guide)

label_im, nb_labels = scipy.ndimage.label(eroded_img)
plt.figure(figsize=(16,12))
plt.subplot(211)
plt.title("Segmentation")
plt.imshow(label_im)
plt.subplot(212)
plt.title("One Object as an example")
plt.imshow(label_im == 6)   # change number for the others!

Which will output:

As an example I showed the S letter. if you change label_im == 6 you will get the next letter. As you will see yourself, it is not always correct and other little pieces of the image are also considered as objects. So you will have to work a little bit more on that.


问:
WordPress custom theme errors with showing content
Wordpress index.php errors

<?php
get_header();
get_content();
get_footer();
?>
```

The footer.php is not showing, and when I remove the get_content() footer is working normally.

答:
You can try add while loop:

```<code>while ( have_posts() ) :

    print_r(get_the_content())

endwhile; // End the loop.
</code>```

It's worked. I checked.

Body:
Wordpress index.php errors

<?php
get_header();
get_content();
get_footer();
?>

The footer.php is not showing, and when I remove the get_content() footer is working normally.

Body:
You can try add while loop:

while ( have_posts() ) :

    print_r(get_the_content())

endwhile; // End the loop.

It's worked. I checked.


问:
What to embed the dynamic help command
So I coded a dynamic help command using the discord documentation. But to make it eye-catching, I want to embed it and display it into the users DM.
Here is a small snippet - </p>

```<code>execute(client, message, args) {
        const data = [];
        const { commands } = message.client;

        if (!args.length) {
            data.push('Here\'s a list of all my commands:'); //push on data var to append the info you want
            data.push(commands.map(command => command.name).join('\n'));
            data.push(`\nYou can send \`${prefix}help [command name]\` to get info on a specific command!`);

            return message.author.send(data, { split: true })
                .then(() => {
                    if (message.channel.type === 'dm') return;
                    message.reply('I\'ve sent you a DM with all my commands!');
                })
                .catch(error => {
                    console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
                    message.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
                });
        }
</code>```

<p>Is there anyway I can use data.push in an embed? </p>

答:
Do you mean make an embed and display it with all the command names?

Is there anyway I can use data.push in an embed

Not sure what you exactly mean but from what I understand, no, an embed has properties like fields, files, title and etc, you can set those though instead of using your current method of an array of data.

This might be what you want:

execute(client, message, args) {
  const data = [];
  const { commands } = message.client;
  if (!args.length) {
    //you'll need refrence to this somehow, like const {MessageEmbed} = require("discord.js")
    const embed = new MessageEmbed()
      .setTitle("Here's a list of all my commands:");
      .setDescription(commands.map(cmd => cmd.name).join("\n"));
      .setFooter(`You can send \`${prefix}help [command name]\` to get info on a specific command!`);

    return message.author.send(data, { split: true })
      .then(() => {
        if (message.channel.type === 'dm') return;
        message.reply('I\'ve sent you a DM with all my commands!');
      })
      .catch(error => {
        console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
        message.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
      });
  }
}
```

Title: What to embed the dynamic help command

Body:
So I coded a dynamic help command using the discord documentation. But to make it eye-catching, I want to embed it and display it into the users DM.
Here is a small snippet -

execute(client, message, args) {
        const data = [];
        const { commands } = message.client;

        if (!args.length) {
            data.push('Here\'s a list of all my commands:'); //push on data var to append the info you want
            data.push(commands.map(command => command.name).join('\n'));
            data.push(`\nYou can send \`${prefix}help [command name]\` to get info on a specific command!`);

            return message.author.send(data, { split: true })
                .then(() => {
                    if (message.channel.type === 'dm') return;
                    message.reply('I\'ve sent you a DM with all my commands!');
                })
                .catch(error => {
                    console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
                    message.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
                });
        }

Is there anyway I can use data.push in an embed?


答:
Using dplyr you have to do two things to get your desired result:

df1[df1==0] <- 0.00001
df1 %>%
  mutate_at(vars(-Name), log)
```

But since you want to use a log on your columns I advice to skip the df1[df1==0] <- 0.00001 part and replace -Inf created by log with 0 or NA or whatever value you need.

Title: Add number to all zeros within a dataframe and log-transform

Body:
I have a dataframe that looks like this:

df1 <- structure(list(Name = c("Mark", "Anders", "Tom", "Vin", "Marcel",
"Tyta", "Gerta", "Moses", "Hank", "Rita", "Margary"), Col = c(1769380097.5,
1444462500, 1499146687.5, 1276309375, 22279500, 3114023471, 2961012500,
3978937423.5, 1703925000, 1838885550, 0), item1 = c(1534931323.07692,
1794881375, 2292661687.5, 855786250, 21915500, 3056061512.25,
3581940000, 3766909703.25, 2043300000, 2135859875, 1482031250
), item2 = c(1628137500, 1781982737.5, 1659391250, 741220687.5,
41242000, 2833327766.38514, 3675450000, 3592650662.5, 1586512500,
1934575000, 1467271250), item3 = c(1545572702.88461, 1748600000,
1745026687.5, 1556481250, 0, 3551716021.25, 3108137500, 3718036445,
1380278750, 2217526000, 1026813750)), .Names = c("Name", "Col",
"dKO1", "dKO2", "sdi1"), row.names = c(29L, 30L, 1278L, 1295L,
1296L, 1297L, 1298L, 1307L, 1642L, 1674L, 1754L), class = "data.frame")

> df1
        Name        Col       dKO1       dKO2       sdi1
29      Mark 1769380098 1534931323 1628137500 1545572703
30    Anders 1444462500 1794881375 1781982738 1748600000
1278     Tom 1499146688 2292661688 1659391250 1745026688
1295     Vin 1276309375  855786250  741220688 1556481250
1296  Marcel   22279500   21915500   41242000          0
1297    Tyta 3114023471 3056061512 2833327766 3551716021
1298   Gerta 2961012500 3581940000 3675450000 3108137500
1307   Moses 3978937424 3766909703 3592650662 3718036445
1642    Hank 1703925000 2043300000 1586512500 1380278750
1674    Rita 1838885550 2135859875 1934575000 2217526000
1754 Margary          0 1482031250 1467271250 1026813750

Some values are zeros. I want to add 0.00001 to those numbers across the entire dataframe. Then, i want to log transform all the columns, excluding the first one. How can I do this?

Body:
Using dplyr you have to do two things to get your desired result:

df1[df1==0] <- 0.00001
df1 %>%
  mutate_at(vars(-Name), log)

But since you want to use a log on your columns I advice to skip the df1[df1==0] <- 0.00001 part and replace -Inf created by log with 0 or NA or whatever value you need.


问:
Unable to edit form fields in Reactjs after fetched from server
I have a user edit page in Reactjs where I fetch the user details and populate it to corresponding input fields. The problem is after fetching and displaying the data I'm not able to edit the fields.

My code is:

```<code>function EditProfile(props) {
    const [user, setUser] = useState()
    useEffect(() => {
        const fetchUserInfo = async () => {
            const profileConfig = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + auth.token
                }
            };
            fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
            .then(response => response.json())
            .then(response => {
                console.log("response: ", response.user);
                if (response.success === true) {
                    setUser(response.user)
                } else {
                    alert(response.message)
                }
            },
            (error) => {
                alert('User fetching faied: ' + error)
            })
        }
        fetchUserInfo()
    }, [])

    return (
       <form>
           <input type="text" value={user.name} name="name" />
       </form>
    )
}
</code>```

The corresponding name is displayed in this input field but not editable. How to solve the issue?

答:
In React controlled component needs value & change handler.</p>

```<code>function EditProfile(props) {
    const [user, setUser] = useState({name: ''})

    useEffect(() => {
        /*
          ....
        */
    }, [])

    const handleChange = e => {
       setUser({...user, name: e.target.value})
    }

    return (
       <form>
           <input type="text" onChange={handleChange} value={user.name} name="name" />
       </form>
    )
}
</code>```

Body:
I have a user edit page in Reactjs where I fetch the user details and populate it to corresponding input fields. The problem is after fetching and displaying the data I'm not able to edit the fields.

My code is:

function EditProfile(props) {
    const [user, setUser] = useState()
    useEffect(() => {
        const fetchUserInfo = async () => {
            const profileConfig = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + auth.token
                }
            };
            fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
            .then(response => response.json())
            .then(response => {
                console.log("response: ", response.user);
                if (response.success === true) {
                    setUser(response.user)
                } else {
                    alert(response.message)
                }
            },
            (error) => {
                alert('User fetching faied: ' + error)
            })
        }
        fetchUserInfo()
    }, [])

    return (
       <form>
           <input type="text" value={user.name} name="name" />
       </form>
    )
}

The corresponding name is displayed in this input field but not editable. How to solve the issue?

Body:
In React controlled component needs value & change handler.

function EditProfile(props) {
    const [user, setUser] = useState({name: ''})

    useEffect(() => {
        /*
          ....
        */
    }, [])

    const handleChange = e => {
       setUser({...user, name: e.target.value})
    }

    return (
       <form>
           <input type="text" onChange={handleChange} value={user.name} name="name" />
       </form>
    )
}


问:
How can I solve the error (you can not use my_ area in a patch context, it is a turtle-only)?
I want the turtles to back again to their areas if batches which I had defined before. The problem is I got an error

```<code>you can not use my_ area in a patch context, it is a turtle-only
</code>```

the button is

```<code>to back_from_event

  ask turtles with [ area = 1 ]  [ move-to one-of patches with [ (not any? other turtles-here) and ( area = my_area )  ] ]

end
</code>```

the patches defined as below and the turtles were in areas (2,3,4,5) and moved to area 1 and I need them to back again to there areas:

```<code>to define_areas

  ask patches with [ (pxcor > -3) and (pxcor < 3) and (pycor > -3) and (pycor < 3) ] [  set pcolor white set area 1    ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 2     ]
  ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 3    ]
   ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 4    ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 5   ]

end
</code>```

答:
Okay, this is the same problem as your previous question. Please try to understand the answer rather than simply copy the code. Otherwise, you will keep asking the same question.

You have 'area' as a patch variable and 'my_area' as a turtle variable.

What you need to realise is that turtle to patch is unique because a turtle can only be in one place at a time. Therefore, a turtle can access the variables owned by the patch that it is sitting on without having to specify the patch. So code like this is okay:

```<code>ask turtles with [area = 1] [ ]
</code>```

This is because it is equivalent to:

```<code>ask turtles with [ [area] of patch-here = 1] [ ]
</code>```

However, a patch cannot access a variable owned by a turtle because there may be multiple turtles on the same patch. For example, if you asked a patch to set its pcolor to color and you had red turtle and a blue turtle on the patch, how would it know which color to choose?

Your error says "you can not use my_area in a patch context, it is a turtle-only". That is telling you that you tried to have a patch use the my_area variable but that variable is owned by turtles. So you didn't tell it which turtle to get my_area from.

This is what you have:

```<code>to back_from_event
  ask turtles with [ area = 1 ]
  [ move-to one-of patches with [(not any? other turtles-here) and (area = my_area)]
  ]
end
</code>```

I assume you want the area of the patch to be the same as the my_area of the turtle doing the asking. That is what myself is for.

```<code>to back_from_event
  ask turtles with [ area = 1 ]
  [ move-to one-of patches with [(not any? other turtles-here) and (area = [my_area] of myself)]
  ]
end
</code>```

Body:
I want the turtles to back again to their areas if batches which I had defined before. The problem is I got an error

you can not use my_ area in a patch context, it is a turtle-only

the button is

to back_from_event

  ask turtles with [ area = 1 ]  [ move-to one-of patches with [ (not any? other turtles-here) and ( area = my_area )  ] ]

end

the patches defined as below and the turtles were in areas (2,3,4,5) and moved to area 1 and I need them to back again to there areas:

to define_areas

  ask patches with [ (pxcor > -3) and (pxcor < 3) and (pycor > -3) and (pycor < 3) ] [  set pcolor white set area 1    ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 2     ]
  ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 3    ]
   ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 4    ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 5   ]

end

Body:
Okay, this is the same problem as your previous question. Please try to understand the answer rather than simply copy the code. Otherwise, you will keep asking the same question.

You have 'area' as a patch variable and 'my_area' as a turtle variable.

What you need to realise is that turtle to patch is unique because a turtle can only be in one place at a time. Therefore, a turtle can access the variables owned by the patch that it is sitting on without having to specify the patch. So code like this is okay:

ask turtles with [area = 1] [ ]

This is because it is equivalent to:

ask turtles with [ [area] of patch-here = 1] [ ]

However, a patch cannot access a variable owned by a turtle because there may be multiple turtles on the same patch. For example, if you asked a patch to set its pcolor to color and you had red turtle and a blue turtle on the patch, how would it know which color to choose?

Your error says "you can not use my_area in a patch context, it is a turtle-only". That is telling you that you tried to have a patch use the my_area variable but that variable is owned by turtles. So you didn't tell it which turtle to get my_area from.

This is what you have:

to back_from_event
  ask turtles with [ area = 1 ]
  [ move-to one-of patches with [(not any? other turtles-here) and (area = my_area)]
  ]
end

I assume you want the area of the patch to be the same as the my_area of the turtle doing the asking. That is what myself is for.

to back_from_event
  ask turtles with [ area = 1 ]
  [ move-to one-of patches with [(not any? other turtles-here) and (area = [my_area] of myself)]
  ]
end


问:
Efficiently rename/re-map javascript/json object keys within array of objects
I have some structured JSON data like so. Let's assume this is interchangeable, via JSON.parse():

```<code>[
    {
        "title": "pineapple",
        "uid": "ab982d34c98f"
    },
    {
        "title": "carrots",
        "uid": "6f12e6ba45ec"
    }
]
</code>```

I need it to look like this, remapping title to name, and uid to id with the result:

```<code>[
    {
        "name": "pineapple",
        "id": "ab982d34c98f"
    },
    {
        "name": "carrots",
        "id": "6f12e6ba45ec"
    }
]
</code>```

The most obvious way of doing it is like this:

```<code>str = '[{"title": "pineapple","uid": "ab982d34c98f"},{"title": "carrots", "uid": "6f12e6ba45ec"}]';

var arr = JSON.parse(str);
for (var i = 0; i<arr.length; i++) {
    arr[i].name = arr[i].title;
    arr[i].id = arr[i].uid;
    delete arr[i].title;
    delete arr[i].uid;
}
</code>```

str = '[{"title": "pineapple","uid": "ab982d34c98f"},{"title": "carrots",      "uid": "6f12e6ba45ec"}]';

var arr = JSON.parse(str);
for (var i = 0; i<arr.length; i++) {
    arr[i].name = arr[i].title;
    arr[i].id = arr[i].uid;
    delete arr[i].title;
    delete arr[i].uid;
}

$('body').append("```"+JSON.stringify(arr, undefined, 4)+"```");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

...or using something more complex (albeit not more efficient) like this.

This is all fine and dandy, but what if there were 200,000 objects in the array? This is a lot of processing overhead.

Is there a more efficient way to remap a key name? Possibly without looping through the entire array of objects? If your method is more efficient, please provide proof/references.

答:
```<code>function replaceElem(value, replace, str) {
            while (str.indexOf(value) > -1) {
                str = str.replace(value, replace);
            }
            return str;
        }
</code>```

call this from main

```<code>var value = "tittle";
var replace = "name";
replaceElem(value, replace, str);
</code>```

Body:
I have some structured JSON data like so. Let's assume this is interchangeable, via JSON.parse():

[
    {
        "title": "pineapple",
        "uid": "ab982d34c98f"
    },
    {
        "title": "carrots",
        "uid": "6f12e6ba45ec"
    }
]

I need it to look like this, remapping title to name, and uid to id with the result:

[
    {
        "name": "pineapple",
        "id": "ab982d34c98f"
    },
    {
        "name": "carrots",
        "id": "6f12e6ba45ec"
    }
]

The most obvious way of doing it is like this:

str = '[{"title": "pineapple","uid": "ab982d34c98f"},{"title": "carrots", "uid": "6f12e6ba45ec"}]';

var arr = JSON.parse(str);
for (var i = 0; i<arr.length; i++) {
    arr[i].name = arr[i].title;
    arr[i].id = arr[i].uid;
    delete arr[i].title;
    delete arr[i].uid;
}

str = '[{"title": "pineapple","uid": "ab982d34c98f"},{"title": "carrots",      "uid": "6f12e6ba45ec"}]';

var arr = JSON.parse(str);
for (var i = 0; i<arr.length; i++) {
    arr[i].name = arr[i].title;
    arr[i].id = arr[i].uid;
    delete arr[i].title;
    delete arr[i].uid;
}

$('body').append("
"+JSON.stringify(arr, undefined, 4)+"
");

...or using something more complex (albeit not more efficient) like this.

This is all fine and dandy, but what if there were 200,000 objects in the array? This is a lot of processing overhead.

Is there a more efficient way to remap a key name? Possibly without looping through the entire array of objects? If your method is more efficient, please provide proof/references.

Body:
function replaceElem(value, replace, str) {
            while (str.indexOf(value) > -1) {
                str = str.replace(value, replace);
            }
            return str;
        }

call this from main

var value = "tittle";
var replace = "name";
replaceElem(value, replace, str);


问:
Should x._1,x._2... syntax be avoided?
I'm just starting out in Scala. I find myself using tuple variables a lot.

For example, here's some code I wrote:

```<code>/* Count each letter of a string and return in a list sorted by character
 * countLetter("test") = List(('e',1),('s',1),('t',2))
*/
def countLetters(s: String): List[(Char, Int)] = {
  val charsListMap = s.toList.groupBy((c:Char) => c)
  charsListMap.map(x => (x._1, x._2.length)).toList.sortBy(_._1)
}
</code>```

Is this tuple syntax (x._1, x._2 etc) frowned upon by Scala developers?

答:
Starting in Scala 3, with the parameter untupling feature, the following will become an alternative for .map(x => x._1 -> x._2.length):

```<code>.map(_ -> _.length)
</code>```

and thus, your example becomes:

```<code>"test".toList.groupBy(identity).map(_ -> _.length).toList.sortBy(identity)
// List(("e", 1), ("s", 1), ("t", 2))
</code>```

Concerning your example more specifically and starting in Scala 2.13, you could also use groupMapReduce which (as its name suggests) is an equivalent of a groupBy followed by mapValues and a reduce step:

```<code>"test".groupMapReduce(identity)(_ => 1)(_ + _).toList.sortBy(identity)
</code>```

Title: Should x._1,x._2... syntax be avoided?

Body:
I'm just starting out in Scala. I find myself using tuple variables a lot.

For example, here's some code I wrote:

/* Count each letter of a string and return in a list sorted by character
 * countLetter("test") = List(('e',1),('s',1),('t',2))
*/
def countLetters(s: String): List[(Char, Int)] = {
  val charsListMap = s.toList.groupBy((c:Char) => c)
  charsListMap.map(x => (x._1, x._2.length)).toList.sortBy(_._1)
}

Is this tuple syntax (x._1, x._2 etc) frowned upon by Scala developers?

Body:
Starting in Scala 3, with the parameter untupling feature, the following will become an alternative for .map(x => x._1 -> x._2.length):

.map(_ -> _.length)

and thus, your example becomes:

"test".toList.groupBy(identity).map(_ -> _.length).toList.sortBy(identity)
// List(("e", 1), ("s", 1), ("t", 2))

Concerning your example more specifically and starting in Scala 2.13, you could also use groupMapReduce which (as its name suggests) is an equivalent of a groupBy followed by mapValues and a reduce step:

"test".groupMapReduce(identity)(_ => 1)(_ + _).toList.sortBy(identity)


问:
Creating animation on ImageView while changing image resource
I have only one ImageView in my layout and I am changing its resource when a gasture event detected. I just want to show an animation while changing resource of ImageView. Can I use ViewFlipper with one ImageView?

答:
I found another way to animate it using transition drawable(I took idea from here)

```<code>public static void setImageDrawableWithAnimation(ImageView imageView,
                                                 Drawable drawable,
                                                 int duration) {
    Drawable currentDrawable = imageView.getDrawable();
    if (currentDrawable == null) {
        imageView.setImageDrawable(drawable);
        return;
    }

    TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[] {
            currentDrawable,
            drawable
    });
    imageView.setImageDrawable(transitionDrawable);
    transitionDrawable.startTransition(duration);
}
</code>```

Analogous kotlin extension function:

```<code>fun ImageView.setImageDrawableWithAnimation(drawable: Drawable, duration: Int = 300) {
    val currentDrawable = getDrawable()
    if (currentDrawable == null) {
        setImageDrawable(drawable)
        return
    }

    val transitionDrawable = TransitionDrawable(arrayOf(
            currentDrawable,
            drawable
    ))
    setImageDrawable(transitionDrawable)
    transitionDrawable.startTransition(duration)
}
</code>```

If your drawables contains transparent parts, this flag could be useful to prevent old drawable visibility:

```<code>transitionDrawable.setCrossFadeEnabled(true);
</code>```

Body:
I found another way to animate it using transition drawable(I took idea from here)

public static void setImageDrawableWithAnimation(ImageView imageView,
                                                 Drawable drawable,
                                                 int duration) {
    Drawable currentDrawable = imageView.getDrawable();
    if (currentDrawable == null) {
        imageView.setImageDrawable(drawable);
        return;
    }

    TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[] {
            currentDrawable,
            drawable
    });
    imageView.setImageDrawable(transitionDrawable);
    transitionDrawable.startTransition(duration);
}

Analogous kotlin extension function:

fun ImageView.setImageDrawableWithAnimation(drawable: Drawable, duration: Int = 300) {
    val currentDrawable = getDrawable()
    if (currentDrawable == null) {
        setImageDrawable(drawable)
        return
    }

    val transitionDrawable = TransitionDrawable(arrayOf(
            currentDrawable,
            drawable
    ))
    setImageDrawable(transitionDrawable)
    transitionDrawable.startTransition(duration)
}

If your drawables contains transparent parts, this flag could be useful to prevent old drawable visibility:

transitionDrawable.setCrossFadeEnabled(true);


问:
MediaWiki installation issue - port problems
I am trying to install MediaWiki version 1.31 localy and I have run into some issues that I cant get past by. Mainly when I input datatabe connection (I am trying to connect to PostgreSQL database) information it returns this error.

Thing is the port I am trying to connect is 5433 not 5432, also the names "template1" and "postgres" are not included in my input trough the dialogue screen - I dont know where they came from. "test1" is the name of the database I am trying to  connect to.
Any help or advice how to get trough this error would be greatly appreciated. Thank you.

答:
That the port you specify is not used while setting up the database schema in the first place is a long-standing known bug.  One workaround is to run your database on the default port until you have wiki set up, then change it back to the port you want.

In order to create a new database, you need to connect to an existing database in the same cluster.  'template1' and 'postgres' are pre-existing databases (usually created at the time the cluster was created) commonly used to connect to in order to create a new database.  These names are "well-known", you don't need to specify them.


问:
Why does this Eloquent query not get the expected results?
For practice, I am making a web app in Laravel for a fictional company that sells training courses. I have a table for Courses, Venues, and Instances. An Instance defines the date and venue for a particular course. For example, Course A may run in New York on 2020-06-05, London on 2020-07-02, etc etc.

I have defined the relationships like this:

```<code>class Instance extends Model
{
    public function courses(){
        return $this->belongsTo(Course::class);
    }

    public function venues(){
        return $this->belongsTo(Venue::class);
    }

}
</code>```

```<code>class Course extends Model
{
    public function instances(){
        return $this->hasMany(Instance::class);
    }
}
</code>```

```<code>class Venue extends Model
{
    public function instances(){
        return $this->hasMany(Instance::class);
    }
}
</code>```

The id of the courses and venues table are foreign keys in the instance table.

I want to get all the instances associated with a given course, and pull in the venue for each one too, so I try the following query in Tinker:

$instance = App\Instance::with('venues')->where('course_id','=',1)->get()

This gives me the following output:

```<code>         course_id: 1,
         venue_id: 2,
         date: "2020-11-04",
         length: 0,
         cost: 635.0,
         created_at: "2020-05-26 13:35:06",
         updated_at: "2020-05-26 13:35:06",
         venues: null,
</code>```

As you can see, venues is null. My question is... why?

答:
The issue is the pluralised name you have given to the function.

Laravel under the hood will look at the function name and work out the foreign key it should try to use. So in your case its looking for 'venues_id', because a 'belongs_to' relationship should return a single record the function name should be venue(), then Laravel will look for 'venue_id'.

Of course you can override the foreign key as you have but just explaining why it didnt work.

Body:
For practice, I am making a web app in Laravel for a fictional company that sells training courses. I have a table for Courses, Venues, and Instances. An Instance defines the date and venue for a particular course. For example, Course A may run in New York on 2020-06-05, London on 2020-07-02, etc etc.

I have defined the relationships like this:

class Instance extends Model
{
    public function courses(){
        return $this->belongsTo(Course::class);
    }

    public function venues(){
        return $this->belongsTo(Venue::class);
    }

}

class Course extends Model
{
    public function instances(){
        return $this->hasMany(Instance::class);
    }
}

class Venue extends Model
{
    public function instances(){
        return $this->hasMany(Instance::class);
    }
}

The id of the courses and venues table are foreign keys in the instance table.

I want to get all the instances associated with a given course, and pull in the venue for each one too, so I try the following query in Tinker:

$instance = App\Instance::with('venues')->where('course_id','=',1)->get()

This gives me the following output:

         course_id: 1,
         venue_id: 2,
         date: "2020-11-04",
         length: 0,
         cost: 635.0,
         created_at: "2020-05-26 13:35:06",
         updated_at: "2020-05-26 13:35:06",
         venues: null,

As you can see, venues is null. My question is... why?


问:
Why RxJava2 does not emitter data to the thread
I have read the RxJava's doc. and try the demo below:
The Output is d = [0]d = false

May I know the reason that: why the data does not emitter to the Observer

RxJava version: 2.2.6

```<code>        Observable.just("aa","bbb")
                .observeOn(Schedulers.newThread())
                .map(s -> {
                    System.out.println("s = [" + s + "]");
                    return s.toUpperCase();
                })
                .subscribeOn(Schedulers.single())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        System.out.println("d = [" + d + "]"+"d = "+ d.isDisposed());
                    }

                    @Override
                    public void onNext(String s) {
                        System.out.println("s = [" + s + "]");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
</code>```

答:
With all the thread switches you have added to your subscription your subscription is not running on the main thread anymore. This also means that nothing is stopping the main thread anymore and you application quits before it could print the data you want.

For testing purposes you can add a Thread.sleep(1000); at the end of your main() method (where I suppose you have added this code). Then you will see the output from the System.out.println() statements. Other solutions are to not use subscribeOn() or observeOn() and stay on the current thread. Also, you can use blockingSubscribe() to wait for the subscription to finish before continuing on the main thread.

Body:
I have read the RxJava's doc. and try the demo below:
The Output is d = [0]d = false

May I know the reason that: why the data does not emitter to the Observer

RxJava version: 2.2.6

        Observable.just("aa","bbb")
                .observeOn(Schedulers.newThread())
                .map(s -> {
                    System.out.println("s = [" + s + "]");
                    return s.toUpperCase();
                })
                .subscribeOn(Schedulers.single())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        System.out.println("d = [" + d + "]"+"d = "+ d.isDisposed());
                    }

                    @Override
                    public void onNext(String s) {
                        System.out.println("s = [" + s + "]");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


问:
Would calling a mediator be correct in my Handler when crossing services/modules in a DDD monolith

Preface about the architecture

In a microservice, this could be a service according to clean-architecture:

BasketService

Api

Application  [CQRS]

Core

Infrastructure

CatalogService

Api

Application  [CQRS]

Core

Infrastructure

But since i'm applying DDD to a monolith, i can currently remove my Api layer and have less "projects"/module. So every module ( eg. basket and catalog) contains 3 projects currently:

Application

Core

Infrastructure

Both have a dependency on .Core

Problem description

My application has a BasketModule and a CatalogModule.
Would it be correct to get information from the CatalogModule ( which contains the products) with Mediator like this:

```<code>public Task<BasketDTO> Handle(GetBasketByBuyerIdCommand request, CancellationToken cancellationToken)
    {
        BasketDTO result;
        var basket = m_basketRepo.GetById(request.BuyerId);

        if (basket == null)
        {
            result = new BasketDTO()
            {
                BuyerId = request.BuyerId,
                Items = new List<BasketItem>()
            };
            return Task.FromResult(result);
        }

        //Could be automapper, but not now currently //ignore
        var products = new List<DTO.Product>();

        foreach (var item in basket.Items)
        {
          var product = m_mediator.Send(new GetProductByIdQuery(item.ProductId)).Result; //ignore the non-async. It's example code

            products.Add(new DTO.Product()
            {
                Id = product.Id,
                Price = product.Price,
                Title = product.Title
            });
        }

        result = new BasketDTO()
        {
            BuyerId = basket.BuyerId,
            Items = basket.Items
            .Select(dl => new DTO.BasketItem()
            {

                ProductId = dl.ProductId,
                Quantity = dl.Quantity,
                Product = products
                .Where(cl => cl.Id == dl.ProductId)
                .FirstOrDefault()
            }).ToList()
        };

        return Task.FromResult(result);
    }
}
</code>```

It is about the following line:

```<code> var product = await m_mediator.Send(new GetProductByIdQuery(item.ProductId));
</code>```

Is this correct to do? I'm not talking about the rest of the example code, but specifically about calling the mediator to get the product and having a dependency of the project "Basket.Application" on "Catalog.Application"

答:
The mean role of a mediator is to decouple the presentation layer from the application services and do some default treatments using middlewares, rather than communicating between bounded contexts.

Thus I would prefer to have a mediator per bounded context :)

To integrate the two BCs you can add an interface of GetProductByIdQuery to the Basket domain (or application) layer and have its implementation in Basket/infra.

The implementation of GetProductByIdQuery (considered as a secondary adapter) may call the mediator of Catalog's BC, and transform the result to preserve the ubiquitous language.

IMHO, This will keep the monolith clean and reduce the migration cost if you decide to split some parts of it i.e only the secondary adapter implementation will change to do some inter-process communication instead.

PS: I'm not really familiar with clean architecture, but I consider it a more featured version of the Hexagonal one..

Body:
Preface about the architecture

In a microservice, this could be a service according to clean-architecture:

BasketService

Api

Application  [CQRS]

Core

Infrastructure

CatalogService

Api

Application  [CQRS]

Core

Infrastructure

But since i'm applying DDD to a monolith, i can currently remove my Api layer and have less "projects"/module. So every module ( eg. basket and catalog) contains 3 projects currently:

Application

Core

Infrastructure

Both have a dependency on .Core

Problem description

My application has a BasketModule and a CatalogModule.
Would it be correct to get information from the CatalogModule ( which contains the products) with Mediator like this:

public Task<BasketDTO> Handle(GetBasketByBuyerIdCommand request, CancellationToken cancellationToken)
    {
        BasketDTO result;
        var basket = m_basketRepo.GetById(request.BuyerId);

        if (basket == null)
        {
            result = new BasketDTO()
            {
                BuyerId = request.BuyerId,
                Items = new List<BasketItem>()
            };
            return Task.FromResult(result);
        }

        //Could be automapper, but not now currently //ignore
        var products = new List<DTO.Product>();

        foreach (var item in basket.Items)
        {
          var product = m_mediator.Send(new GetProductByIdQuery(item.ProductId)).Result; //ignore the non-async. It's example code

            products.Add(new DTO.Product()
            {
                Id = product.Id,
                Price = product.Price,
                Title = product.Title
            });
        }

        result = new BasketDTO()
        {
            BuyerId = basket.BuyerId,
            Items = basket.Items
            .Select(dl => new DTO.BasketItem()
            {

                ProductId = dl.ProductId,
                Quantity = dl.Quantity,
                Product = products
                .Where(cl => cl.Id == dl.ProductId)
                .FirstOrDefault()
            }).ToList()
        };

        return Task.FromResult(result);
    }
}

It is about the following line:

 var product = await m_mediator.Send(new GetProductByIdQuery(item.ProductId));

Is this correct to do? I'm not talking about the rest of the example code, but specifically about calling the mediator to get the product and having a dependency of the project "Basket.Application" on "Catalog.Application"


问:
Getting error messages from QtCreator when trying to build hello world program but the code can still be executed
Im doing another QtCreator setup on a new system, and now Im getting errors when I try to build even a hello world program.Seems something is wrong with my C++ libs of how Qt is trying to put them together. I'm truly stumped here, any suggestions at all are appreciated.

Looked at this a bit more, and it is even stranger than i thought. There is build errors on several lines of several of my projects, but they are actually building and can be ran and even debugged! Unknown type name errors on almost every Qt type, but it still works fine.

So I know even less about the issue: many errors, but everything runs fine....

Anyone seen this before?

答:
So this is caused by some changes they have made to the Clang code model( which I do not/never have used ) and apparaently is quite a common issue.

See: https://forum.qt.io/topic/107181/lot-of-errors-but-it-builds-and-runs-successfully/2

To disable go to Help->About plugins and uncheck the Clang code model box.
Restart QtCreator and this will solve it.

Strange.


问:
            ';
        }
```

It seems that there is a filter that strips the "style" tag in the entire template. That's because when I convert the code above and instead of  add  the font-face is rendered successfully. This does not affect anything ofcourse because 'style2' is not a valid tag.

Title: <style> tag has been removed from woocommerce email templates

Body:
I'm trying to add a 'style' tag inside my woocommerce email templates, in order to include a font-face attribute, with no success.

What I already tried is to:

Add it directly in the template file (ex. email-header.php)

Add it in 'woocommerce_email_header' filter

add_action('woocommerce_email_header', 'add_style_tag_to_email', 10);
function add_style_tag_to_email() {
            echo '

            ';
        }

It seems that there is a filter that strips the "style" tag in the entire template. That's because when I convert the code above and instead of  add  the font-face is rendered successfully. This does not affect anything ofcourse because 'style2' is not a valid tag.

Body:
This is caused by Emogrifier, which tries to convert all <style> tags(and others) into inline styles. You can prevent this by changing the settings like so:

add_action('woocommerce_emogrifier', function($emogrifier){
    $emogrifier->disableStyleBlocksParsing();
});


问:
Cannot find the object "XXX" because it does not exist or you do not have permission
I'm getting the following error when calling a stored procedure:

Cannot find the object "XXX" because it does not exist or you do not have permission.

I've checked the database and the SP is there with the correct permissions yet I'm still getting the error.

Any suggestions?

答:
Possible typo or already removed? Refresh your view or query for it (looks like this was for a stored procedure):

```<code>SELECT name AS procedure_name
    ,SCHEMA_NAME(schema_id) AS schema_name
    ,type_desc
    ,create_date
    ,modify_date
FROM sys.procedures;
</code>```

Then if it's listed, copy the name and try your query with the name taken from those results (or copy the object's name any other way you may be familiar with).

MORE GENERIC SOLUTION FOR ANY OBJECT (if you have SSMS):
In SQL Server Management Studio, right-click on the object, "Script [OBJECT_TYPE] as", DROP To (or the action you're attempting), New Query Editor.

If you can run this successfully you probably had a typo.

OwnerDisplayName: Twiggz

ContentLicense: CC BY-SA 2.5

Body:
Possible typo or already removed? Refresh your view or query for it (looks like this was for a stored procedure):

SELECT name AS procedure_name
    ,SCHEMA_NAME(schema_id) AS schema_name
    ,type_desc
    ,create_date
    ,modify_date
FROM sys.procedures;

Then if it's listed, copy the name and try your query with the name taken from those results (or copy the object's name any other way you may be familiar with).

MORE GENERIC SOLUTION FOR ANY OBJECT (if you have SSMS):
In SQL Server Management Studio, right-click on the object, "Script [OBJECT_TYPE] as", DROP To (or the action you're attempting), New Query Editor.

If you can run this successfully you probably had a typo.