问:
Is it possible to change volume with no reencode with ffmpeg?
I just had this question because I used the following command with ffmpeg:

```<code>ffmpeg -i input.wav -filter:a "volume=0.2" output.wav
</code>```

Following the documentation here: https://trac.ffmpeg.org/wiki/AudioVolume

However, when I created the new file, the output was half the size of the input and the bitrate of the audio track was reduced as well.

So my questions are:

Is the bitrate supposed to decrease with decreasing and increasing volume like so?

Is it possible to change volume without reencoding with ffmpeg?

答:
Okay as someone from Reddit kindly explained to me, I should be able to change the volume without reencoding, however, my input codec was pcm_f32le and the default setting for the output codec for ffmpeg without any specifiers is pcm_f16le.

The first one pcm_f32le is 32 bits, so it stores more information than the second which is 16 bits.

So the answer is:

Yes it is because in this case I was reencoding unknowingly to a codec with less information.

Actually no, it still reencoding. The best option is to use the same code I used above with an extra specifier:

```<code>ffmpeg -i input.wav -filter:a "volume=0.2" -c:a pcm_f32le output.wav
</code>```

The codec for input and output must be the same as in both 32 bit or 16 bit or else I have to add a specifier which I was shown how to do by the same person on Reddit.

However, this is still reencoding whenever you add a filter.

Body:
I just had this question because I used the following command with ffmpeg:

ffmpeg -i input.wav -filter:a "volume=0.2" output.wav

Following the documentation here: https://trac.ffmpeg.org/wiki/AudioVolume

However, when I created the new file, the output was half the size of the input and the bitrate of the audio track was reduced as well.

So my questions are:

Is the bitrate supposed to decrease with decreasing and increasing volume like so?

Is it possible to change volume without reencoding with ffmpeg?

Body:
Okay as someone from Reddit kindly explained to me, I should be able to change the volume without reencoding, however, my input codec was pcm_f32le and the default setting for the output codec for ffmpeg without any specifiers is pcm_f16le.

The first one pcm_f32le is 32 bits, so it stores more information than the second which is 16 bits.

So the answer is:

Yes it is because in this case I was reencoding unknowingly to a codec with less information.

Actually no, it still reencoding. The best option is to use the same code I used above with an extra specifier:

ffmpeg -i input.wav -filter:a "volume=0.2" -c:a pcm_f32le output.wav

The codec for input and output must be the same as in both 32 bit or 16 bit or else I have to add a specifier which I was shown how to do by the same person on Reddit.

However, this is still reencoding whenever you add a filter.


来源: stackexchange

问:
Getting the bit rate of a externally loaded mp3 in the flashplayer
does anyone know if this is possible?

much appreciated,

答:
Using the native flash sound class, you can read the id3 metadata property of the sound object, however this depends on the software that encoded the mp3 putting the encoding information in the metadata. there's nothing inherent to the mp3 itself that reports this to the sound class, and the metadata is often missing or unreliable.

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#id3

alternatively there's this 3rd party utility for reading actual mp3 header information, which is much more accurate.

http://code.google.com/p/mp3infoutil/

ContentLicense: CC BY-SA 3.0


问:
Allow anonymouos access to healthcheck endpoint when authentication fallback policy is set in ASP.NET Core 3
asp.net core 3 allows to set FallbackPolicy to make the endpoints secure by default:

            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });
```

<p>It is a great feature, but I have a <strong>HealthCheck</strong> endpoint too, that requires Authorization now.</p>

<pre class="lang-cs prettyprint-override"><code>            services.AddHealthChecks();
            [...]
            app.UseEndpoints(endpoints => {
                endpoints.MapHealthChecks("/health");
                endpoints.MapControllers();
            });
</code>```

How do I allow anonymous access to the HealthCheck endpoint (NO authentication or authorization)?

答:
I ran into exactly the same issue so I hope this helps as a more satisfactory way of achieving:</p>

```<code>        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute().RequireAuthorization();

            endpoints.MapHealthChecks("/health").WithMetadata(new AllowAnonymousAttribute());

        });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
asp.net core 3 allows to set FallbackPolicy to make the endpoints secure by default:

            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });

It is a great feature, but I have a HealthCheck endpoint too, that requires Authorization now.

            services.AddHealthChecks();
            [...]
            app.UseEndpoints(endpoints => {
                endpoints.MapHealthChecks("/health");
                endpoints.MapControllers();
            });

How do I allow anonymous access to the HealthCheck endpoint (NO authentication or authorization)?

Body:
I ran into exactly the same issue so I hope this helps as a more satisfactory way of achieving:

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute().RequireAuthorization();

            endpoints.MapHealthChecks("/health").WithMetadata(new AllowAnonymousAttribute());

        });


问:
elif <= invalid syntax?
i am currently working on a calculator using pandas, and to determine a variable I have used a nested if statement. But unfortunately, I get an invalid syntax error from the below code.

```<code>    if net_option == 'Y':
        if age <= 30:
            desired_net = 0.15
        elif age >= 31 and <= 60:
            desired_net = 0.12
        elif age >= 61 and <= 90:
            desired_net = 0.11
        elif age >= 91 and <= 140:
            desired_net = 0.10
        elif age >= 141 and <= 180:
            desired_net = 0.09
        elif age >= 181 and <= 245:
            desired_net = 0.08
        elif age >= 246 and <= 270:
            desired_net = 0.07
        elif age >= 271 and <= 365:
            desired_net = 0.6
        elif age >= 366 and <= 500:
            desired_net = 0.3
        elif: age >= 501 and <= 700:
            desired_net = 0.0
        elif age > 700:
            desired_net = -0.1
        else:
            desired_net = 0.1
    else:
        desired_net = desired_net
</code>```

Error message:

```<code>elif age >= 31 and <= 60:
                    ^
SyntaxError: invalid syntax
</code>```

I think I am missing something here as I am pretty sure that <= is a valid syntax.

Has anyone got an idea what may be wrong? Let me know if you would like to see more lines.

答:
Or, if you use Numpy, you could make your code much more simple and functionalize the logic like this:</p>

```<code>def get_desired_net(age):
    desired_net = {0:0.15, 31:0.12, 61:0.11, 91:0.10, 141:0.09, 181:0.08, 246:0.07, 271:0.06, 366:0.03, 501:0.00, 701:-0.01}

    keys_array = np.array(list(desired_net.keys()))

    max_age = max(keys_array[keys_array <= age])

    return desired_net[max_age]

>>> get_desired_net(15)
0.15
>>> get_desired_net(30)
0.15
>>> get_desired_net(31)
0.12
>>> get_desired_net(700)
0.0
>>> get_desired_net(701)
-0.01
</code>```

Title: elif <= invalid syntax?

Body:
i am currently working on a calculator using pandas, and to determine a variable I have used a nested if statement. But unfortunately, I get an invalid syntax error from the below code.

    if net_option == 'Y':
        if age <= 30:
            desired_net = 0.15
        elif age >= 31 and <= 60:
            desired_net = 0.12
        elif age >= 61 and <= 90:
            desired_net = 0.11
        elif age >= 91 and <= 140:
            desired_net = 0.10
        elif age >= 141 and <= 180:
            desired_net = 0.09
        elif age >= 181 and <= 245:
            desired_net = 0.08
        elif age >= 246 and <= 270:
            desired_net = 0.07
        elif age >= 271 and <= 365:
            desired_net = 0.6
        elif age >= 366 and <= 500:
            desired_net = 0.3
        elif: age >= 501 and <= 700:
            desired_net = 0.0
        elif age > 700:
            desired_net = -0.1
        else:
            desired_net = 0.1
    else:
        desired_net = desired_net

Error message:

elif age >= 31 and <= 60:
                    ^
SyntaxError: invalid syntax

I think I am missing something here as I am pretty sure that <= is a valid syntax.

Has anyone got an idea what may be wrong? Let me know if you would like to see more lines.

Body:
Or, if you use Numpy, you could make your code much more simple and functionalize the logic like this:

def get_desired_net(age):
    desired_net = {0:0.15, 31:0.12, 61:0.11, 91:0.10, 141:0.09, 181:0.08, 246:0.07, 271:0.06, 366:0.03, 501:0.00, 701:-0.01}

    keys_array = np.array(list(desired_net.keys()))

    max_age = max(keys_array[keys_array <= age])

    return desired_net[max_age]

>>> get_desired_net(15)
0.15
>>> get_desired_net(30)
0.15
>>> get_desired_net(31)
0.12
>>> get_desired_net(700)
0.0
>>> get_desired_net(701)
-0.01


问:
Customize attribute on type to expect methods marked with another attribute
I'm trying to create a custom attribute on a type that expects some properties inside this type to be marked with another attribute, similar to how it is done with ServiceContract in WCF:

[ServiceContract]
public interface ITestServiceContract
{
    [OperationContract]
    void SomeOperation();
}
```

<p>If no method in a <code>ServiceContract</code> is marked with the <code>OperationContract</code> attribute, the following warning is shown:</p>

<blockquote>
  <p>Interface 'ITestServiceContract' is marked as ServiceContract but doesn't contain any operation contracts</p>
</blockquote>

<p>When looking at the implementation of the <code>ServiceContract</code> I can't see where this would be defined:</p>

<pre class="lang-cs prettyprint-override"><code>[AttributeUsage(ServiceModelAttributeTargets.ServiceContract, Inherited = false, AllowMultiple = false)]
public sealed class ServiceContractAttribute : Attribute
{
    ...
}
</code>```

ServiceModelAttributeTargets.ServiceContract is defined externally:

public const AttributeTargets ServiceContract = AttributeTargets.Interface | AttributeTargets.Class;
```

Is there any way for me to define an attribute like this?

答:
You usually don't define that kind of logic in the attribute itself. The attribute usually just "sits" there and contains some data. You will evalutate such constraints, when you retrieve the attribute at a later time.

The emit a warning message, when such a constraint isn't met, you can implement a custom analyzer, that you'll ship along. You can start here to learn how to implement such an analyzer.

Body:
I'm trying to create a custom attribute on a type that expects some properties inside this type to be marked with another attribute, similar to how it is done with ServiceContract in WCF:

[ServiceContract]
public interface ITestServiceContract
{
    [OperationContract]
    void SomeOperation();
}

If no method in a ServiceContract is marked with the OperationContract attribute, the following warning is shown:

Interface 'ITestServiceContract' is marked as ServiceContract but doesn't contain any operation contracts

When looking at the implementation of the ServiceContract I can't see where this would be defined:

[AttributeUsage(ServiceModelAttributeTargets.ServiceContract, Inherited = false, AllowMultiple = false)]
public sealed class ServiceContractAttribute : Attribute
{
    ...
}

ServiceModelAttributeTargets.ServiceContract is defined externally:

public const AttributeTargets ServiceContract = AttributeTargets.Interface | AttributeTargets.Class;

Is there any way for me to define an attribute like this?


问:
How to add filter row inside material table?
I'm using angular material table and I try to use filter option. In documentation I find filter example but for my case I need to add textInputs after each headers. How can I do it ?
My example

```<code><table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Id Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID</th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</code>```

I need table like this.

答:
filterPredicate: ((data: T, filter: string) => boolean)

https://stackblitz.com/edit/stackover-flow-answer-02

Body:
I'm using angular material table and I try to use filter option. In documentation I find filter example but for my case I need to add textInputs after each headers. How can I do it ?
My example

  <ng-container matColumnDef="id">
     ID
     {{element.id}}
  </ng-container>

  <ng-container matColumnDef="name">
     Name
     {{element.name}}
  </ng-container>

I need table like this.


问:
Selected value on a DropDownList inside of a repeater
I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..

```<code>private void PhysicianSource()
{
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}
</code>```

asp.net

```<code><asp:Repeater ID="rptrPatientList" runat="server" >
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td class="style2">
            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>
            </td>

            </td>
        </tr>
</code>```

nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..

答:
Hi Ian Ace its better to modify your code a little bit

```<code> <asp:Repeater ID="rptProductList" runat="server" OnItemDataBound="rptProductList_ItemDataBound">
 <ItemTemplate>
<asp:DropDownList runat="server" ID="MyRepeater" AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" >
</asp:DropDownList>
 </ItemTemplate>
 </asp:Repeater>
</code>```

Now the code behind should be

```<code>  protected void Page_Load(object sender, EventArgs e)
  {
     if (!IsPostBack)
    {
       fillRepeater();
    }
  }

}
protected void rptProductList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DropDownList MyDropDown= (DropDownList)e.Item.FindControl("MyRepeater");
        if (MyDropDown!= null)
        {
           MyDropDown.DataSource =   fillDropDown(MyDropDown);
            MyDropDown.DataBind();
        }
    }
}

 private DataSet fillDropDown(DropDownList dropDown)
    {
     // get  your collection and return.
    }

protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList MyDropDown= (DropDownList)sender;
    string item = MyDropDown.SelectedValue;
}
</code>```

hope the above example helps.

Body:
I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..

private void PhysicianSource()
{
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}

asp.net

<asp:Repeater ID="rptrPatientList" runat="server" >
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>

            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>

nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..

Body:
Hi Ian Ace its better to modify your code a little bit

 <asp:Repeater ID="rptProductList" runat="server" OnItemDataBound="rptProductList_ItemDataBound">
 <ItemTemplate>
<asp:DropDownList runat="server" ID="MyRepeater" AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" >
</asp:DropDownList>
 </ItemTemplate>
 </asp:Repeater>

Now the code behind should be

  protected void Page_Load(object sender, EventArgs e)
  {
     if (!IsPostBack)
    {
       fillRepeater();
    }
  }

}
protected void rptProductList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DropDownList MyDropDown= (DropDownList)e.Item.FindControl("MyRepeater");
        if (MyDropDown!= null)
        {
           MyDropDown.DataSource =   fillDropDown(MyDropDown);
            MyDropDown.DataBind();
        }
    }
}

 private DataSet fillDropDown(DropDownList dropDown)
    {
     // get  your collection and return.
    }

protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList MyDropDown= (DropDownList)sender;
    string item = MyDropDown.SelectedValue;
}

hope the above example helps.


问:
Android Studio use setOnTouchListener after changing layout
I like to swipe right, left to switch the layout of my Activity. But after switching the layout once the setOnTouchListener stop working. What is my fault?

My Activity:

```<code>import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    static Fragment fragment;
private int pagenumber;
private ConstraintLayout cl;
    private View factory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.instruction_1);

        cl = findViewById(R.id.layout);
        pagenumber= 0;

        cl.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

            public void onSwipeRight() {
                if (pagenumber != 0)
                    pagenumber = pagenumber - 1;
                if(pagenumber==0){
                    setContentView(R.layout.instruction_1);
                    factory = getLayoutInflater().inflate(R.layout.instruction_1, null);

                    cl = factory.findViewById(R.id.layout);
                }
              else if(pagenumber==1){
                    setContentView(R.layout.instruction_2);
                    factory = getLayoutInflater().inflate(R.layout.instruction_2, null);
                    cl = factory.findViewById(R.id.layout);
              }

            }
            public void onSwipeLeft() {
                if(pagenumber<2) {
                    pagenumber = pagenumber + 1;

                     if (pagenumber==1){
                         setContentView(R.layout.instruction_2);
                         factory = getLayoutInflater().inflate(R.layout.instruction_2, null);
                         cl = factory.findViewById(R.id.layout);
                    }
                    else if (pagenumber==2){
                         setContentView(R.layout.instruction_3);
                         factory = getLayoutInflater().inflate(R.layout.instruction_3, null);
                         cl = factory.findViewById(R.id.layout);
                    }
                }

            }

        });

    }
}
</code>```

答:
Why the app is not working after first swipe is bcz when you swipe once you are replacing the layout file with another when you still have reference to old Constrained layout which is no more now.

You are trying to implement the behavior of Fragments

You should not be replacing the layout file completely, instead create a Layout inside the xml file and replace it Or just use ViewPager.

I think you are looking for something like this.
Try it

```<code> public class MainActivity extends AppCompatActivity {

static Fragment fragment;
private int pagenumber;
private ConstraintLayout cl;
private View factory;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.instruction_1);

    cl = findViewById(R.id.layout);
    pagenumber = 0;

    cl.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

        public void onSwipeRight() {
            if (pagenumber == 0) {
                setContentView(R.layout.instruction_1);
                pagenumber = 1;
            } else if (pagenumber == 1) {
                setContentView(R.layout.instruction_2);
                pagenumber = 2;
            } else if (pagenumber == 2) {
                setContentView(R.layout.instruction_3);
                pagenumber = 3;
            }
        }

        public void onSwipeLeft() {
           if (pagenumber == 1) {
                setContentView(R.layout.instruction_0);
                pagenumber = 0;
            } else if (pagenumber == 2) {
                setContentView(R.layout.instruction_1);
                pagenumber = 1;
            }else if (pagenumber == 3) {
                setContentView(R.layout.instruction_2);
                pagenumber = 2;
            }

        }
    });
}
}
</code>```

Body:
I like to swipe right, left to switch the layout of my Activity. But after switching the layout once the setOnTouchListener stop working. What is my fault?

My Activity:

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    static Fragment fragment;
private int pagenumber;
private ConstraintLayout cl;
    private View factory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.instruction_1);

        cl = findViewById(R.id.layout);
        pagenumber= 0;

        cl.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

            public void onSwipeRight() {
                if (pagenumber != 0)
                    pagenumber = pagenumber - 1;
                if(pagenumber==0){
                    setContentView(R.layout.instruction_1);
                    factory = getLayoutInflater().inflate(R.layout.instruction_1, null);

                    cl = factory.findViewById(R.id.layout);
                }
              else if(pagenumber==1){
                    setContentView(R.layout.instruction_2);
                    factory = getLayoutInflater().inflate(R.layout.instruction_2, null);
                    cl = factory.findViewById(R.id.layout);
              }

            }
            public void onSwipeLeft() {
                if(pagenumber<2) {
                    pagenumber = pagenumber + 1;

                     if (pagenumber==1){
                         setContentView(R.layout.instruction_2);
                         factory = getLayoutInflater().inflate(R.layout.instruction_2, null);
                         cl = factory.findViewById(R.id.layout);
                    }
                    else if (pagenumber==2){
                         setContentView(R.layout.instruction_3);
                         factory = getLayoutInflater().inflate(R.layout.instruction_3, null);
                         cl = factory.findViewById(R.id.layout);
                    }
                }

            }

        });

    }
}

Body:
Why the app is not working after first swipe is bcz when you swipe once you are replacing the layout file with another when you still have reference to old Constrained layout which is no more now.

You are trying to implement the behavior of Fragments

You should not be replacing the layout file completely, instead create a Layout inside the xml file and replace it Or just use ViewPager.

I think you are looking for something like this.
Try it

 public class MainActivity extends AppCompatActivity {

static Fragment fragment;
private int pagenumber;
private ConstraintLayout cl;
private View factory;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.instruction_1);

    cl = findViewById(R.id.layout);
    pagenumber = 0;

    cl.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

        public void onSwipeRight() {
            if (pagenumber == 0) {
                setContentView(R.layout.instruction_1);
                pagenumber = 1;
            } else if (pagenumber == 1) {
                setContentView(R.layout.instruction_2);
                pagenumber = 2;
            } else if (pagenumber == 2) {
                setContentView(R.layout.instruction_3);
                pagenumber = 3;
            }
        }

        public void onSwipeLeft() {
           if (pagenumber == 1) {
                setContentView(R.layout.instruction_0);
                pagenumber = 0;
            } else if (pagenumber == 2) {
                setContentView(R.layout.instruction_1);
                pagenumber = 1;
            }else if (pagenumber == 3) {
                setContentView(R.layout.instruction_2);
                pagenumber = 2;
            }

        }
    });
}
}


问:
MySQL SELECT IFNULL then compare it numerically with other column
I've tried numerous methods to translate NULL to the number 0 upon selection:

```<code>SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IF(s.paid_amount IS NOT NULL, s.paid_amount,0.00) AS paid_amount,
  (ss.amount-s.paid_amount)
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)
</code>```

I've used IFNULL but that doesn't turn the 0 into any numeric at all hence the selection didn't even list those with NULL values. Is there a way at all to turn NULL values into numerical upon selection and compare it against other columns numerically?

BTW .. down here is the create table statements for both tables.

f_salary_staff

```<code>CREATE TABLE `f_salary_staff` (  `id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `date_enter` date DEFAULT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `last_activated` datetime DEFAULT NULL,  `last_inactivated` datetime DEFAULT NULL,  `status` varchar(16) DEFAULT NULL,  PRIMARY KEY (`id`), KEY `store_id` (`store_id`),  KEY `user_id` (`user_id`),  CONSTRAINT `f_salary_staff_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,  CONSTRAINT `f_salary_staff_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )
</code>```

then f_salary

```<code>CREATE TABLE `f_salary` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `staff_id` int(11) NOT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `note` tinytext,  `ref_date` date DEFAULT NULL,  `month_year` date DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `approved` datetime DEFAULT NULL,  `approved_by` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `staff_id` (`staff_id`),  CONSTRAINT `f_salary_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `f_salary_staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )
</code>```

hope this helps those who needs to understand the table structure

答:
Thank you to forpas and Gosfly .. apparently COALESCE or IFNULL or even IF cannot alter the NULL to anything else other than NULL or not NOT NULL .. the result is only for show but not the real value of it .. so I've changed the statement to such instead

```<code>SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IFNULL(s.paid_amount,0.00) AS paid_amount,
  IF(s.paid_amount IS NULL,ss.amount,ss.amount-s.paid_amount) AS unpaid_amount
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)
WHERE ss.amount != s.paid_amount OR s.paid_amount IS NULL
</code>```

thank you all!

Body:
I've tried numerous methods to translate NULL to the number 0 upon selection:

SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IF(s.paid_amount IS NOT NULL, s.paid_amount,0.00) AS paid_amount,
  (ss.amount-s.paid_amount)
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)

I've used IFNULL but that doesn't turn the 0 into any numeric at all hence the selection didn't even list those with NULL values. Is there a way at all to turn NULL values into numerical upon selection and compare it against other columns numerically?

BTW .. down here is the create table statements for both tables.

f_salary_staff

CREATE TABLE `f_salary_staff` (  `id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `date_enter` date DEFAULT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `last_activated` datetime DEFAULT NULL,  `last_inactivated` datetime DEFAULT NULL,  `status` varchar(16) DEFAULT NULL,  PRIMARY KEY (`id`), KEY `store_id` (`store_id`),  KEY `user_id` (`user_id`),  CONSTRAINT `f_salary_staff_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,  CONSTRAINT `f_salary_staff_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )

then f_salary

CREATE TABLE `f_salary` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `staff_id` int(11) NOT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `note` tinytext,  `ref_date` date DEFAULT NULL,  `month_year` date DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `approved` datetime DEFAULT NULL,  `approved_by` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `staff_id` (`staff_id`),  CONSTRAINT `f_salary_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `f_salary_staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )

hope this helps those who needs to understand the table structure

Body:
Thank you to forpas and Gosfly .. apparently COALESCE or IFNULL or even IF cannot alter the NULL to anything else other than NULL or not NOT NULL .. the result is only for show but not the real value of it .. so I've changed the statement to such instead

SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IFNULL(s.paid_amount,0.00) AS paid_amount,
  IF(s.paid_amount IS NULL,ss.amount,ss.amount-s.paid_amount) AS unpaid_amount
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)
WHERE ss.amount != s.paid_amount OR s.paid_amount IS NULL

thank you all!


问:
How to remove orientation from jQuery datepicker
This is my jQuery code

```<code><input type="text" name="assign_date" readonly class="form-control datepickermin" id="assign_date" required>
</code>```

$('.datepickermin').datepicker({
  orientation: "auto",
  keyboardNavigation: false,
  forceParse: false,
  autoclose: true,
  startDate: new Date('2020-2-12'),
  endDate: new Date('2020-2-15'),
  dateFormat: 'dd-mm-yy',
});
```
<p><strong>This is Image</strong></p>
<p><img src="https://i.stack.imgur.com/IrrQO.png" alt="enter link description here" /></p>
<p><strong>How to remove orientation from jQuery datepicker?</strong></p>
```             <option value="Pending" data-status="Pending" data-id ="'.$q->id.'"';
             if($q->status == 'Pending'): $return .= 'selected'; endif; $return .='>Pending</option>
             <option value="Completed" data-status="Completed" data-id ="'.$q->id.'"';
             if($q->status == 'Completed'): $return .= 'selected'; endif; $return .='>Completed</option>
             <option value="Hold" data-status="Hold" data-id ="'.$q->id.'"';
             if($q->status == 'Hold'): $return .= 'selected'; endif; $return .='>Hold</option>
             <option value="Prospect" data-status="Prospect" data-id ="'.$q->id.'"';
             if($q->status == 'Prospect'): $return .= 'selected'; endif; $return .='>Prospect</option>
```

答:
Try this

```<code>.datetimepicker:before, .datetimepicker:after { display: none;}
</code>```

Body:
This is my jQuery code

<input type="text" name="assign_date" readonly class="form-control datepickermin" id="assign_date" required>

$('.datepickermin').datepicker({
  orientation: "auto",
  keyboardNavigation: false,
  forceParse: false,
  autoclose: true,
  startDate: new Date('2020-2-12'),
  endDate: new Date('2020-2-15'),
  dateFormat: 'dd-mm-yy',
});

This is Image

How to remove orientation from jQuery datepicker?

             <option value="Pending" data-status="Pending" data-id ="'.$q->id.'"';
             if($q->status == 'Pending'): $return .= 'selected'; endif; $return .='>Pending</option>
             <option value="Completed" data-status="Completed" data-id ="'.$q->id.'"';
             if($q->status == 'Completed'): $return .= 'selected'; endif; $return .='>Completed</option>
             <option value="Hold" data-status="Hold" data-id ="'.$q->id.'"';
             if($q->status == 'Hold'): $return .= 'selected'; endif; $return .='>Hold</option>
             <option value="Prospect" data-status="Prospect" data-id ="'.$q->id.'"';
             if($q->status == 'Prospect'): $return .= 'selected'; endif; $return .='>Prospect</option>

Body:
Try this

.datetimepicker:before, .datetimepicker:after { display: none;}


问:
Strange result when speed testing Math() in Firefox
I got a strange result from a test I did (Firefox specific), and I would like to know more about how/why this is the result.

A typical result looks like this (10 million list items) (I have run it several times manually, I didn't feel like making a full on "statistics module").

Results for Firefox 72.0.2 (64-bit) on Windows 7

```<code>itteration: 40 ms - timer stopped
__rounding: 14 ms - timer stopped
______ceil: 16 ms - timer stopped
_____floor: 15 ms - timer stopped
</code>```

What I find most strange is the itteration test.

The "effective" itteration code looks like this: arrNumbers[index] = arrNumbers[index]; and this code is part of ALL the tests, but the other parts have a Math function wraped around the right part.

So it seams like the itteration test should dictate the speed for all other tests, I expected this part to be fastest, not slowest.

First I thought this was a "problem" with floating point numbers possibly being slower to process than integers, so I tried to just assign a 1 (int) so every function works on equal data, but the result is still the same.

Code:
(will probably not run here since I'm using console.time() I guess. But you can just copy it as is, to a text file & change the file extension to .html & open it with Firefox, press F12 to open the inspection tool & switch to the Console tab if needed).

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <title>Title</title>

```
</div>
</div>
</p>

<hr>

<p><strong>Other results:</strong></p>

<p><strong>Results for Firefox 72.0.2 (64-bit)</strong> (Same as above, just for completeness & ease of comparison)</p>

```itteration: 40 ms - timer stopped
__rounding: 14 ms - timer stopped
______ceil: 16 ms - timer stopped
_____floor: 15 ms - timer stopped
```

<p><strong>Firefox again,</strong> but now assigned 1.5 (<code>float</code>) as input data (instead of <code>int</code>, as above)
(Math.random() gives a similar result)</p>

```itteration: 67 ms - timer stopped
__rounding: 33 ms - timer stopped
______ceil: 34 ms - timer stopped
_____floor: 32 ms - timer stopped
```

<p><strong>Results for Google Chrome Version 80.0.3987.106 (64 bit)</strong></p>

```itteration: 11.7060546875   ms
__rounding: 12.194091796875 ms
______ceil: 11.73681640625  ms
_____floor: 11.551025390625 ms
```

<p><strong>Results for Internet Explorer 11.0.9600..... Update: 11.0</strong></p>

```itteration:  37,3 ms
__rounding: 203,5 ms
______ceil:  85,9 ms
_____floor:  85,7 ms
```

答:
It's actually the order you are running the tests, I believe.

First of all, the results aren't that dramatic for me. In Chrome they're almost identical, and in Firefox I see a small--but consistent--increase in time on your iteration test. Usually it's around 5-15ms longer, but it's consistent, so I'll give it to you that it's real.

If you add a Math.floor() to the iteration test, you'll still see higher numbers here.

But if you move the iteration test to the end, like this:

```<code>let arrNumbers = makeNrArray(loopSize);
testRoundingSpeed(arrNumbers)

arrNumbers = makeNrArray(loopSize);
testCeilingSpeed(arrNumbers);

arrNumbers = makeNrArray(loopSize);
testFlooringSpeed(arrNumbers);

arrNumbers = makeNrArray(loopSize);
testItterationSpeed(arrNumbers);
</code>```

Then you'll see the testItterationSpeed result go down to the range of the others, while the testRoundingSpeed will go up.

I suspect it has something to do with the allocation of memory, since the subsequent results use the same variable (well, the same let). I don't know the details. Regardless, it is less about what you are doing and more about when.

Body:
I got a strange result from a test I did (Firefox specific), and I would like to know more about how/why this is the result.

A typical result looks like this (10 million list items) (I have run it several times manually, I didn't feel like making a full on "statistics module").

Results for Firefox 72.0.2 (64-bit) on Windows 7

itteration: 40 ms - timer stopped
__rounding: 14 ms - timer stopped
______ceil: 16 ms - timer stopped
_____floor: 15 ms - timer stopped

What I find most strange is the itteration test.

The "effective" itteration code looks like this: arrNumbers[index] = arrNumbers[index]; and this code is part of ALL the tests, but the other parts have a Math function wraped around the right part.

So it seams like the itteration test should dictate the speed for all other tests, I expected this part to be fastest, not slowest.

First I thought this was a "problem" with floating point numbers possibly being slower to process than integers, so I tried to just assign a 1 (int) so every function works on equal data, but the result is still the same.

Code:
(will probably not run here since I'm using console.time() I guess. But you can just copy it as is, to a text file & change the file extension to .html & open it with Firefox, press F12 to open the inspection tool & switch to the Console tab if needed).

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <title>Title</title>

Other results:

Results for Firefox 72.0.2 (64-bit) (Same as above, just for completeness & ease of comparison)

itteration: 40 ms - timer stopped
__rounding: 14 ms - timer stopped
______ceil: 16 ms - timer stopped
_____floor: 15 ms - timer stopped

Firefox again, but now assigned 1.5 (float) as input data (instead of int, as above)
(Math.random() gives a similar result)

itteration: 67 ms - timer stopped
__rounding: 33 ms - timer stopped
______ceil: 34 ms - timer stopped
_____floor: 32 ms - timer stopped

Results for Google Chrome Version 80.0.3987.106 (64 bit)

itteration: 11.7060546875   ms
__rounding: 12.194091796875 ms
______ceil: 11.73681640625  ms
_____floor: 11.551025390625 ms

Results for Internet Explorer 11.0.9600..... Update: 11.0

itteration:  37,3 ms
__rounding: 203,5 ms
______ceil:  85,9 ms
_____floor:  85,7 ms

Body:
It's actually the order you are running the tests, I believe.

First of all, the results aren't that dramatic for me. In Chrome they're almost identical, and in Firefox I see a small--but consistent--increase in time on your iteration test. Usually it's around 5-15ms longer, but it's consistent, so I'll give it to you that it's real.

If you add a Math.floor() to the iteration test, you'll still see higher numbers here.

But if you move the iteration test to the end, like this:

let arrNumbers = makeNrArray(loopSize);
testRoundingSpeed(arrNumbers)

arrNumbers = makeNrArray(loopSize);
testCeilingSpeed(arrNumbers);

arrNumbers = makeNrArray(loopSize);
testFlooringSpeed(arrNumbers);

arrNumbers = makeNrArray(loopSize);
testItterationSpeed(arrNumbers);

Then you'll see the testItterationSpeed result go down to the range of the others, while the testRoundingSpeed will go up.

I suspect it has something to do with the allocation of memory, since the subsequent results use the same variable (well, the same let). I don't know the details. Regardless, it is less about what you are doing and more about when.


问:
how to pass id of a multiple dropdown inside the $.each function

function fieldsFilter(flag,value,chkClass)
 {
  var checkedfields = [];

  $.each($("#rep_id option:selected"), function(){
            checkedfields.push($(this).val());
        });
  $('#'+flag+'Filters').val(checkedfields);
 }```

Here i have a javascript function. Here i want to pass the chkClass in the place of rep_id in $.each(). i
 am getting confusion.can one please help me

答:
Try this:

function fieldsFilter(flag,value,chkClass) {
    var checkedfields = [];
    $.each($(`#${rep_id} option:selected`), function(){
        checkedfields.push($(this).val());
    });
    $('#'+flag+'Filters').val(checkedfields);
}
```

Body:
function fieldsFilter(flag,value,chkClass)
 {
  var checkedfields = [];

  $.each($("#rep_id option:selected"), function(){
            checkedfields.push($(this).val());
        });
  $('#'+flag+'Filters').val(checkedfields);
 }

Here i have a javascript function. Here i want to pass the chkClass in the place of rep_id in $.each(). i
 am getting confusion.can one please help me


问:
Post to Google Hangouts with Webhook and GScript
Right now we use a Slack webhook to send important data from an email account into our Slack channel. Management wants us to switch to Hangouts and retain similar functionality with automated alerts. I tried adapting my slack gscript with no success. I even tried dumbing down the script as much as possible to eliminate potential errors. I want to use a webhook and not an API because it should be easier. I only need async messaging without the bot replying back.

I have used their python quickstart (which works well!), but my script is getting content from an email and then sending it to the webhook. GScript makes this easy (at least it was easy with Slack).

No matter what I try (I even copied Wesley's example exactly with no success)

Maybe I am doing something wrong, but at this point I can't figure out what. Any help would be much appreciated!

Omitting all the extra stuff about getting details from an email thread, as I can't even get the GScript to post a "Hello World" (only python)

```<code>var data = {
  text: "hello"
};

var payload = JSON.stringify(data);

var options = {
  method: "POST",
  ContentType: "application/json; charset=UTF-8",
  payload: payload,
  muteHttpExceptions: true
};

var webhook = 'https://chat.googleapis.com/v1/spaces/{space}/messages?key={key}&token={token}';
var response = UrlFetchApp.fetch(webhook, options);
Logger.log(response.getContentText());
</code>```

```<code>[20-02-14 12:15:10:615 CST] {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"{\"text\":\"hello\"}\": Cannot bind query parameter. Field '{\"text\":\"hello\"}' could not be found in request message.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"{\"text\":\"hello\"}\": Cannot bind query parameter. Field '{\"text\":\"hello\"}' could not be found in request message."
          }
        ]
      }
    ]
  }
}
</code>```

答:
In order to be able to have the options sent properly, you should be using contentType instead of ContentType.

After changing the parameter you can see that the message is sent accordingly.

You can also check this example for seeing the exact names for the parameters for the options you send the for the request.

```<code>UrlFetchApp.fetch(url, {
    method: 'post',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify(message),
  });
</code>```

Reference

Hangouts Chat API - Async Messages

Body:
Right now we use a Slack webhook to send important data from an email account into our Slack channel. Management wants us to switch to Hangouts and retain similar functionality with automated alerts. I tried adapting my slack gscript with no success. I even tried dumbing down the script as much as possible to eliminate potential errors. I want to use a webhook and not an API because it should be easier. I only need async messaging without the bot replying back.

I have used their python quickstart (which works well!), but my script is getting content from an email and then sending it to the webhook. GScript makes this easy (at least it was easy with Slack).

No matter what I try (I even copied Wesley's example exactly with no success)

Maybe I am doing something wrong, but at this point I can't figure out what. Any help would be much appreciated!

Omitting all the extra stuff about getting details from an email thread, as I can't even get the GScript to post a "Hello World" (only python)

var data = {
  text: "hello"
};

var payload = JSON.stringify(data);

var options = {
  method: "POST",
  ContentType: "application/json; charset=UTF-8",
  payload: payload,
  muteHttpExceptions: true
};

var webhook = 'https://chat.googleapis.com/v1/spaces/{space}/messages?key={key}&token={token}';
var response = UrlFetchApp.fetch(webhook, options);
Logger.log(response.getContentText());

[20-02-14 12:15:10:615 CST] {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"{\"text\":\"hello\"}\": Cannot bind query parameter. Field '{\"text\":\"hello\"}' could not be found in request message.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"{\"text\":\"hello\"}\": Cannot bind query parameter. Field '{\"text\":\"hello\"}' could not be found in request message."
          }
        ]
      }
    ]
  }
}

Body:
In order to be able to have the options sent properly, you should be using contentType instead of ContentType.

After changing the parameter you can see that the message is sent accordingly.

You can also check this example for seeing the exact names for the parameters for the options you send the for the request.

UrlFetchApp.fetch(url, {
    method: 'post',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify(message),
  });

Reference

Hangouts Chat API - Async Messages


问:
Hyperledger fabric NodeOUs not activated. Cannot tell apart identities
When I try to approve a chaincode package it throws a timeout error.
The peer logs show the following warnings. Even though I have config.yaml file in the MSP directory with NodeOUs enable to true, it says NodeOus not activated. Can anyone help me resolve this issue?  I use hyperledger fabric 2.0 binaries.
identity 0 does not satisfy principal: The identity is not a [PEER] under this MSP [org1MSP]: NodeOUs not activated. Cannot tell apart identities.

WARN 1012b Peer {"CN":"peer2-org1","Issuer-CN":"rca-org1.inuit.local","Issuer-L-ST-C":"[RM]-[]-[IT]","Issuer-OU":["fabric"],"L-ST-C":"[]-[]-[US]","MSP":"org1MSP","OU":["peer"]} isn't eligible for channel twoorgschannel : implicit policy evaluation failed - 0 sub-policies were satisfied, but this policy requires 1 of the 'Readers' sub-policies to be satisfied

答: This is my fault not to include policy definitions in the orderer system channel. So even  though I have enabled NodeOUs in MSPs and defined policies in configtx.yaml, I didn't include channel policies in the orderersystemchannel. So it throws the error mentioned in the question above.</p>


问:
Two Custom tool s for a single file?
I want to generate some code from my dbml(Linq to Sql) file,the dbml file is placed in many part of my project So I wrote a custom tool for this purpose

But the problem is that dbml already  has contained MSLinqToSQLGenerator custom tool ,

So do you know any way to set two custom tools for one file, If no, Let me know your idea about that

答:
You'd get proper control on the T4 if you include the LINQ to SQL T4 generator in your template's responsibility.

If I understood properly, you want to keep the default behavior of .dbml generator, but also add your own.

This seemed a bit "old", and I haven't personally used LINQ to SQL for some time, but I did use this as-is replacement of T4 generator, that produced the equivalent of the standard .dbml generator.

https://github.com/damieng/L2ST4

Not sure if that's up to date with VS 2010 version, but you can always compare the standard .dbml generated code and this T4 output and make proper changes to achieve identical outcome.

Of course you can simply have multiple different generators, and simply run them with "Transform All Templates", but based on your question, you'd want the generator to be attached to the file specific custom tool.

You might want to check out (unless its already familiar to you) also T4 Toolbox https://github.com/olegsych/T4Toolbox that adds "T4ScriptFileGenerator" custom tool to a file. It effectively runs the T4 code when the file changes.

Title: Two Custom tool s for a single file?


问:
jQuery add class based on parent URL
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.

However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?

Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"

Here is my jQuery:

```<code>var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
    if(jQuery(this).attr('href')=== cururl){
        jQuery(this).addClass("current-slider-menu");
    }
});
</code>```

EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.

答:
You're definitely on the right track.

You can grab the currentURL (before the anchor #):

```<code>const currentURL = window.location.href.split('#')[0];
</code>```

Then you can split the currentURL into its constituent folders:

```<code>const currentURLArray = currentURL.split('/');
</code>```

Then, separately, you can grab all the myLinks:

```<code>const myLinks = [...document.querySelectorAll('a.rs-layer')];
</code>```

And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:

```<code>for (myLink of myLinks) {

  if (myLink.href.split('/')[1] === currentURLArray[1]) {

    myLink.classList.add('current-slider-menu');
  }
}
</code>```

Complete Example:

```<code>const currentURL = window.location.href.split('#')[0];

const currentURLArray = currentURL.split('/');

const myLinks = [...document.querySelectorAll('a.rs-layer')];

for (myLink of myLinks) {

  if (myLink.href.split('/')[1] === currentURLArray[1]) {

    myLink.classList.add('current-slider-menu');
  }
}
</code>```

Title: jQuery add class based on parent URL

Body:
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.

However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?

Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"

Here is my jQuery:

var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
    if(jQuery(this).attr('href')=== cururl){
        jQuery(this).addClass("current-slider-menu");
    }
});

EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.

Body:
You're definitely on the right track.

You can grab the currentURL (before the anchor #):

const currentURL = window.location.href.split('#')[0];

Then you can split the currentURL into its constituent folders:

const currentURLArray = currentURL.split('/');

Then, separately, you can grab all the myLinks:

const myLinks = [...document.querySelectorAll('a.rs-layer')];

And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:

for (myLink of myLinks) {

  if (myLink.href.split('/')[1] === currentURLArray[1]) {

    myLink.classList.add('current-slider-menu');
  }
}

Complete Example:

const currentURL = window.location.href.split('#')[0];

const currentURLArray = currentURL.split('/');

const myLinks = [...document.querySelectorAll('a.rs-layer')];

for (myLink of myLinks) {

  if (myLink.href.split('/')[1] === currentURLArray[1]) {

    myLink.classList.add('current-slider-menu');
  }
}


问:
Firebase Tasks in Swift / iOS
I'm an android developer learning to write my app for iOS using swift. I'm unsure how to run multiple firebase (firestore and realtime database) write tasks asynchronous and return a completion handler. In android I use the Tasks API and have it written as follows:

```<code>Task<Void> firestoreTask = firestoreDB.getDocument("users/someId").update("name", "some name");

Task<Void> realtimeTask = realtimeDB.child("users/someId/name/").setValue("some name");

Tasks.whenAll(firestoreTask, realtimeTask).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // if both tasks are successful
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if at least one of the two task fails
            }
        });
</code>```

I can't seem to figure out how to write such a task in swift. Can someone please point me in the right direction? Thank you.

答: I think in iOS you have only closures.</p>

Title: Firebase Tasks in Swift / iOS

Body:
I'm an android developer learning to write my app for iOS using swift. I'm unsure how to run multiple firebase (firestore and realtime database) write tasks asynchronous and return a completion handler. In android I use the Tasks API and have it written as follows:

Task<Void> firestoreTask = firestoreDB.getDocument("users/someId").update("name", "some name");

Task<Void> realtimeTask = realtimeDB.child("users/someId/name/").setValue("some name");

Tasks.whenAll(firestoreTask, realtimeTask).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // if both tasks are successful
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if at least one of the two task fails
            }
        });

I can't seem to figure out how to write such a task in swift. Can someone please point me in the right direction? Thank you.

Body: I think in iOS you have only closures.


问:
Something like margin or padding except where background doesn't draw
Is there something that will do what margin does but without the background drawing in that area? For instance, when you give an element margin: 1em you get a 1em border of blank space around the element, but the background draws in that area. Is there something similar to that except where the background doesn't draw?

My problem is I'm trying to put something below three float: lefted divs and right now I can't get any spacing between that and the floated divs above it. They just abut directly against each other.

The div that is going below the float: lefted divs has the property clear: both. If there was something that made that div have space between it and that floated div above it then that would work too.

答:
Because the element is floated margin space won't always be properly respected. Use a margin/border hack where you simply set the element's color to the same color as your page background and its thickness to whatever you desire. Such as in the following post:

http://socialstreams.co/41/CSS_MarginBorder_Hack


问:
How to read .xhprof files?
I have .xhprof files generated from XHProf and UProfiler.

Tried using SugarCrm XHProf Viewer and UProfiler viewer, but both of them doesn't read .xhprof files.

Do I have to do any conversion to read this reports?

答:
I am maintaining XHProf since it is not maintained by Facebook anymore.

As part of the project, there is an xhprof_html sub-directory. If you can reach its index.php directly from a URL (maybe you will have to create a separate VirtualHost and/or putting it somewhere under your document root), then it should show you a list of profiles that have been generated (by default, it is in the temporary directory (/tmp?)).

Title: How to read .xhprof files?


问:
How to Handle 500 internal error while mapping JSON to POJO If one of attribute of POJO class is empty
Hi I am working on Rest API written in java and have come through the below doubt.

I have already written the code which takes post data and maps to pojo class and sends back the data in JSON form.

Correct Format:-

```<code>{
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}
</code>```

Output:

```<code>{
    "Pkid":"1",
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}
</code>```

But when I am passing empty value to one of the attribute I am getting 500 internal error can someone help me how to handle it and return the value in json format after handling it:

```<code>{
    "Name":,
    "Address":"Mumbai",
    "Age": 27
}
</code>```

Output:

```<code>500 Internal error
</code>```

答:
first of all, use a json validator. it seems that you have a missing comma.

https://jsonformatter.curiousconcept.com/

And also it is helpful to share corresponding code, and retrieved exception etc.

Body:
Hi I am working on Rest API written in java and have come through the below doubt.

I have already written the code which takes post data and maps to pojo class and sends back the data in JSON form.

Correct Format:-

{
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}

Output:

{
    "Pkid":"1",
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}

But when I am passing empty value to one of the attribute I am getting 500 internal error can someone help me how to handle it and return the value in json format after handling it:

{
    "Name":,
    "Address":"Mumbai",
    "Age": 27
}

Output:

500 Internal error


问:
Missing mysql2 gem Amazon Web Services EC2 error
When I try to open my site it gives me this error.

!!! Missing the mysql2 gem. Add it to your Gemfile: gem 'mysql2'

I have added it to my Gemfile, but still no avail.
And changed all my adapters to mysql2 in the database.yml

Running
Rails 3.0.7
Ruby 1.8.7 enterprise

答:
You may be getting this error because the latest mysql2 gem doesn't contain the ActiveRecord adaptor (they've excluded it because Rails 3.1 has it built into ActiveRecord).

You should require the old version of mysql2 in your gemfile:

```<code>gem 'mysql2', "~> 0.2.7"
</code>```

This is as per instructions in mysql2 README doc

Body:
You may be getting this error because the latest mysql2 gem doesn't contain the ActiveRecord adaptor (they've excluded it because Rails 3.1 has it built into ActiveRecord).

You should require the old version of mysql2 in your gemfile:

gem 'mysql2', "~> 0.2.7"

This is as per instructions in mysql2 README doc


问:
Subdomains not working after migration due to uppercase presence
During migration we moved subdomains from our previous SSL provider to LetsEncrypt for SSL certificate change. Some of the subdomains had uppercases in them, but during certificate generation, in LEtsEncrypt the subdomain can be created only in lowercase.(We even tried to create subdomain names with uppercase, but it didn't work) After the migration, the subdomains that had uppercases in them arent working if we point the newly generated Letsencrypt certificates but they are working with perfectly with the previous provider. Does anyone know how to solve this problem or even better know any way to generate the certificate name with uppercases in them?
Example
The subdomain names are Support.Example.com but the certificate can only be generated for support.example.com

答: DNS is case insensitive. So you wrongly define your hosts (presumably in apache) with upercase. Rename them to lower case and use Lets Encrypt certificates.</p>


问:
How do I implement RichTextEditor in Flash?
I'm looking at this example: and for the life of me I don't see how to utilize this in Flash.  I don't want to build a Flex app... I want to implement this object in my Flash code.  But I'm not having any luck importing mx.controls or getting an instance of this component. It's not in my component's library, either.  Is there some lib I'm missing? Or am I just attempting the impossible here?</p>

答:
Flex components/containers must be parented by other Flex components/containers.  Adding one to a regular Flash project won't function properly.

As for Rich Text Editors you have to either build one or look around.  It seems like there's a few non-Flex ones available.  Here's one I found: http://www.flashloaded.com/flashcomponents/flashtexteditor/


问:
How to use lambda if else in map() on list in python?
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

```<code>l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])
</code>```

it seems that it should work but its giving syntax error

What is the issue here?

答:
you are not allowed to use pass keyword in conditional expressions(ternary operator)

you can read more about conditional expressions in PEP308

So, if you want to use the map built-in function you have to pick an "else" value for the ternary operator, ex:

```<code>map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry'])
</code>```

or if you want to filter your list by the string "apple" you can use @Rakesh suggested solution by using the built-in function filter:

```<code>list(filter(lambda x : x == "apple", ['apple', 'banana', 'cherry']))
</code>```

Body:
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])

it seems that it should work but its giving syntax error

What is the issue here?

Body:
you are not allowed to use pass keyword in conditional expressions(ternary operator)

you can read more about conditional expressions in PEP308

So, if you want to use the map built-in function you have to pick an "else" value for the ternary operator, ex:

map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry'])

or if you want to filter your list by the string "apple" you can use @Rakesh suggested solution by using the built-in function filter:

list(filter(lambda x : x == "apple", ['apple', 'banana', 'cherry']))


问:
Are there any languages that are not written in c++, rust, or ada?
I am currently developing a programming language for which I am using golang as a primary programming language.

It doesn't seem much slower than python.
I just wanted to know that whether I am wasting my time writing language in go?
Has anyone already written any programming language keeping golang as base language?

I hear that the fastest languages are c, c++, rust, and ada. I also heard that go was fast, but not nearly as fast as c++. What (semi-popular) languages are written in go, or any other non-ultra fast programming language.

答:
you can check this book when writing a language based on Go: Writing An Interpreter In Go. It also has a sequel , Writing A Compiler In Go.

It shows the development of a toy language called monkey, and while monkey is not being used in production, the book does a good job of showing the fundamentals. You can read more about it on their website.

There is a particular language that is being developed by Alexander Medvednikov, which is vlang.
Vlang aims to be a production ready language, so also check it out. Vlang was initially developed in Go, but now it's compiler is in vlang, which is another example of bootstrapping.

If you count Domain specific languages, you can argue that Dockerfile format is also written in Go, as docker daemon is in Go, and it has to parse Dockerfile.

Well, Golang is also written in Golang. The language had a compiler in C until version 1.4, but they rewrote their compiler in Golang, compiled it with the old C compiler, and use their Golang compiler since the said version. That thing is called bootstrapping, and is a popular way when developing new languages.

If I'm right, the language that the compiler is written only affect the compile time of the language, and the runtime speed is affected by your optimizations on the compiler itself. (Assuming you have a compiled language).

For interpreted languages, which you seem to have, because you compare yours with python, Golang might be slower than C++, although keep in mind that this is the case if you can optimize both languages pretty well.( which is a hard thing to do)

I think, it's not a waste of time to develop a language in Go. It's easier to develop than C++ (again, my opinion) , thus you can iterate quickly while developing the semantics of your own language. If you end up requiring much more speed than Go can offer, good for you, that means your language is popular now, and has a stable syntax, you can think of rewriting it in Rust, or C. Until than, Go should be fine.


问:
How can I assign n number of column names into individual variables?
I have a mapping table that contains a list of SourceFields, TargetFields and FileNames.

```<code>SourceField TargetField Filename

A           1           test.xlsx
B           2           test.xlsx
C           3           test.xlsx
d           1           other.xlsx
e           2           other.xlsx
</code>```

I want to set a SourceField variable, based on the TargetField and FileName`

```<code>        DECLARE
            @FileName NVARCHAR(MAX)
            ,@sql1Target NVARCHAR(MAX)
            ,@sql2Target NVARCHAR(MAX)
        -------------------------------------------------------------------------------
            ,@sql1Source NVARCHAR(MAX)
            ,@sql2Source NVARCHAR(MAX)
        -------------------------------------------------------------------------------
            ,@sql1Transform NVARCHAR(MAX)
            ,@sql2Transform NVARCHAR(MAX)

        SET @FileName = 'other.xlsx'
        SET @sql1Target = '1'
        SET @sql2Target = '2'

        SET @sql1Transform =
            'SELECT
                @SourceField = SourceField
            FROM
                MAPPING_DIM
            WHERE
                TargetField = ''1'' and FileName = ' + ''''+ @FileName +''''
        ------------------------------------------------------------------------------------------------------------
        SET @sql2Transform =
                'SELECT
                    @SourceField = SourceField
                FROM
                    MAPPING_DIM
                WHERE
                    TargetField = ''2'' and FileName = ' + ''''+ @FileName +''''
</code>```

These statements when executed will return the SourceField based on the other two variables. I can then use these source variables to select from my FileName.

```<code>        EXECUTE sp_executesql @sql1Transform , N'@SourceField NVARCHAR (MAX) OUTPUT', @SourceField = @sql1Source OUTPUT
        EXECUTE sp_executesql @sql2Transform , N'@SourceField NVARCHAR (MAX) OUTPUT', @SourceField = @sql2Source OUTPUT
</code>```

I want to be able to do this for any table containing any number of columns. My problem at the moment is this code will only work as I have set my TargetVariables for when my FileName = 'other.xlsx'. If I was doing this for where the FileName = 'test.xlsx' then I would need to set my variable to include the third field.

Is there any way I can return my SourceFields based on my TargetFields and FileName name for 'n' number of columns in a table?

答:
This is too long for a comment.  I don't think there is a simple method to assign an arbitrary set of values to the results of a query.

I would actually suggest that you just set each value using a separate query:

```<code>select @a = TargetField
from mapping
where filename = @filename and sourcefield = 'A';

select @b = TargetField
from mapping
where filename = @filename and sourcefield = 'B';

select @c = TargetField
from mapping
where filename = @filename and sourcefield = 'C';
</code>```

If there are no corresponding rows, then the value will not be changed.  However, you could force the value to be NULL or some other value using aggregation:

```<code>select @a = max(TargetField)
from mapping
where filename = @filename and sourcefield = 'A';
</code>```

or:

```<code>select @a = coalesce(max(TargetField), '<default value>')
from mapping
where filename = @filename and sourcefield = 'A';
</code>```

Note:  This requires knowing all the possible values that could be set.  However, it does not require dynamic SQL.  And, if you are going to use the values, then you need to know the names of the variables in subsequent code anyway.

Body:
I have a mapping table that contains a list of SourceFields, TargetFields and FileNames.

SourceField TargetField Filename

A           1           test.xlsx
B           2           test.xlsx
C           3           test.xlsx
d           1           other.xlsx
e           2           other.xlsx

I want to set a SourceField variable, based on the TargetField and FileName`

        DECLARE
            @FileName NVARCHAR(MAX)
            ,@sql1Target NVARCHAR(MAX)
            ,@sql2Target NVARCHAR(MAX)
        -------------------------------------------------------------------------------
            ,@sql1Source NVARCHAR(MAX)
            ,@sql2Source NVARCHAR(MAX)
        -------------------------------------------------------------------------------
            ,@sql1Transform NVARCHAR(MAX)
            ,@sql2Transform NVARCHAR(MAX)

        SET @FileName = 'other.xlsx'
        SET @sql1Target = '1'
        SET @sql2Target = '2'

        SET @sql1Transform =
            'SELECT
                @SourceField = SourceField
            FROM
                MAPPING_DIM
            WHERE
                TargetField = ''1'' and FileName = ' + ''''+ @FileName +''''
        ------------------------------------------------------------------------------------------------------------
        SET @sql2Transform =
                'SELECT
                    @SourceField = SourceField
                FROM
                    MAPPING_DIM
                WHERE
                    TargetField = ''2'' and FileName = ' + ''''+ @FileName +''''

These statements when executed will return the SourceField based on the other two variables. I can then use these source variables to select from my FileName.

        EXECUTE sp_executesql @sql1Transform , N'@SourceField NVARCHAR (MAX) OUTPUT', @SourceField = @sql1Source OUTPUT
        EXECUTE sp_executesql @sql2Transform , N'@SourceField NVARCHAR (MAX) OUTPUT', @SourceField = @sql2Source OUTPUT

I want to be able to do this for any table containing any number of columns. My problem at the moment is this code will only work as I have set my TargetVariables for when my FileName = 'other.xlsx'. If I was doing this for where the FileName = 'test.xlsx' then I would need to set my variable to include the third field.

Is there any way I can return my SourceFields based on my TargetFields and FileName name for 'n' number of columns in a table?

Body:
This is too long for a comment.  I don't think there is a simple method to assign an arbitrary set of values to the results of a query.

I would actually suggest that you just set each value using a separate query:

select @a = TargetField
from mapping
where filename = @filename and sourcefield = 'A';

select @b = TargetField
from mapping
where filename = @filename and sourcefield = 'B';

select @c = TargetField
from mapping
where filename = @filename and sourcefield = 'C';

If there are no corresponding rows, then the value will not be changed.  However, you could force the value to be NULL or some other value using aggregation:

select @a = max(TargetField)
from mapping
where filename = @filename and sourcefield = 'A';

or:

select @a = coalesce(max(TargetField), '<default value>')
from mapping
where filename = @filename and sourcefield = 'A';

Note:  This requires knowing all the possible values that could be set.  However, it does not require dynamic SQL.  And, if you are going to use the values, then you need to know the names of the variables in subsequent code anyway.


问:
Randomly choose a file inside a folder using Hypothesis
I want to add tests using the Hypothesis library (already use in the software for testing).
For these tests, I have to use a set of txt files contained in a folder.
I need to randomly choose one of these files each time I run my tests.
How to do that using Hypothesis?

edit
Here basically how it would look like, to comply the templates of already existing tests.

```<code>@given(doc=)
def mytest(doc):

    # assert some stuff according to doc
    assert some_stuff
</code>```

答:
Static case

If files list is assumed to be "frozen" (no files will be deleted/added) then we can use os.listdir + hypohtesis.strategies.sampled_from like

import os

from hypothesis import strategies

directory_path = 'path/to/directory/with/txt/files'
txt_files_names = strategies.sampled_from(sorted(os.listdir(directory_path)))
```

<p>or if we need full paths</p>

<pre class="lang-py prettyprint-override"><code>from functools import partial
...
txt_files_paths = (strategies.sampled_from(sorted(os.listdir(directory_path)))
                   .map(partial(os.path.join, directory_path)))
</code>```

or if the directory may have files of different extensions and we need only .txt ones we can use glob.glob

import glob
...
txt_files_paths = strategies.sampled_from(sorted(glob.glob(os.path.join(directory_path, '*.txt'))))
```

<h1>Dynamic case</h1>

<p>If directory contents may change and we want to make directory scan on each data generation attempt it can be done like</p>

<pre class="lang-py prettyprint-override"><code>dynamic_txt_files_names = (strategies.builds(os.listdir,
                                             strategies.just(directory_path))
                           .map(sorted)
                           .flatmap(strategies.sampled_from))
</code>```

or with full paths

dynamic_txt_files_paths = (strategies.builds(os.listdir,
                                             strategies.just(directory_path))
                           .map(sorted)
                           .flatmap(strategies.sampled_from)
                           .map(partial(os.path.join, directory_path)))
```

<p>or with <code>glob.glob</code></p>

<pre class="lang-py prettyprint-override"><code>dynamic_txt_files_paths = (strategies.builds(glob.glob,
                                             strategies.just(os.path.join(
                                                     directory_path,
                                                     '*.txt')))
                           .map(sorted)
                           .flatmap(strategies.sampled_from))
</code>```

Edit

Added sorted following comment by @Zac Hatfield-Dodds.

Body:
I want to add tests using the Hypothesis library (already use in the software for testing).
For these tests, I have to use a set of txt files contained in a folder.
I need to randomly choose one of these files each time I run my tests.
How to do that using Hypothesis?

edit
Here basically how it would look like, to comply the templates of already existing tests.

@given(doc=)
def mytest(doc):

    # assert some stuff according to doc
    assert some_stuff

Body:
Static case

If files list is assumed to be "frozen" (no files will be deleted/added) then we can use os.listdir + hypohtesis.strategies.sampled_from like

import os

from hypothesis import strategies

directory_path = 'path/to/directory/with/txt/files'
txt_files_names = strategies.sampled_from(sorted(os.listdir(directory_path)))

or if we need full paths

from functools import partial
...
txt_files_paths = (strategies.sampled_from(sorted(os.listdir(directory_path)))
                   .map(partial(os.path.join, directory_path)))

or if the directory may have files of different extensions and we need only .txt ones we can use glob.glob

import glob
...
txt_files_paths = strategies.sampled_from(sorted(glob.glob(os.path.join(directory_path, '*.txt'))))

Dynamic case

If directory contents may change and we want to make directory scan on each data generation attempt it can be done like

dynamic_txt_files_names = (strategies.builds(os.listdir,
                                             strategies.just(directory_path))
                           .map(sorted)
                           .flatmap(strategies.sampled_from))

or with full paths

dynamic_txt_files_paths = (strategies.builds(os.listdir,
                                             strategies.just(directory_path))
                           .map(sorted)
                           .flatmap(strategies.sampled_from)
                           .map(partial(os.path.join, directory_path)))

or with glob.glob

dynamic_txt_files_paths = (strategies.builds(glob.glob,
                                             strategies.just(os.path.join(
                                                     directory_path,
                                                     '*.txt')))
                           .map(sorted)
                           .flatmap(strategies.sampled_from))

Edit

Added sorted following comment by @Zac Hatfield-Dodds.


问:
Set umask for a sftp account?
Could anyone tell me how to set the umaskfor a single sftp user? Worth mentioning is a IBM AIX...

Adding umask 002 to that user's .profile didn't work... (the goal is that this user files are accesible to people from the same group).

I've seen somehowto's around editing the sftpd configs, though I want to set it for one user only, so I expected to find something that didn't need root access.

thanks!

f.

答:
I don't know about AIX, but you should be able to do this with OpenSSH, though it will require root permissions. You'll need to write a wrapper script for the server component of sftp. The wrapper will need to selectively change the umask for the user and then exec the sftp server. For selecting a user, I'm partial to:

```<code>id --user
</code>```

If you were to create such a script as /usr/local/sbin/sftp-wrapper, you would then change the configuration for the sftp subsystem in /etc/ssh/sshd_config from:

```<code>Subsystem   sftp    /usr/libexec/openssh/sftp-server
</code>```

to:

```<code>Subsystem   sftp    /usr/local/sbin/sftp-wrapper
</code>```

Beyond writing the wrapper script, every step will require root permissions.

Comment: I believe the sftp server is started by root when you connect via sftp. Thus, the default umask derives from root's umask. I don't believe there is a way of altering this for a particular user from within that user's configuration. If you want to change the sftp umask for all users, you can make a simpler modification to the sftp subsystem configuration:

```<code>Subsystem   sftp    /bin/bash -c ‘umask 002; /usr/libexec/openssh/sftp-server’
</code>```

ContentLicense: CC BY-SA 2.5

Title: Set umask for a sftp account?

Body:
I don't know about AIX, but you should be able to do this with OpenSSH, though it will require root permissions. You'll need to write a wrapper script for the server component of sftp. The wrapper will need to selectively change the umask for the user and then exec the sftp server. For selecting a user, I'm partial to:

id --user

If you were to create such a script as /usr/local/sbin/sftp-wrapper, you would then change the configuration for the sftp subsystem in /etc/ssh/sshd_config from:

Subsystem   sftp    /usr/libexec/openssh/sftp-server

to:

Subsystem   sftp    /usr/local/sbin/sftp-wrapper

Beyond writing the wrapper script, every step will require root permissions.

Comment: I believe the sftp server is started by root when you connect via sftp. Thus, the default umask derives from root's umask. I don't believe there is a way of altering this for a particular user from within that user's configuration. If you want to change the sftp umask for all users, you can make a simpler modification to the sftp subsystem configuration:

Subsystem   sftp    /bin/bash -c ‘umask 002; /usr/libexec/openssh/sftp-server’


问:
Return List based on generic T
I want to convert list of TEntity to list of TDto.

```<code>    private List<TDto> ConvertUEntityToDto<TDto, TEntity>(IEnumerable<TEntity> entities)
    {
        if (entities is IEnumerable<Entity1>)
        {
            var result = new List<EntityDto1>
            foreach (var entity in entities)
            {
                result.Add(_mapper.Map<EntityDto1>(entity ));
            }

            return result;
        }

        else if (entities is IEnumerable<Entity2>)
        {
            var result = new List<EntityDto2>
            foreach (var entity in entities)
            {
                result.Add(_mapper.Map<EntityDto2>(entity));
            }

            return result;
        }

        return null;
    }
</code>```

From code above i get an error:

Error CS0029  Cannot implicitly convert type 'System.Collections.Generic.List< EntityDto>' to 'System.Collections.Generic.List< TDto>'

How to return dynamically List of T from generic method in C#?

答:
The meaning of generics are to use them! The if-else should precede your generic function (also see edit below).

```<code>if (entities is IEnumerable<Entity1>)
    ConvertUEntityToDto<TDto1, Entity1>(entities);
else if (entities is IEnumerable<Entity2>)
    ConvertUEntityToDto<TDto2, Entity2>(entities);
else ; //do nothing
</code>```

and inside ConvertUEntityToDto it should use the T (TDto) as follows:

```<code>private List<TDto> ConvertUEntityToDto<TDto, TEntity>(IEnumerable<TEntity> entities)
{
    var result = new List<TDto>
    foreach (var entity in entities)
    {
        result.Add(_mapper.Map<TDto>(entity));
    }
    return result;
}
</code>```

The error was because the return type didn't match with the signature of your function.

But I want to mention

You could just pass in a list, iterate it with foreach and if the element within the list is of type T, then Add to your new List<T> which you return.

Also, you should have constraints for T.

Edit:

What I mentioned above, to return all element of the list, only which matches the type TDto (and to get rid of the preceding if-else block), we can use the following snippet (by referencing System.Linq in the project) (thanks @Janne Matikainen to mention):

```<code>private List<TDto> ConvertUEntityToDto<TDto, TEntity, Tmixed>(IEnumerable<Tmixed> entities)
{
    return entities.Where(e => e is TEntity).Select(e => _mapper.Map<TDto>(e));
}
</code>```

Which is equivalent to:

```<code>private List<TDto> ConvertUEntityToDto<TDto, TEntity, Tmixed>(IEnumerable<Tmixed> entities)
    => entities.Where(e => e is TEntity).Select(e => _mapper.Map<TDto>(e));
</code>```

Title: Return List based on generic T

Body:
I want to convert list of TEntity to list of TDto.

    private List<TDto> ConvertUEntityToDto<TDto, TEntity>(IEnumerable<TEntity> entities)
    {
        if (entities is IEnumerable<Entity1>)
        {
            var result = new List<EntityDto1>
            foreach (var entity in entities)
            {
                result.Add(_mapper.Map<EntityDto1>(entity ));
            }

            return result;
        }

        else if (entities is IEnumerable<Entity2>)
        {
            var result = new List<EntityDto2>
            foreach (var entity in entities)
            {
                result.Add(_mapper.Map<EntityDto2>(entity));
            }

            return result;
        }

        return null;
    }

From code above i get an error:

Error CS0029  Cannot implicitly convert type 'System.Collections.Generic.List< EntityDto>' to 'System.Collections.Generic.List< TDto>'

How to return dynamically List of T from generic method in C#?

Body:
The meaning of generics are to use them! The if-else should precede your generic function (also see edit below).

if (entities is IEnumerable<Entity1>)
    ConvertUEntityToDto<TDto1, Entity1>(entities);
else if (entities is IEnumerable<Entity2>)
    ConvertUEntityToDto<TDto2, Entity2>(entities);
else ; //do nothing

and inside ConvertUEntityToDto it should use the T (TDto) as follows:

private List<TDto> ConvertUEntityToDto<TDto, TEntity>(IEnumerable<TEntity> entities)
{
    var result = new List<TDto>
    foreach (var entity in entities)
    {
        result.Add(_mapper.Map<TDto>(entity));
    }
    return result;
}

The error was because the return type didn't match with the signature of your function.

But I want to mention

You could just pass in a list, iterate it with foreach and if the element within the list is of type T, then Add to your new List<T> which you return.

Also, you should have constraints for T.

Edit:

What I mentioned above, to return all element of the list, only which matches the type TDto (and to get rid of the preceding if-else block), we can use the following snippet (by referencing System.Linq in the project) (thanks @Janne Matikainen to mention):

private List<TDto> ConvertUEntityToDto<TDto, TEntity, Tmixed>(IEnumerable<Tmixed> entities)
{
    return entities.Where(e => e is TEntity).Select(e => _mapper.Map<TDto>(e));
}

Which is equivalent to:

private List<TDto> ConvertUEntityToDto<TDto, TEntity, Tmixed>(IEnumerable<Tmixed> entities)
    => entities.Where(e => e is TEntity).Select(e => _mapper.Map<TDto>(e));


问:
Keycloak integration with CDI in REST API JAXRS
We have a widlfy REST API jaxrs and we want to secure it with keycloak.

The problem is the integration with @SecurityDomain("keycloak") is working only with an EJB entry-point. it is ignored on class with no @Stateless annotation

The issue is the entry point become an EJB and EJB poolManaged what is not really a good thing for a stateless application.
Moreover all methods in EJB are transactional and we do not want this behavior. So yes we can add an annotation transactional to specify to not use transaction in the method, but i think it is a workaround.

We want to work the most we can with CDI. and have entry point with ejb pool management with in wildlfy 20 EJB in same time can be a bottleneck in a big application.

Any idea ? or proper way to implement keycloak security with CDI ?

答:
If you mean declarative security using @RolesAllowed annotation this is not supported on all CDI beans, is only supported by EJBs and Servlets.

As JAX-RS will run on a webapp, you can use declarative security based on url-patterns and HTTP methods using security-constraints in web.xml

You can also implement programmatic security in the JAX-RS methods (or in a filter), using the SecurityContext.

```<code>@Context
SecurityContext securityContext;

@GET
public Response get() {
    if (securityContext.isUserInRole("ROLE")) {
        ....
    }
    ....
}
</code>```

Although not and standard feature, Wildfly JAX-RS implementation, RestEasy, can be configured to support @RolesAllowed annotations. See:
https://docs.jboss.org/resteasy/docs/4.4.2.Final/userguide/html/Securing_JAX-RS_and_RESTeasy.html

Body:
If you mean declarative security using @RolesAllowed annotation this is not supported on all CDI beans, is only supported by EJBs and Servlets.

As JAX-RS will run on a webapp, you can use declarative security based on url-patterns and HTTP methods using security-constraints in web.xml

You can also implement programmatic security in the JAX-RS methods (or in a filter), using the SecurityContext.

@Context
SecurityContext securityContext;

@GET
public Response get() {
    if (securityContext.isUserInRole("ROLE")) {
        ....
    }
    ....
}

Although not and standard feature, Wildfly JAX-RS implementation, RestEasy, can be configured to support @RolesAllowed annotations. See:
https://docs.jboss.org/resteasy/docs/4.4.2.Final/userguide/html/Securing_JAX-RS_and_RESTeasy.html


问:
useState hook not initialising with correct value: Array
I am passing an array 'defaults' into my panel component and then trying to set state hook 'selected option' to be equal to it. For some reason, the hook is setting an empty array instead.

component:

```<code>const Panel = ({ title, inputs, datepicker, identifiers, apiBase, isins, defaults = [], notes = "" }) => {
    const [expand, setExpand] = useState(false);
    const [date, setDate] = useState(new Date());
    const [selectedOption, setSelectedOption] = useState([...defaults]);
    const [dataError, setDataError] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    const [errorCheckLoading, setErrorCheckLoading] = useState(false);

    const toggleExpand = () => {
        setExpand(!expand);
        console.log(defaults);
        console.log(selectedOption);
    };
</code>```

Just for testing, I have a couple of console logs in my toggle expand function so I can test the data passed in against the data set.

Output from console logs:

```<code>>(48) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
>[]
</code>```

So I know the data comes in ok, just that it doesn't set in the hook.

I have also tried giving the hook initial values of defaults, and  [defaults].

Now drawing a blank - any ideas?

Edit: this is the parent component supplying the defaults:

```<code>const Parent = () => {

    const [all, setAll] = useState([]);
    const [allLoadFailed, setAllLoadFailed] = useState(false);

    const [defaults, setDefaults] = useState([]);
    const [defaultsLoadFailed, setDefaultsLoadFailed] = useState(false);

    useEffect(() => { loadData()}, []);
    useEffect(() => { loadDefaultData()}, []);

    const loadDefaultData = async () => {
        try {
            let defaultData = await GetDefaults();
            setDefaults(defaultData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setDefaultsLoadFailed(true);
        }
    };

    const loadData = async () => {
        try {
            let iData = await GetAll();
            let filteredIData = iData.filter(item => item);
            setAll(filteredIData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setAllLoadFailed(true);
        }
    };

    return (

            <Panel
                title="Test"
                isins={all}
                defaults={defaults}
                inputs
                datepicker
                identifiers
                apiBase=""
                notes="not yet complete"
                key="2"
            />
    );
</code>```

答:
Check your destructuring, you're setting a default value to defaults = []. It will only render the empty array first and then the component will complete it's mount. You might want to use a useEffect hook to check for new updates and then set the setSelectedOption(defaults) in there like so:

```<code>useEffect(() => {
   setSelectedOption(defaults)
}, [defaults])
</code>```

Body:
I am passing an array 'defaults' into my panel component and then trying to set state hook 'selected option' to be equal to it. For some reason, the hook is setting an empty array instead.

component:

const Panel = ({ title, inputs, datepicker, identifiers, apiBase, isins, defaults = [], notes = "" }) => {
    const [expand, setExpand] = useState(false);
    const [date, setDate] = useState(new Date());
    const [selectedOption, setSelectedOption] = useState([...defaults]);
    const [dataError, setDataError] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    const [errorCheckLoading, setErrorCheckLoading] = useState(false);

    const toggleExpand = () => {
        setExpand(!expand);
        console.log(defaults);
        console.log(selectedOption);
    };

Just for testing, I have a couple of console logs in my toggle expand function so I can test the data passed in against the data set.

Output from console logs:

>(48) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
>[]

So I know the data comes in ok, just that it doesn't set in the hook.

I have also tried giving the hook initial values of defaults, and  [defaults].

Now drawing a blank - any ideas?

Edit: this is the parent component supplying the defaults:

const Parent = () => {

    const [all, setAll] = useState([]);
    const [allLoadFailed, setAllLoadFailed] = useState(false);

    const [defaults, setDefaults] = useState([]);
    const [defaultsLoadFailed, setDefaultsLoadFailed] = useState(false);

    useEffect(() => { loadData()}, []);
    useEffect(() => { loadDefaultData()}, []);

    const loadDefaultData = async () => {
        try {
            let defaultData = await GetDefaults();
            setDefaults(defaultData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setDefaultsLoadFailed(true);
        }
    };

    const loadData = async () => {
        try {
            let iData = await GetAll();
            let filteredIData = iData.filter(item => item);
            setAll(filteredIData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setAllLoadFailed(true);
        }
    };

    return (

            <Panel
                title="Test"
                isins={all}
                defaults={defaults}
                inputs
                datepicker
                identifiers
                apiBase=""
                notes="not yet complete"
                key="2"
            />
    );

Body:
Check your destructuring, you're setting a default value to defaults = []. It will only render the empty array first and then the component will complete it's mount. You might want to use a useEffect hook to check for new updates and then set the setSelectedOption(defaults) in there like so:

useEffect(() => {
   setSelectedOption(defaults)
}, [defaults])