问:
JavaScript Function Call Causes "setUTCHours is not a Function"
I have some MongoDB records with an OrderDate I wish to update the time component to midnight 00:00:00.000. The object is of the form

```<code>{
    "SourceSystem" : "XXXX"
    "OrderDate" : {
        "DateTime" : ISODate("2017-11-29T00:00:00.000+00:00"),
        "Ticks" : 636475104000000000
    }
}
</code>```

To do this I have the following JavaScript

```<code>function generateDate(targetDateTime){
    let ticks = targetDateTime.getTime() * 10000;
    ticks += 621355968000000000;
    return {
        DateTime: targetDateTime,
        Ticks: NumberLong(ticks)
    };
}

function datePartOnly(targetDateTime){
    targetDateTime.setUTCHours(0, 0, 0, 0);
    return generateDate(targetDateTime);
}

let orders = db.Orders.aggregate([
    {
        $match: {
            State: { $in: [ "Completed", "AwaitingExport" ] },
            SourceSystem: "Demon",
            OrderDate: {
                $gte: generateDate(ISODate("20200101")),
                $lt: generateDate(ISODate("20200701"))
            }
        }
    },
    {
        $addFields: {
            OrderDateString: {
                $dateToString: {
                    format: "%H%M%S.%L",
                    date: "$OrderDate.DateTime"
                }
            }
        }
    },
    {
        $match: {
            OrderDateString: /^((?!0{6}\.0{3})[\s\S])*$/
        }
    },
    {
        $project: { _id: 1 }
    }
]).toArray().map( o => o._id );

db.Orders.updateMany(
    {
        _id: { $in : orders }
    },
    {
        $set : {
            OrderDate: datePartOnly("$OrderDate.DateTime")
        }
    }
)
</code>```

but I am getting the following error

"message" : "targetDateTime.setUTCHours is not a function",
  "stack" : "script:11:20" +
            "script:52:24"

Why is this call failing. I have tried using OrderDate: datePartOnly(ISODate("$OrderDate.DateTime")) but this gives

"message" : "invalid ISO date: $OrderDate.DateTime",
      "stack" : "script:1:37" +
                "script:1:37" +
                "script:52:37"

OrderDate: datePartOnly(Date("$OrderDate.DateTime")) does not work either.

What is wrong with the above?

答: By a small chance, is it possible the argument you are passing as targetDateTime is not a Date object (or any type with such function) ? This could explain why targetDateTime.setUTCHours is not a valid function.

Body:
I have some MongoDB records with an OrderDate I wish to update the time component to midnight 00:00:00.000. The object is of the form

{
    "SourceSystem" : "XXXX"
    "OrderDate" : {
        "DateTime" : ISODate("2017-11-29T00:00:00.000+00:00"),
        "Ticks" : 636475104000000000
    }
}

To do this I have the following JavaScript

function generateDate(targetDateTime){
    let ticks = targetDateTime.getTime() * 10000;
    ticks += 621355968000000000;
    return {
        DateTime: targetDateTime,
        Ticks: NumberLong(ticks)
    };
}

function datePartOnly(targetDateTime){
    targetDateTime.setUTCHours(0, 0, 0, 0);
    return generateDate(targetDateTime);
}

let orders = db.Orders.aggregate([
    {
        $match: {
            State: { $in: [ "Completed", "AwaitingExport" ] },
            SourceSystem: "Demon",
            OrderDate: {
                $gte: generateDate(ISODate("20200101")),
                $lt: generateDate(ISODate("20200701"))
            }
        }
    },
    {
        $addFields: {
            OrderDateString: {
                $dateToString: {
                    format: "%H%M%S.%L",
                    date: "$OrderDate.DateTime"
                }
            }
        }
    },
    {
        $match: {
            OrderDateString: /^((?!0{6}\.0{3})[\s\S])*$/
        }
    },
    {
        $project: { _id: 1 }
    }
]).toArray().map( o => o._id );

db.Orders.updateMany(
    {
        _id: { $in : orders }
    },
    {
        $set : {
            OrderDate: datePartOnly("$OrderDate.DateTime")
        }
    }
)

but I am getting the following error

"message" : "targetDateTime.setUTCHours is not a function",
  "stack" : "script:11:20" +
            "script:52:24"

Why is this call failing. I have tried using OrderDate: datePartOnly(ISODate("$OrderDate.DateTime")) but this gives

"message" : "invalid ISO date: $OrderDate.DateTime",
      "stack" : "script:1:37" +
                "script:1:37" +
                "script:52:37"

OrderDate: datePartOnly(Date("$OrderDate.DateTime")) does not work either.

What is wrong with the above?


来源: stackexchange

问:
How do I mock leaflet for jest tests?
I use a custom icon in L.Icon in a CRA project. It keeps saying L is undefined when running jest tests. How would I mock leaflet to avoid this error?</p>

答:
I found this answer on a similar issue in leaflet itself

```<code>What I can recommend for testing is the following,
 just mock leaflet using this in your test file,
 that is rendering the map component:
jest.mock('leaflet')

And then you place this leaflet mock you can
find in react-leaflet into the jest mocks folder
 (__mocks__/leaflet.js, download the current file from:
https://github.com/PaulLeCam/react-leaflet/blob/master/__mocks__/leaflet.js)

That should be enough in most cases.
</code>```

ref: https://github.com/Leaflet/Leaflet/issues/6297#issuecomment-499809735

ContentLicense: CC BY-SA 4.0

Title: How do I mock leaflet for jest tests?

Body:
I found this answer on a similar issue in leaflet itself

What I can recommend for testing is the following,
 just mock leaflet using this in your test file,
 that is rendering the map component:
jest.mock('leaflet')

And then you place this leaflet mock you can
find in react-leaflet into the jest mocks folder
 (__mocks__/leaflet.js, download the current file from:
https://github.com/PaulLeCam/react-leaflet/blob/master/__mocks__/leaflet.js)

That should be enough in most cases.

ref: https://github.com/Leaflet/Leaflet/issues/6297#issuecomment-499809735


问:
Hi, Using Oracle Apex 19.1, I have a requirement of downloading data into excel as multiple tabs
.Each interactive report data should come in each tab(i.e) sheet1, sheet2....

Example: In Apex page, I have 5 report region. Each report data should be downloaded in each sheet, In a single excel file.Please provide me a solution, Thanks in advance Karthick.

答:
If you cannot upgrade your APEX environment then, as TineO said, probably AOP is the best option you have.

If you can upgrade to 19.2 or higher, then you can utilize APEX_REGION.OPEN_QUERY_CONTEXT API to get the records of the interactive reports. Then, you can use the Open Source library Alexandria and in particular, the xlsx_builder_pkg package to create the spreadsheets.


问:
Moving elements to end of previous line
I have a problem with moving a defined text block ("PT") to the end of its previous line.. for eg, consider the following :-

100001,-6.0704
 PT

  100061,19.1127
 100122,8.1831

  PT

I need that to be :-

100001,-6.0704PT

  100061,19.1127
 100122,8.1831PT

I have a large irregularly repeating data like this.. and need to achieve this..(moving the "PT" to currentline-1")

I have Notepad++  I need to achieve this somehow.. maybe using spreadsheets? online tools? and how? macros? batch files?

答:
try this as a first attempt

```<code>@echo off
setlocal enabledelayedexpansion
set prevline=
for /f "tokens=*" %%a in (a.txt) do (
  if '%%a'=='PT' (
   echo !prevline!PT
   set prevline=
  ) else (
   if not '!prevline!'=='' echo !prevline!
   set prevline=%%a
 )
)
</code>```

this batch file iterates over all the lines of the a.txt file, storing each line in the variable prevline, if it happens to find the 'PT' string it spits the stored line and concatenates the PT, if it happens not to find the PT string, it spits just the stored line and stores the new line.

For a further explanation, see help for and help set.

ContentLicense: CC BY-SA 3.0

Title: Moving elements to end of previous line

Body:
try this as a first attempt

@echo off
setlocal enabledelayedexpansion
set prevline=
for /f "tokens=*" %%a in (a.txt) do (
  if '%%a'=='PT' (
   echo !prevline!PT
   set prevline=
  ) else (
   if not '!prevline!'=='' echo !prevline!
   set prevline=%%a
 )
)

this batch file iterates over all the lines of the a.txt file, storing each line in the variable prevline, if it happens to find the 'PT' string it spits the stored line and concatenates the PT, if it happens not to find the PT string, it spits just the stored line and stores the new line.

For a further explanation, see help for and help set.


问:
Unable to trigger onchange event from select tag in ASP.Net
I want to change the textboxes that should be displayed based on accountType the user selects. However, the onchange event attached to select is not getting triggered. Any heads up?

This is the select tag.

```<code><div class="col-md-12 form-group" style="color:black">
    <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
            <option value="customer">Customer</option>
            <option value="pharmacy">Pharmacy</option>
            <option value="doctor">Doctor</option>
    </select>
</div>
</code>```

The accountType_Changed function is:

```<code>void accountType_Changed(Object sender, EventArgs e)
{
    cnic.Text = accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}
</code>```

Edit:
Based on the solution proposed by @mahesh_b, following edits were made that fixed the problem:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    this.accountTypes.Attributes.Add("onchange", Page.ClientScript.GetPostBackEventReference(this.accountTypes, this.accountTypes.ID));
}

protected void accountType_Changed(object sender, EventArgs e)
{
    cnic.Text = "Working!!!"; //accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}
</code>```

Edit 2: Layout Rendering Issue after adding partial refresh

Login.aspx:

```<code><asp:ScriptManager EnablePartialRendering="true" ID="scriptManager" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <section class="login_part section_padding ">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-6 col-md-6">
                <div class="login_part_text text-center">
                    <div class="login_part_text_iner">
                        <h2>New to PHS?</h2>

                        <div class="row">

                            <div class="column col-md-12 form-group p_star">
                                <div class="col-md-12 form-group p_star">
                                    <asp:TextBox ID="firstname" placeholder="First Name" class="form-control" runat="server">
                                    </asp:TextBox>
                                </div>
                            </div>

                            <div class="column col-md-12 form-group p_star">
                                <div class="col-md-12 form-group p_star">
                                    <asp:TextBox ID="lastname" placeholder="Last Name" class="form-control" runat="server">
                                    </asp:TextBox>
                               </div>

                            </div>

                        </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="cnic" placeholder="CNIC" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="email" placeholder="Email" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="pass" placeholder="Password" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group" style="color:black">
                            <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
                              <option value="customer">Customer</option>
                              <option value="pharmacy">Pharmacy</option>
                              <option value="doctor">Doctor</option>
                            </select>
                        </div>

                        <br /><br />
                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="taxNo" placeholder="Tax No" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="pName" placeholder="Pharmacy Name" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="pAddress" placeholder="Pharmacy Address" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="cAddress" placeholder="Address" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="docID" placeholder="Doctor Id" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="experience" placeholder="Experience (Years)" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="expertise" placeholder="Expertise (Specialization)" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <br />
                        <p>Create an account today and avail the best deals on medics.</p>
                        <asp:Button ID="registerButton" class="btn_3" runat="server" width="50%" Text="Create Account" OnClick="createAccount_Clicked"/>

                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-6">
                <div class="login_part_form">
                    <div class="login_part_form_iner">
                        <h3>Welcome Back ! <br>
                            Please Sign in now</h3>
                        <form class="row contact_form" action="#" method="post" novalidate="novalidate">
                            <div class="col-md-12 form-group p_star">
                                <input type="text" class="form-control" id="name" name="name" value=""
                                    placeholder="Username">
                            </div>
                            <div class="col-md-12 form-group p_star">
                                <input type="password" class="form-control" id="password" name="password" value=""
                                    placeholder="Password">
                            </div>
                            <div class="col-md-12 form-group">

                                <button type="submit" value="submit" class="btn_3">
                                    log in
                                </button>
                                <a class="lost_pass" href="#">forget password?</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</ContentTemplate>
</asp:UpdatePanel>
</code>```

These images show the original layout of select and what gets loaded after I change the value:

Original:

This is what gets loaded after changing the value in accountType:

How can I get to keep my original layout?

答:
For HTML controls use the server events, in your case OnServerChange event. In order the serverchange event to fire you have to explicitly submit the form or do a postback on onchange event. You can do this with below two options -

Submit the form on onchange event from client side:

```<code><select name="accountTypes" id="accountTypes" runat="server"
onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
</code>```

Use the GetPostBackEventReference method from server side:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    this.accountTypes.Attributes.Add("onchange", Page.ClientScript.GetPostBackEventReference(this.accountTypes, this.accountTypes.ID));

}
</code>```

You may have to also change the method signature to-

```<code>    protected void accountType_Changed(object sender, EventArgs e)
    {

    }
</code>```

Refer these threads to understand more on the same -

How to make HtmlSelect Control with OnChange event to trigger C# code behind function

OnServerChange event not firing

If your requirement can fit with changing to ASP.NET Drop down list then you can follow which Selim mentioned in another answer.

Body:
I want to change the textboxes that should be displayed based on accountType the user selects. However, the onchange event attached to select is not getting triggered. Any heads up?

This is the select tag.

    <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
            <option value="customer">Customer</option>
            <option value="pharmacy">Pharmacy</option>
            <option value="doctor">Doctor</option>
    </select>

The accountType_Changed function is:

void accountType_Changed(Object sender, EventArgs e)
{
    cnic.Text = accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}

Edit:
Based on the solution proposed by @mahesh_b, following edits were made that fixed the problem:

protected void Page_Load(object sender, EventArgs e)
{
    this.accountTypes.Attributes.Add("onchange", Page.ClientScript.GetPostBackEventReference(this.accountTypes, this.accountTypes.ID));
}

protected void accountType_Changed(object sender, EventArgs e)
{
    cnic.Text = "Working!!!"; //accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}

Edit 2: Layout Rendering Issue after adding partial refresh

Login.aspx:

<asp:ScriptManager EnablePartialRendering="true" ID="scriptManager" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

New to PHS?

                                    <asp:TextBox ID="firstname" placeholder="First Name" class="form-control" runat="server">
                                    </asp:TextBox>

                                    <asp:TextBox ID="lastname" placeholder="Last Name" class="form-control" runat="server">
                                    </asp:TextBox>

                            <asp:TextBox ID="cnic" placeholder="CNIC" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="email" placeholder="Email" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="pass" placeholder="Password" class="form-control" runat="server">
                            </asp:TextBox>

                            <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
                              <option value="customer">Customer</option>
                              <option value="pharmacy">Pharmacy</option>
                              <option value="doctor">Doctor</option>
                            </select>

                            <asp:TextBox ID="taxNo" placeholder="Tax No" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="pName" placeholder="Pharmacy Name" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="pAddress" placeholder="Pharmacy Address" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="cAddress" placeholder="Address" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="docID" placeholder="Doctor Id" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="experience" placeholder="Experience (Years)" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="expertise" placeholder="Expertise (Specialization)" class="form-control" runat="server">
                            </asp:TextBox>

Create an account today and avail the best deals on medics.

                        <asp:Button ID="registerButton" class="btn_3" runat="server" width="50%" Text="Create Account" OnClick="createAccount_Clicked"/>

Welcome Back !

                            Please Sign in now

                        <form class="row contact_form" action="#" method="post" novalidate="novalidate">

                                <input type="text" class="form-control" id="name" name="name" value=""
                                    placeholder="Username">

                                <input type="password" class="form-control" id="password" name="password" value=""
                                    placeholder="Password">

                                <button type="submit" value="submit" class="btn_3">
                                    log in
                                </button>
                                forget password?

                        </form>

</ContentTemplate>
</asp:UpdatePanel>

These images show the original layout of select and what gets loaded after I change the value:

Original:

This is what gets loaded after changing the value in accountType:

How can I get to keep my original layout?

Body:
For HTML controls use the server events, in your case OnServerChange event. In order the serverchange event to fire you have to explicitly submit the form or do a postback on onchange event. You can do this with below two options -

Submit the form on onchange event from client side:

<select name="accountTypes" id="accountTypes" runat="server"
onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">

Use the GetPostBackEventReference method from server side:

protected void Page_Load(object sender, EventArgs e)
{
    this.accountTypes.Attributes.Add("onchange", Page.ClientScript.GetPostBackEventReference(this.accountTypes, this.accountTypes.ID));

}

You may have to also change the method signature to-

    protected void accountType_Changed(object sender, EventArgs e)
    {

    }

Refer these threads to understand more on the same -

How to make HtmlSelect Control with OnChange event to trigger C# code behind function

OnServerChange event not firing

If your requirement can fit with changing to ASP.NET Drop down list then you can follow which Selim mentioned in another answer.


问:
Dashboard wordpress is empty
somebody else have created my web site then he gave me access to wp-admin page, but my Dashboard is empty i can't add anything. i'm a beginer so please help me, thanks </p>

答:
Check the permissions of the account you're logged into. If you're not seeing much but you can login, high chance you're not an admin.

If you're only seeing a white page after logging in, then there could be a number of things causing the issue https://wordpress.org/support/article/common-wordpress-errors/#the-white-screen-of-death

Providing a screenshot of what you're seeing will help diagnosing the issue further.

Title: Dashboard wordpress is empty


问:
Why does my banner create a horizontal scroll bar?
• When I insert the banner for the site a horizontal scroll bar is created, how can I solve this? That the image resolution is good.
The same thing happens to me at the table, he creates a vertical scroll bar. How can I solve these things? I don't know how to use @media to optimize all resolutions. Do you think I can solve this somehow?

Link preview: https://imgur.com/a/CQsvWeW
Banner: https://imgur.com/a/1hEhJRI

.banner{
position: relative;
top: 0;
margin-top: 4.3%;
right: -80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <body>
<div id="container">
<div id="header">
  <img class="banner" src="img\banner.png" alt="Banner">
</div></code>```

答:
If all you want is to hide scrollbars without regard to whether the whole banner is displayed, then you can use overflow:</p>

```<code>.banner{
overflow: hidden; /* Hide scrollbars */
position: relative;
top: 0;
margin-top: 4.3%;
right: -80px;
}
</code>```

Body:
If all you want is to hide scrollbars without regard to whether the whole banner is displayed, then you can use overflow:

.banner{
overflow: hidden; /* Hide scrollbars */
position: relative;
top: 0;
margin-top: 4.3%;
right: -80px;
}


问:
powerpc-eabivle-gcc does not support e_and2i instruction
I am using NXP's GCC 4.9 VLE compiler. I am targeting an e200z7 core. I want to disable 16th bit of the MSR register. Here is what I am using:

```<code>/* Disable MSR[EE] bit*/
        mfmsr   r6
        e_and2i r6,0x7fff
        mtmsr   r6
</code>```

When I compile the .S file using powerpc_eabivle_4_9/bin/powerpc-eabivle-gcc, it gives me following error:

```<code>Error: unrecognized opcode: `e_and2i'
</code>```

How to set it to 0 without the and instruction?

答:
Update: see @MichaelPetch's answer for VLE (variable-length-encoding).  My answer is just a simple naive answer for generic PowerPC that's not optimal when compact 16-bit instructions are available.

If you applied the same technique with NXP's version of GCC that can produce VLE asm for you from C, it will use se_bclri r3, 16.

The general technique of asking a compiler is very very useful when you don't know every peephole optimization for an ISA off the top of your head.

As usual, ask a compiler:

```<code>unsigned foo(unsigned x) {
    return x &= ~(1UL << 15);
}
</code>```

compiles on Godbolt with GCC4.8.5 -O3 -mregnames

```<code>foo(unsigned int):
        rlwinm %r3,%r3,0,17,15
        blr
</code>```

I think rlwinm is available on every PowerPC, or at least isn't particularly new or rare.  It takes a bit-range (start / end which can wrap around to leave only that one bit masked out) and a rotate count (which is zero in this case).

Body:
I am using NXP's GCC 4.9 VLE compiler. I am targeting an e200z7 core. I want to disable 16th bit of the MSR register. Here is what I am using:

/* Disable MSR[EE] bit*/
        mfmsr   r6
        e_and2i r6,0x7fff
        mtmsr   r6

When I compile the .S file using powerpc_eabivle_4_9/bin/powerpc-eabivle-gcc, it gives me following error:

Error: unrecognized opcode: `e_and2i'

How to set it to 0 without the and instruction?

Body:
Update: see @MichaelPetch's answer for VLE (variable-length-encoding).  My answer is just a simple naive answer for generic PowerPC that's not optimal when compact 16-bit instructions are available.

If you applied the same technique with NXP's version of GCC that can produce VLE asm for you from C, it will use se_bclri r3, 16.

The general technique of asking a compiler is very very useful when you don't know every peephole optimization for an ISA off the top of your head.

As usual, ask a compiler:

unsigned foo(unsigned x) {
    return x &= ~(1UL << 15);
}

compiles on Godbolt with GCC4.8.5 -O3 -mregnames

foo(unsigned int):
        rlwinm %r3,%r3,0,17,15
        blr

I think rlwinm is available on every PowerPC, or at least isn't particularly new or rare.  It takes a bit-range (start / end which can wrap around to leave only that one bit masked out) and a rotate count (which is zero in this case).


问:
startsWith() and endsWith() functions in PHP
How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?

For example:

```<code>$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
</code>```

答:
PHP 8 update

PHP 8 includes new str_starts_with and str_ends_with functions that finally provide a performant and convenient solution to this problem:

```<code>$str = "beginningMiddleEnd";
if (str_starts_with($str, "beg")) echo "printed\n";
if (str_starts_with($str, "Beg")) echo "not printed\n";
if (str_ends_with($str, "End")) echo "printed\n";
if (str_ends_with($str, "end")) echo "not printed\n";
</code>```

The RFC for this feature provides more information, and also a discussion of the merits and problems of obvious (and not-so-obvious) userland implementations.

Body:
How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?

For example:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true

Body:
PHP 8 update

PHP 8 includes new str_starts_with and str_ends_with functions that finally provide a performant and convenient solution to this problem:

$str = "beginningMiddleEnd";
if (str_starts_with($str, "beg")) echo "printed\n";
if (str_starts_with($str, "Beg")) echo "not printed\n";
if (str_ends_with($str, "End")) echo "printed\n";
if (str_ends_with($str, "end")) echo "not printed\n";

The RFC for this feature provides more information, and also a discussion of the merits and problems of obvious (and not-so-obvious) userland implementations.


问:
OpenGL on Android: Any conflicts when calling OpenGL functions in both Java and C++?
In my application, I'm using a 3rd party custom view that calls OpenGL functions in Java, and I'm also calling OpenGL functions in my native C++ code.

Should this be a problem?

Is there any risk that they could be called at the same time?

What is the threading order of OpenGL calls across java/c++?

答:
There is always problems with calling the same function from multiple threads if that function modifies some global object.

You can call OpenGL from both Java and C++, unsure if it has to be in the same thread though.

In a game I wrote I did all the rendering in C++ but loading of textures in Java (since java has access to the R class), the C++ class would call a java function which loaded the textures.


问:
Azure Functions Database Connection String
How do I add or access an app.config file in Azure functions to add a database connection string?

If you're not supposed to add an app.config and there is a better way to access an external database to execute the function please let me know best practices.  Thanks!

答:
Addition to the answer from @ToddDeLand.

With a local.settings.json like this:

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true;",
    "AzureWebJobsDashboard": ""
  },
  "ConnectionStrings": {
    "MyConnectionString": "[YourConnectionStringHere]"
  }
}
</code>```

You can then access your connection string like this, no NuGets needed.

```<code>var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:MyConnectionString");
</code>```

Microsoft recommends this approach here:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables

If you add the connection string to values:

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true;",
    "AzureWebJobsDashboard": "",
    "MyConnectionString": "[YourConnectionStringHere]"
  }
}
</code>```

You can access your connection string like this:

```<code>var connectionString = Environment.GetEnvironmentVariable("MyConnectionString");
</code>```

Sources:

https://stackoverflow.com/a/52219491/3850405

https://github.com/Azure/Azure-Functions/issues/717#issuecomment-400098791

Body:
Addition to the answer from @ToddDeLand.

With a local.settings.json like this:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true;",
    "AzureWebJobsDashboard": ""
  },
  "ConnectionStrings": {
    "MyConnectionString": "[YourConnectionStringHere]"
  }
}

You can then access your connection string like this, no NuGets needed.

var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:MyConnectionString");

Microsoft recommends this approach here:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables

If you add the connection string to values:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true;",
    "AzureWebJobsDashboard": "",
    "MyConnectionString": "[YourConnectionStringHere]"
  }
}

You can access your connection string like this:

var connectionString = Environment.GetEnvironmentVariable("MyConnectionString");

Sources:

https://stackoverflow.com/a/52219491/3850405

https://github.com/Azure/Azure-Functions/issues/717#issuecomment-400098791


问:
Add new column into table tbody and thead
could you please help me with adding new column into table. Table has thead and tbody, I need to add column with heading (th) "Details", and each row (that is td) needs to have link inside.for example Link. New column should be inserted after second column.</p>

```<code><table>
            <thead>
                <tr>
                    <th></th>
                    <th>Title</th>
                    <th>Author</th>
                    <th># comments</th>
                    <th>Publication date</th>
                    <th>Updated</th>
                    <th>Type</th>
                    <th>Section</th>
                    <th>Language</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="checkbox"></td>
                    <td><a href="#">Lorem ipsum #1</a></td>
                    <td>Name</td>
                    <td>3 comments</td>
                    <td>2014-05-07 15:00</td>
                    <td>2014-05-07 15:00</td>
                    <td>Article</td>
                    <td><a href="#">Standard</a></td>
                    <td>English</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td><a href="#">Lorem ipsum #2</a></td>
                    <td>Name</td>
                    <td>3 comments</td>
                    <td>2014-05-07 14:00</td>
                    <td></td>
                    <td>Article</td>
                    <td><a href="#">Standard</a></td>
                    <td>English</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td><a href="#">Lorem ipsum #3</a></td>
                    <td>Name</td>
                    <td></td>
                    <td>2014-05-07 13:00</td>
                    <td></td>
                    <td>Forum post</td>
                    <td><a href="#">Forum</a></td>
                    <td>Polish</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td><a href="#">Lorem ipsum #4</a></td>
                    <td>Name</td>
                    <td>25 comments</td>
                    <td>2014-05-07 12:00</td>
                    <td>2014-05-07 15:00</td>
                    <td>Blog post</td>
                    <td><a href="#">Blog</a></td>
                    <td>French</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td><a href="#">Lorem ipsum #5</a></td>
                    <td>Name</td>
                    <td>35 comments</td>
                    <td>2014-05-07 11:00</td>
                    <td>2014-05-07 15:00</td>
                    <td>Blog post</td>
                    <td><a href="#">Blog</a></td>
                    <td>English</td>
                </tr>
            </tbody>
        </table>
</code>```

答:
```<code>var _ky = 0;
//  Below code append column in thead
$('#table_id').find('thead').find('tr').each(function () {
var tr = $(this);
tr.append('<th>Write Heading Here</th>');
});
//  Below code append column in tbody
$('#table_id').find('tbody').find('tr').each(function () {
var tr = $(this);
tr.append('<td>' + _ky + '</td>');
_ky += 1;
});
</code>```

Body:
could you please help me with adding new column into table. Table has thead and tbody, I need to add column with heading (th) "Details", and each row (that is td) needs to have link inside.for example Link. New column should be inserted after second column.

                    Title
                    Author
                    # comments
                    Publication date
                    Updated
                    Type
                    Section
                    Language

                    <input type="checkbox">
                    Lorem ipsum #1
                    Name
                    3 comments
                    2014-05-07 15:00
                    2014-05-07 15:00
                    Article
                    Standard
                    English

                    <input type="checkbox">
                    Lorem ipsum #2
                    Name
                    3 comments
                    2014-05-07 14:00

                    Article
                    Standard
                    English

                    <input type="checkbox">
                    Lorem ipsum #3
                    Name

                    2014-05-07 13:00

                    Forum post
                    Forum
                    Polish

                    <input type="checkbox">
                    Lorem ipsum #4
                    Name
                    25 comments
                    2014-05-07 12:00
                    2014-05-07 15:00
                    Blog post
                    Blog
                    French

                    <input type="checkbox">
                    Lorem ipsum #5
                    Name
                    35 comments
                    2014-05-07 11:00
                    2014-05-07 15:00
                    Blog post
                    Blog
                    English


问:
Excluding items selectively from Sitecore's Lucene search index - works when rebuilding with IndexViewer, but not when using Sitecore's built-in tools
On a site powered by Sitecore 6.2, I need to give the user the ability to selectively exclude items from search results.

To accomplish this, I have added a checkbox field entitled "Include in Search Results", and I created a custom database crawler to check that field's value:

~\App_Config\Include\Search Indexes\Website.config:

```<code><search>
  <configuration type="Sitecore.Search.SearchConfiguration, Sitecore.Kernel" singleInstance="true">
    <indexes hint="list:AddIndex">
      <index id="website" singleInstance="true" type="Sitecore.Search.Index, Sitecore.Kernel">
        ...

        <locations hint="list:AddCrawler">
          <master type="MyProject.Lib.Search.Indexing.CustomCrawler, MyProject">
            ...
          </master>

          <!-- Similar entry for web database. -->
        </locations>
      </index>
    </indexes>
  </configuration>
</search>
</code>```

~\Lib\Search\Indexing\CustomCrawler.cs:

```<code>using Lucene.Net.Documents;
using Sitecore.Search.Crawlers;
using Sitecore.Data.Items;

namespace MyProject.Lib.Search.Indexing
{
  public class CustomCrawler : DatabaseCrawler
  {
    /// <summary>
    ///   Determines if the item should be included in the index.
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    protected override bool IsMatch(Item item)
    {
      if (item["include in search results"] != "1")
      {
        return false;
      }

      return base.IsMatch(item);
    }
  }
}
</code>```

What's interesting is, if I rebuild the index using the Index Viewer application, everything behaves as normal.  Items whose "Include in Search Results" checkbox is not checked will not be included in the search index.

However, when I use the search index rebuilder in the Sitecore Control Panel application or when the IndexingManager auto-updates the search index, all items are included, regardless of the state of their "Include in Search Results" checkbox.

I've also set numerous breakpoints in my custom crawler class, and the application never hits any of them when I rebuild the search index using the built-in indexer.  When I use Index Viewer, it does hit all the breakpoints I've set.

How do I get Sitecore's built-in indexing processes to respect my "Include in Search Results" checkbox?

答:
I spoke with Alex Shyba yesterday, and we were able to figure out what was going on.  There were a couple of problems with my configuration that was preventing everything from working correctly:

As Seth noted, there are two distinct search APIs in Sitecore.  My configuration file was using both of them.  To use the newer API, only the sitecore/search/configuration section needs to be set up (In addition to what I posted in my OP, I was also adding indexes in sitecore/indexes and sitecore/databases/database/indexes, which is not correct).

Instead of overriding IsMatch(), I should have been overriding AddItem().  Because of the way Lucene works, you can't update a document in place; instead, you have to first delete it and then add the updated version.

When Sitecore.Search.Crawlers.DatabaseCrawler.UpdateItem() runs, it checks IsMatch() to see if it should delete and re-add the item.  If IsMatch() returns false, the item won't be removed from the index even if it shouldn't be there in the first place.

By overriding AddItem(), I was able to instruct the crawler whether the item should be added to the index after its existing documents had already been removed.  Here is what the updated class looks like:

~\Lib\Search\Indexing\CustomCrawler.cs:

```<code>using Sitecore.Data.Items;
using Sitecore.Search;
using Sitecore.Search.Crawlers;

namespace MyProject.Lib.Search.Indexing
{
  public class CustomCrawler : DatabaseCrawler
  {
    protected override void AddItem(Item item, IndexUpdateContext context)
    {
      if (item["include in search results"] == "1")
      {
        base.AddItem(item, context);
      }
    }
  }
}
</code>```

Alex also pointed out that some of my scalability settings were incorrect.  Specifically:

The InstanceName setting was empty, which can cause problems on ephemeral (cloud) instances where the machine name might change between executions.  We changed this setting on each instance to have a constant and distinct value (e.g., CMS and CD).

The Indexing.ServerSpecificProperties setting needs to be true so that each instance maintains its own record of when it last updated its search index.

The EnableEventQueues setting needs to be true to prevent race conditions between the search indexing and cache flush processes.

When in development, the Indexing.UpdateInterval should be set to a relatively small value (e.g., 00:00:15).  This is not great for production environments, but it cuts down on the amount of waiting you have to do when troubleshooting search indexing problems.

Make sure the history engine is turned on for each web database, including remote publishing targets:

```<code><database id="production">
  <Engines.HistoryEngine.Storage>
    <obj type="Sitecore.Data.$(database).$(database)HistoryStorage, Sitecore.Kernel">
      <param connectionStringName="$(id)" />
      <EntryLifeTime>30.00:00:00</EntryLifeTime>
    </obj>
  </Engines.HistoryEngine.Storage>
  <Engines.HistoryEngine.SaveDotNetCallStack>false</Engines.HistoryEngine.SaveDotNetCallStack>
</database>
</code>```

To manually rebuild the search indexes on CD instances, since there is no access to the Sitecore backend, I also installed RebuildDatabaseCrawlers.aspx (from this article).

Body:
On a site powered by Sitecore 6.2, I need to give the user the ability to selectively exclude items from search results.

To accomplish this, I have added a checkbox field entitled "Include in Search Results", and I created a custom database crawler to check that field's value:

~\App_Config\Include\Search Indexes\Website.config:

<search>
  <configuration type="Sitecore.Search.SearchConfiguration, Sitecore.Kernel" singleInstance="true">
    <indexes hint="list:AddIndex">
      <index id="website" singleInstance="true" type="Sitecore.Search.Index, Sitecore.Kernel">
        ...

        <locations hint="list:AddCrawler">
          <master type="MyProject.Lib.Search.Indexing.CustomCrawler, MyProject">
            ...
          </master>

        </locations>
      </index>
    </indexes>
  </configuration>
</search>

~\Lib\Search\Indexing\CustomCrawler.cs:

using Lucene.Net.Documents;
using Sitecore.Search.Crawlers;
using Sitecore.Data.Items;

namespace MyProject.Lib.Search.Indexing
{
  public class CustomCrawler : DatabaseCrawler
  {
    ///
    ///   Determines if the item should be included in the index.
    ///
    /// <param name="item"></param>
    /// <returns></returns>
    protected override bool IsMatch(Item item)
    {
      if (item["include in search results"] != "1")
      {
        return false;
      }

      return base.IsMatch(item);
    }
  }
}

What's interesting is, if I rebuild the index using the Index Viewer application, everything behaves as normal.  Items whose "Include in Search Results" checkbox is not checked will not be included in the search index.

However, when I use the search index rebuilder in the Sitecore Control Panel application or when the IndexingManager auto-updates the search index, all items are included, regardless of the state of their "Include in Search Results" checkbox.

I've also set numerous breakpoints in my custom crawler class, and the application never hits any of them when I rebuild the search index using the built-in indexer.  When I use Index Viewer, it does hit all the breakpoints I've set.

How do I get Sitecore's built-in indexing processes to respect my "Include in Search Results" checkbox?

Body:
I spoke with Alex Shyba yesterday, and we were able to figure out what was going on.  There were a couple of problems with my configuration that was preventing everything from working correctly:

As Seth noted, there are two distinct search APIs in Sitecore.  My configuration file was using both of them.  To use the newer API, only the sitecore/search/configuration section needs to be set up (In addition to what I posted in my OP, I was also adding indexes in sitecore/indexes and sitecore/databases/database/indexes, which is not correct).

Instead of overriding IsMatch(), I should have been overriding AddItem().  Because of the way Lucene works, you can't update a document in place; instead, you have to first delete it and then add the updated version.

When Sitecore.Search.Crawlers.DatabaseCrawler.UpdateItem() runs, it checks IsMatch() to see if it should delete and re-add the item.  If IsMatch() returns false, the item won't be removed from the index even if it shouldn't be there in the first place.

By overriding AddItem(), I was able to instruct the crawler whether the item should be added to the index after its existing documents had already been removed.  Here is what the updated class looks like:

~\Lib\Search\Indexing\CustomCrawler.cs:

using Sitecore.Data.Items;
using Sitecore.Search;
using Sitecore.Search.Crawlers;

namespace MyProject.Lib.Search.Indexing
{
  public class CustomCrawler : DatabaseCrawler
  {
    protected override void AddItem(Item item, IndexUpdateContext context)
    {
      if (item["include in search results"] == "1")
      {
        base.AddItem(item, context);
      }
    }
  }
}

Alex also pointed out that some of my scalability settings were incorrect.  Specifically:

The InstanceName setting was empty, which can cause problems on ephemeral (cloud) instances where the machine name might change between executions.  We changed this setting on each instance to have a constant and distinct value (e.g., CMS and CD).

The Indexing.ServerSpecificProperties setting needs to be true so that each instance maintains its own record of when it last updated its search index.

The EnableEventQueues setting needs to be true to prevent race conditions between the search indexing and cache flush processes.

When in development, the Indexing.UpdateInterval should be set to a relatively small value (e.g., 00:00:15).  This is not great for production environments, but it cuts down on the amount of waiting you have to do when troubleshooting search indexing problems.

Make sure the history engine is turned on for each web database, including remote publishing targets:

<database id="production">
  <Engines.HistoryEngine.Storage>
    <obj type="Sitecore.Data.$(database).$(database)HistoryStorage, Sitecore.Kernel">
      <param connectionStringName="$(id)" />
      <EntryLifeTime>30.00:00:00</EntryLifeTime>
    </obj>
  </Engines.HistoryEngine.Storage>
  <Engines.HistoryEngine.SaveDotNetCallStack>false</Engines.HistoryEngine.SaveDotNetCallStack>
</database>

To manually rebuild the search indexes on CD instances, since there is no access to the Sitecore backend, I also installed RebuildDatabaseCrawlers.aspx (from this article).


问:
PHP: basename not working as expected on special character
Here's my code:

```<code>$url = "https://de.wikipedia.org/wiki/…_und_wenn_der_letzte_Reifen_platzt";

$base = basename($url);
echo $base . "<br>";

$url2 = urlencode($base);
echo $url2 . "<br>";

$url = dirname($url) . "/" . $url2;

echo $url;
$aHeader = @get_headers($url);

echo "```" . print_r($aHeader,true) . "```";
</code>```

It works fine on my local machine (running Xampp with PHP v7.3.12) - $base encodes as %E2%80%A6_und_wenn_der_letzte_Reifen_platzt

But when running on my server, $base will encode as _und_wenn_der_letzte_Reifen_platzt which is wrong and will result in an error 404 (the server is running on PHP 7.2.24).

Any ideas what is causing this behaviour? Both scripts are encoded in UTF-8.

答:
I could be a bug related to the basename function. Because if you mix … char with letters in und_wenn_der_letzte_Reifen_platzt part, if works as expected. You can try to upgrade your PHP on your server matching your local version if possible.

If you can't do this, there is always a better way to achieve this with regular expressions.

```<code>$re = '/.+\/(.*)/m';
$str = 'https://de.wikipedia.org/wiki/…_und_wenn_der_letzte_Reifen_platzt';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$base = $matches[0][1];
echo $base . "<br>";

$url2 = rawurlencode($base);
echo $url2 . "<br>";
</code>```

Body:
Here's my code:

$url = "https://de.wikipedia.org/wiki/…_und_wenn_der_letzte_Reifen_platzt";

$base = basename($url);
echo $base . "
";

$url2 = urlencode($base);
echo $url2 . "
";

$url = dirname($url) . "/" . $url2;

echo $url;
$aHeader = @get_headers($url);

echo "
" . print_r($aHeader,true) . "
";

It works fine on my local machine (running Xampp with PHP v7.3.12) - $base encodes as %E2%80%A6_und_wenn_der_letzte_Reifen_platzt

But when running on my server, $base will encode as _und_wenn_der_letzte_Reifen_platzt which is wrong and will result in an error 404 (the server is running on PHP 7.2.24).

Any ideas what is causing this behaviour? Both scripts are encoded in UTF-8.

Body:
I could be a bug related to the basename function. Because if you mix … char with letters in und_wenn_der_letzte_Reifen_platzt part, if works as expected. You can try to upgrade your PHP on your server matching your local version if possible.

If you can't do this, there is always a better way to achieve this with regular expressions.

$re = '/.+\/(.*)/m';
$str = 'https://de.wikipedia.org/wiki/…_und_wenn_der_letzte_Reifen_platzt';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$base = $matches[0][1];
echo $base . "<br>";

$url2 = rawurlencode($base);
echo $url2 . "<br>";


问:
symbolic link / alias to a database
I want to use several versions of databases (with tables, views, procedures) within one instance of MS SQL server. Let's say I have these databases:

db_dev1

db_dev2

db_dev3

...

db_dev10

I always have a current / stable version and want to create a kind of "link". Currently, "db_dev2" is stable and I want a "link" or alias "db_stable" and use all the tables, procedures,... of "db_dev2" but using the name "db_stable". In a filesystem like NTFS or EXT4 I would create a symbolic link. How can I do it within MS SQL server? When developments continues I would change the "link" to "db_dev3" and so on. Doing this I do not have to change the SQL code that access this database(s).

A workaround with a "hardlink" -- a copy of "db_dev2" to be renamed as "db_stable" -- would be no good solution for me since the databases are quite big.

答:
You can use synonyms. Unfortunately you cannot create a synonym for a database.
But you can create a "empty" database db_stable that has synonyms for all the objects.
Just write some script to create/alter the synonyms for every object.</p>

Title: symbolic link / alias to a database


问:
php select statement dependent on variables existing
I am trying to set up a filter system for a small shop I am developing. Basically, I am working the results off a list of variables. the page, products.php if there is no querystring will show all products. However, if there is a variable present I want it to alter the select statement where necessary.

however, I am having problems filtering. If i use the AND statement for all variables it does not filter appropriately neither does the OR. So if i wanted black size 5 shoes it would show all size fives regardless of color.

Is there a better approach to take with this as is becoming a fair old head scratcher!

```<code>if ($queryString == NULL){
    $query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
GROUP BY store_products.prod_id";
}else{
        $query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
where store_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat' GROUP BY store_products.prod_id";
}
</code>```

example variable string

```<code>products.php?sale=&cat_id=1&size=&color=Yellow
</code>```

答:
```<code>$query = "SELECT * FROM store_products
    JOIN store_cat on store_products.cat=store_cat.cat_id
    JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
    JOIN prod_color on store_products.prod_id=prod_color.product_id ";

if {$queryString != NULL){
$query .= " WHERE tore_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat'"
}
$query .=" GROUP BY store_products.prod_id;"
</code>```

Then you execute your Query :)

Body:
I am trying to set up a filter system for a small shop I am developing. Basically, I am working the results off a list of variables. the page, products.php if there is no querystring will show all products. However, if there is a variable present I want it to alter the select statement where necessary.

however, I am having problems filtering. If i use the AND statement for all variables it does not filter appropriately neither does the OR. So if i wanted black size 5 shoes it would show all size fives regardless of color.

Is there a better approach to take with this as is becoming a fair old head scratcher!

if ($queryString == NULL){
    $query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
GROUP BY store_products.prod_id";
}else{
        $query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
where store_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat' GROUP BY store_products.prod_id";
}

example variable string

products.php?sale=&cat_id=1&size=&color=Yellow

Body:
$query = "SELECT * FROM store_products
    JOIN store_cat on store_products.cat=store_cat.cat_id
    JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
    JOIN prod_color on store_products.prod_id=prod_color.product_id ";

if {$queryString != NULL){
$query .= " WHERE tore_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat'"
}
$query .=" GROUP BY store_products.prod_id;"

Then you execute your Query :)


问:
Why does grep with the -c option always show 0 over ssh
I have a script on three different servers. The basics are that script checks for a certain file on its system and if the file is not there then it will ssh to the other servers and run the same script. The check is run via;

If [[ $(ls ${folder} | grep -c ${file}) -gt 0 ]]; then "do stuff with the files"; else "ssh to other server and check again"; fi

It wasnt giving output when the information was on a remote server. So I ran the check on a server I knew had the files and it worked. However when i would  try and run it remotely, the file count would be 0.

I changed it from grep to wc -l and then it worked. I'm wondering if anybody knows why grep -c works locally but with ssh

答:
It 'if' doesn't work like that.
If you want to check the existence of a file, you must use this:</p>

```<code>[ -f ${file} ]
</code>```

Body:
It 'if' doesn't work like that.
If you want to check the existence of a file, you must use this:

[ -f ${file} ]


问:
How to create empty temporary table?
Need to create empty temporary table, but that not depends any query result yet, but I need only structure. (then, according to some logic, will be different data inserted into this).

```<code>begin;
CREATE TEMP TABLE my_tmp_table ON COMMIT DROP (
    col1 int,
    col2 numeric,
    col3 text
);
...
</code>```

throws syntax error

So is this way (which looks bit "tricky") only correct way:

```<code>begin;
CREATE TEMP TABLE my_tmp_table ON COMMIT DROP
AS
SELECT
1::INT as col1,
1::numeric as col2,
''::text as col3
WHERE false;
...
</code>```

?

答:
As documented in the manual the ON COMMIT option needs to be after the table definition:

```<code>CREATE TEMP TABLE my_tmp_table
(
  col1 int,
  col2 numeric,
  col3 text
)
ON COMMIT DROP; --<< here
</code>```

Title: How to create empty temporary table?

Body:
Need to create empty temporary table, but that not depends any query result yet, but I need only structure. (then, according to some logic, will be different data inserted into this).

begin;
CREATE TEMP TABLE my_tmp_table ON COMMIT DROP (
    col1 int,
    col2 numeric,
    col3 text
);
...

throws syntax error

So is this way (which looks bit "tricky") only correct way:

begin;
CREATE TEMP TABLE my_tmp_table ON COMMIT DROP
AS
SELECT
1::INT as col1,
1::numeric as col2,
''::text as col3
WHERE false;
...

?

Body:
As documented in the manual the ON COMMIT option needs to be after the table definition:

CREATE TEMP TABLE my_tmp_table
(
  col1 int,
  col2 numeric,
  col3 text
)
ON COMMIT DROP; --<< here


问:
Flutter ScrollController is throwing exception
I have a ScrollController attached to a Listview, but when i scroll it throws an Exception:

```<code>@override
  initState() {
    super.initState();

    _mainCategoriesScrollController = ScrollController();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _mainCategoriesScrollController
          .addListener(_mainCatergoriesScrollListener());
    });
  }

_mainCatergoriesScrollListener() {
    if (_mainCategoriesScrollController.offset >=
            _mainCategoriesScrollController.position.maxScrollExtent &&
        !_mainCategoriesScrollController.position.outOfRange) {
      print("reach the bottom");
    }
    if (_mainCategoriesScrollController.offset <=
            _mainCategoriesScrollController.position.minScrollExtent &&
        !_mainCategoriesScrollController.position.outOfRange) {
      print("reach the top");
    }
  }
</code>```

and the build method

```<code> @override
  Widget build(BuildContext context) {
    _setCurrentMainCategory();
    SystemChrome.setEnabledSystemUIOverlays([]);
    return Container(
        child: Column /*or Column*/ (
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
                flex: 9,
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        flex: 3,
                        child: ListView.builder(
                            controller: _mainCategoriesScrollController,
                            shrinkWrap: true,
                            itemCount: _mainCategories.length,
                            itemBuilder: (context, index) {
                              return MainCategoryEntry(
                                mainCategory: _mainCategories[index],
                                mainCategorySelected: () {
                                  MyApp.setActivity(context);
                                  setState(() {
                                    currentMainCategory =
                                        _mainCategories[index];
                                  });
                                },
                                isSelected: _mainCategories[index] ==
                                    currentMainCategory,
                              );
                            }),
                      ),
</code>```

The exception is the follwing:

════════ Exception caught by foundation library ════════════════════════════════
    The following NoSuchMethodError was thrown while dispatching notifications for ScrollController:
    The method 'call' was called on null.
    Receiver: null
    Tried calling: call()

```<code>When the exception was thrown, this was the stack
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:53:5)
#1      ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:207
#2      ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:207
#3      ScrollPosition.notifyListeners
package:flutter/…/widgets/scroll_position.dart:775
#4      ScrollPosition.setPixels
package:flutter/…/widgets/scroll_position.dart:244
...
The ScrollController sending notification was: ScrollController#7153b(one client, offset 0.7)
════════════════════════════════════════════════════════════════════════════════
</code>```

Can someone tell me what im doing wrong?
Many thanks!

答:
Instead of adding _mainCategoriesScrollListener method to the listener, this line seems to call the method:

```<code>_mainCategoriesScrollController.addListener(_mainCatergoriesScrollListener());
</code>```

I guess the error occurs when you try to access _mainCategoriesScrollController methods when the client isn't even assigned.

Even when you try to add a post-frame callback, the method _mainCatergoriesScrollListener() still gets called in initState() as you are calling it instead of adding it to the listener.

This might be the cause of the error.

Try changing it to:

```<code>_mainCategoriesScrollController.addListener(_mainCatergoriesScrollListener);
</code>```

or

```<code>_mainCategoriesScrollController.addListener(() => _mainCatergoriesScrollListener());
</code>```

Body:
I have a ScrollController attached to a Listview, but when i scroll it throws an Exception:

@override
  initState() {
    super.initState();

    _mainCategoriesScrollController = ScrollController();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _mainCategoriesScrollController
          .addListener(_mainCatergoriesScrollListener());
    });
  }

_mainCatergoriesScrollListener() {
    if (_mainCategoriesScrollController.offset >=
            _mainCategoriesScrollController.position.maxScrollExtent &&
        !_mainCategoriesScrollController.position.outOfRange) {
      print("reach the bottom");
    }
    if (_mainCategoriesScrollController.offset <=
            _mainCategoriesScrollController.position.minScrollExtent &&
        !_mainCategoriesScrollController.position.outOfRange) {
      print("reach the top");
    }
  }

and the build method

 @override
  Widget build(BuildContext context) {
    _setCurrentMainCategory();
    SystemChrome.setEnabledSystemUIOverlays([]);
    return Container(
        child: Column /*or Column*/ (
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
                flex: 9,
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        flex: 3,
                        child: ListView.builder(
                            controller: _mainCategoriesScrollController,
                            shrinkWrap: true,
                            itemCount: _mainCategories.length,
                            itemBuilder: (context, index) {
                              return MainCategoryEntry(
                                mainCategory: _mainCategories[index],
                                mainCategorySelected: () {
                                  MyApp.setActivity(context);
                                  setState(() {
                                    currentMainCategory =
                                        _mainCategories[index];
                                  });
                                },
                                isSelected: _mainCategories[index] ==
                                    currentMainCategory,
                              );
                            }),
                      ),

The exception is the follwing:

════════ Exception caught by foundation library ════════════════════════════════
    The following NoSuchMethodError was thrown while dispatching notifications for ScrollController:
    The method 'call' was called on null.
    Receiver: null
    Tried calling: call()

When the exception was thrown, this was the stack
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:53:5)
#1      ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:207
#2      ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:207
#3      ScrollPosition.notifyListeners
package:flutter/…/widgets/scroll_position.dart:775
#4      ScrollPosition.setPixels
package:flutter/…/widgets/scroll_position.dart:244
...
The ScrollController sending notification was: ScrollController#7153b(one client, offset 0.7)
════════════════════════════════════════════════════════════════════════════════

Can someone tell me what im doing wrong?
Many thanks!

Body:
Instead of adding _mainCategoriesScrollListener method to the listener, this line seems to call the method:

_mainCategoriesScrollController.addListener(_mainCatergoriesScrollListener());

I guess the error occurs when you try to access _mainCategoriesScrollController methods when the client isn't even assigned.

Even when you try to add a post-frame callback, the method _mainCatergoriesScrollListener() still gets called in initState() as you are calling it instead of adding it to the listener.

This might be the cause of the error.

Try changing it to:

_mainCategoriesScrollController.addListener(_mainCatergoriesScrollListener);

or

_mainCategoriesScrollController.addListener(() => _mainCatergoriesScrollListener());


问:
Displaying tooltips during mousedrag
I'd like to display a tooltip while a user is dragging a mouse to create a rectangle.  The contents of the tooltip would be an indication of the size of the rectangle.  I don't know how to get the tooltip to display when the mouse button is down, and to stop displaying when the mouse button is up.

The application is written in C++ on Windows, using Visual Studio 2005, no MFC, no ATL.

答: Try sending a TTM_ACTIVATE message to turn the tooltip window on or off.

Title: Displaying tooltips during mousedrag


问:
Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
When I am trying to load AWS credentials in my project it gives back an error.

When using credentials in plain text everything works good but when I am trying to use environment variables it's not working.

Error message. :

```<code>Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
</code>```

Here is my tried code :

```<code>const AWS = require('aws-sdk');

const SESConfig = {
    apiVersion: "2010-12-01",
    accessKeyId: process.env.AWS_SECRET_KEY,
    accessSecretKey: process.env.AWS_SECRET_KEY,
    region: "us-east-1"
}
AWS.config.update(SESConfig);
var sns = new AWS.SNS()
var sns = new AWS.SNS();

function sendSMS(to_number, message, cb) {

    sns.publish({
        Message: message,
        Subject: 'Admin',
        PhoneNumber:to_number
    }, cb);

  }

  // Example
  const PhoneNumberArray = ['any mobile number']
  PhoneNumberArray.forEach(number => {
    sendSMS(number, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", (err, result)=>{
        console.log("RESULTS: ",err,result)
      })
  })

</code>```

答:
By default, the SDK detects AWS credentials set in your environment and uses them to sign requests to AWS. That way you don’t need to manage credentials in your applications.

Unix:

```<code>$ export AWS_ACCESS_KEY_ID="your_key_id"
$ export AWS_SECRET_ACCESS_KEY="your_secret_key"
</code>```

Windows:

```<code>SET AWS_ACCESS_KEY_ID="your_key_id"
SET AWS_SECRET_ACCESS_KEY="your_secret_key"
</code>```

Powershell:

```<code>$Env:AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
$Env:AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"
</code>```

you can also add $ export AWS_SESSION_TOKEN='your_token' (optional)

See aws-sdk for more details.

Otherwise you can create a ~/.aws/credentials file and add:

```<code>[default]
aws_access_key_id = <YOUR_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>
</code>```

See aws for more details.

Body:
When I am trying to load AWS credentials in my project it gives back an error.

When using credentials in plain text everything works good but when I am trying to use environment variables it's not working.

Error message. :

Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1

Here is my tried code :

const AWS = require('aws-sdk');

const SESConfig = {
    apiVersion: "2010-12-01",
    accessKeyId: process.env.AWS_SECRET_KEY,
    accessSecretKey: process.env.AWS_SECRET_KEY,
    region: "us-east-1"
}
AWS.config.update(SESConfig);
var sns = new AWS.SNS()
var sns = new AWS.SNS();

function sendSMS(to_number, message, cb) {

    sns.publish({
        Message: message,
        Subject: 'Admin',
        PhoneNumber:to_number
    }, cb);

  }

  // Example
  const PhoneNumberArray = ['any mobile number']
  PhoneNumberArray.forEach(number => {
    sendSMS(number, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", (err, result)=>{
        console.log("RESULTS: ",err,result)
      })
  })

Body:
By default, the SDK detects AWS credentials set in your environment and uses them to sign requests to AWS. That way you don’t need to manage credentials in your applications.

Unix:

$ export AWS_ACCESS_KEY_ID="your_key_id"
$ export AWS_SECRET_ACCESS_KEY="your_secret_key"

Windows:

SET AWS_ACCESS_KEY_ID="your_key_id"
SET AWS_SECRET_ACCESS_KEY="your_secret_key"

Powershell:

$Env:AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
$Env:AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"

you can also add $ export AWS_SESSION_TOKEN='your_token' (optional)

See aws-sdk for more details.

Otherwise you can create a ~/.aws/credentials file and add:

[default]
aws_access_key_id = <YOUR_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>

See aws for more details.


问:
Bind viewmodel to recyclerview item.xml with databinding, android?
I want to bind data on adapter from viewmodel in xml layout file

This is my fragment class.

```<code>class NotificationFragment : Fragment() {
var customeProgressDialog: CustomeProgressDialog? = null
private val appPreferences: AppPreference by inject()
private val notificationViewModel: NotificationViewModel by viewModel()
private lateinit var binding: FragmentNotificationBinding

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = FragmentNotificationBinding.inflate(inflater, container, false)
    return binding.getRoot()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.notification.layoutManager=LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    customeProgressDialog = CustomeProgressDialog(activity)
    notificationViewModel.notifications(
        appPreferences.getUsername(),
        appPreferences.getPassword(),
        appPreferences.getUserId()
    )
    initObservables()
}

private fun initObservables() {
    notificationViewModel.progressDialog?.observe(this, Observer {
        if (it!!) customeProgressDialog?.show() else customeProgressDialog?.dismiss()
    })
    notificationViewModel.apiResponse?.observe(
        viewLifecycleOwner,
        androidx.lifecycle.Observer { response ->
            if (response.dataList != null) {
                var notificationAdapter = NotificationAdapter(response.dataList as List<Data>)
                notificationAdapter.notifyDataSetChanged()
                binding.notification.adapter = notificationAdapter
            }
        })
}
}
</code>```

My viewmodel

```<code>class NotificationViewModel(networkCall: NetworkCall) : ViewModel(),
Callback<ApiResponse> {
var progressDialog: SingleLiveEvent<Boolean>? = null
var apiResponse: MutableLiveData<ApiResponse>? = null
var networkCall: NetworkCall;
init {
    progressDialog = SingleLiveEvent<Boolean>()
    apiResponse = MutableLiveData<ApiResponse>()
    this.networkCall = networkCall
}

fun notifications(username: String?, password: String?, userId: String?) {
    progressDialog?.value = true
    val apiPost = ApiPost()
    apiPost.userName = username
    apiPost.password = password
    apiPost.UserId = userId
    apiPost.FileType = NetworkConstant.FILE_TYPE_NOT
    networkCall.getPDF(apiPost).enqueue(this)
}

override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
    progressDialog?.value = false
}

override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
    progressDialog?.value = false
    apiResponse?.value = response.body()
}
}
</code>```

The adapter class

```<code>lass NotificationAdapter(private val list: List<Data>) :
RecyclerView.Adapter<NotificationAdapter.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val view = inflater.inflate(R.layout.element_list, parent, false)
    return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val movie: Data = list[position]
    holder.bind(movie)
    holder.itemView.setOnClickListener {

        if (!TextUtils.isEmpty(movie.filePath)) {
            try {
                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(movie.filePath))
                holder.itemView.context.startActivity(browserIntent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }
}

override fun getItemCount(): Int = list.size

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(movie: Data) {
        with(itemView) {
            tv_notifi.text = movie.displayName
            tv_date.text = movie.UpdatedDate
            if (movie.description != null) {
                tv_brief.text = movie.description
                tv_brief.visibility = View.VISIBLE
            }
        }
    }
}

}
</code>```

This is my item xml layout

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="viewmodel"
        type="com.mountmeru.viewmodel.NotificationViewModel" />
</data>

<androidx.cardview.widget.CardView
    android:id="@+id/main_cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/main_cardrl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/rl_newsdate"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.3">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_notifi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:maxLines="2"
                android:text="hey i am notification text"
                android:textColor="@android:color/black"
                android:textSize="16sp" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_brief"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_notifi"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:visibility="gone" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_brief"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="2dp"
                android:layout_marginRight="10dp"
                android:maxLines="1"
                android:text="hey i am date"
                android:textColor="@color/inactive_text"
                android:textSize="14sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/rl_newsdate"
            android:layout_weight="0.7"
            android:padding="5dp">

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/iv_notifi"
                android:layout_width="match_parent"
                android:layout_height="75dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:src="@drawable/mer" />

        </RelativeLayout>

    </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.cardview.widget.CardView>
</layout>
</code>```

I was able to do the binding for the fragment but for adapter I am unsure how to proceed.

答:
If I understand your question correctly, you want to pass data to your adapter inside xml. For this, you will need to write custom binding adapter for your RecyclerView.
This link has all you need.
https://android.jlelse.eu/how-to-bind-a-list-of-items-to-a-recyclerview-with-android-data-binding-1bd08b4796b4</p>

Body:
I want to bind data on adapter from viewmodel in xml layout file

This is my fragment class.

class NotificationFragment : Fragment() {
var customeProgressDialog: CustomeProgressDialog? = null
private val appPreferences: AppPreference by inject()
private val notificationViewModel: NotificationViewModel by viewModel()
private lateinit var binding: FragmentNotificationBinding

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = FragmentNotificationBinding.inflate(inflater, container, false)
    return binding.getRoot()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.notification.layoutManager=LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    customeProgressDialog = CustomeProgressDialog(activity)
    notificationViewModel.notifications(
        appPreferences.getUsername(),
        appPreferences.getPassword(),
        appPreferences.getUserId()
    )
    initObservables()
}

private fun initObservables() {
    notificationViewModel.progressDialog?.observe(this, Observer {
        if (it!!) customeProgressDialog?.show() else customeProgressDialog?.dismiss()
    })
    notificationViewModel.apiResponse?.observe(
        viewLifecycleOwner,
        androidx.lifecycle.Observer { response ->
            if (response.dataList != null) {
                var notificationAdapter = NotificationAdapter(response.dataList as List<Data>)
                notificationAdapter.notifyDataSetChanged()
                binding.notification.adapter = notificationAdapter
            }
        })
}
}

My viewmodel

class NotificationViewModel(networkCall: NetworkCall) : ViewModel(),
Callback<ApiResponse> {
var progressDialog: SingleLiveEvent<Boolean>? = null
var apiResponse: MutableLiveData<ApiResponse>? = null
var networkCall: NetworkCall;
init {
    progressDialog = SingleLiveEvent<Boolean>()
    apiResponse = MutableLiveData<ApiResponse>()
    this.networkCall = networkCall
}

fun notifications(username: String?, password: String?, userId: String?) {
    progressDialog?.value = true
    val apiPost = ApiPost()
    apiPost.userName = username
    apiPost.password = password
    apiPost.UserId = userId
    apiPost.FileType = NetworkConstant.FILE_TYPE_NOT
    networkCall.getPDF(apiPost).enqueue(this)
}

override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
    progressDialog?.value = false
}

override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
    progressDialog?.value = false
    apiResponse?.value = response.body()
}
}

The adapter class

lass NotificationAdapter(private val list: List<Data>) :
RecyclerView.Adapter<NotificationAdapter.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val view = inflater.inflate(R.layout.element_list, parent, false)
    return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val movie: Data = list[position]
    holder.bind(movie)
    holder.itemView.setOnClickListener {

        if (!TextUtils.isEmpty(movie.filePath)) {
            try {
                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(movie.filePath))
                holder.itemView.context.startActivity(browserIntent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }
}

override fun getItemCount(): Int = list.size

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(movie: Data) {
        with(itemView) {
            tv_notifi.text = movie.displayName
            tv_date.text = movie.UpdatedDate
            if (movie.description != null) {
                tv_brief.text = movie.description
                tv_brief.visibility = View.VISIBLE
            }
        }
    }
}

}

This is my item xml layout

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="viewmodel"
        type="com.mountmeru.viewmodel.NotificationViewModel" />
</data>

<androidx.cardview.widget.CardView
    android:id="@+id/main_cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/main_cardrl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/rl_newsdate"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.3">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_notifi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:maxLines="2"
                android:text="hey i am notification text"
                android:textColor="@android:color/black"
                android:textSize="16sp" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_brief"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_notifi"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:visibility="gone" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_brief"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="2dp"
                android:layout_marginRight="10dp"
                android:maxLines="1"
                android:text="hey i am date"
                android:textColor="@color/inactive_text"
                android:textSize="14sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/rl_newsdate"
            android:layout_weight="0.7"
            android:padding="5dp">

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/iv_notifi"
                android:layout_width="match_parent"
                android:layout_height="75dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:src="@drawable/mer" />

        </RelativeLayout>

    </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.cardview.widget.CardView>
</layout>

I was able to do the binding for the fragment but for adapter I am unsure how to proceed.


问:
Non breaking spaces are rendered as regular space in vue template
When I used   in Vue template, in browser they are rendered as regular space.

```<code><template>
  <p>
     sample text in sample text
     <strong>lorem ipsum</strong>
   </p>
</template>
</code>```

Final render in browser looks like:

sample text in sample text lorem ipsum

My question is how to write non breaking spaces in template?

答:
```<code><p>
 sample text in{{'\xa0'}}sample text
 <strong>lorem ipsum</strong>
<p>
</code>```

Try to use the JavaScript escape code and not the HTML entity.

Body:
When I used   in Vue template, in browser they are rendered as regular space.

<template>

     sample text in sample text
     lorem ipsum

</template>

Final render in browser looks like:

sample text in sample text lorem ipsum

My question is how to write non breaking spaces in template?

Body:
<p>
 sample text in{{'\xa0'}}sample text
 <strong>lorem ipsum</strong>
<p>

Try to use the JavaScript escape code and not the HTML entity.


问:
Retrieve aws s3 bucket policy in json pretty format
Retrieving AWS S3 bucket policy in pretty json format.</p>

```<code>aws \
--profile AWS_PROFILE  \
s3api get-bucket-policy \
--bucket AWS_S3_BUCKET \
--query Policy --output text | jq .
</code>```

答:
You can try the following:

```<code>aws s3api get-bucket-policy \
    --bucket <AWS_S3_BUCKET> \
    --query Policy --output text --profile la | jq
</code>```

Example output:

```<code>{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPublicRead",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::<bucket-name>/*"
    }
  ]
}

</code>```

Body:
Retrieving AWS S3 bucket policy in pretty json format.

aws \
--profile AWS_PROFILE  \
s3api get-bucket-policy \
--bucket AWS_S3_BUCKET \
--query Policy --output text | jq .

Body:
You can try the following:

aws s3api get-bucket-policy \
    --bucket <AWS_S3_BUCKET> \
    --query Policy --output text --profile la | jq

Example output:

{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPublicRead",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::<bucket-name>/*"
    }
  ]
}


问:
httpParams remove undefined params
I need to send params in my URL to get filtered data from the server.

I set params like this

```<code>const queryParams = new HttpParams(
      {
        fromObject: {
          page: this.paginator.pageIndex.toString(),
          pageSize: this.paginator.pageSize.toString(),
          search: this.searchKey,
          sortBy: this.selectedFilterByStatusValue,
          sortByType: this.selectedFilterSortByValue
        }
      });
</code>```

And in my service

```<code> getData(params: HttpParams) {
    return this.apiService.get<IResponseList<IData>>(`${this.url}/list`, params);
  }
</code>```

Problem is, when some filter is not selected, because I don't need them, and it is set like undefined, but this is not correct... I need to remove undefined params.

Here is console.log for queryParams

```<code>cloneFrom: null
encoder: HttpUrlEncodingCodec {}
map: Map(5)
  [[Entries]]
  0: {"page" => Array(1)}
  1: {"pageSize" => Array(1)}
      key: "pageSize"
      value: ["3"]
  2: {"search" => Array(1)}
  3: {"sortBy" => Array(1)}
  4: {"sortByType" => Array(1)}
</code>```

I try to use .set("page", this.paginator.pageIndex) and also .append(...) but I always get same structure

Also, I try directly in service fix this, but this not working, I again get undefined

```<code>this.httpClient.get(`${this.url}/list`, {
  params: Object.entries(queryParameterObject).reduce((queryParams, [key, value]) => queryParams.set(key, value), new HttpParams());
});
</code>```

Thnx

答:
try to skip them in the reduce.

this.httpClient.get(`${this.url}/list`, {
  params: queryParameterObject ? queryParameterObject.keys().reduce((queryParams, key) => {
  // getting value from map
  let value: any = queryParameterObject.get(key);

  // extracting value if it's an array
  value = Array.isArray(value) ? value[0] : value;

  // adding only defined values to the params
  if (value !== undefined && value !== null) {
    queryParams[key] = value;
  }

  return queryParams;
}, {}) : {};
});
```

Title: httpParams remove undefined params

Body:
I need to send params in my URL to get filtered data from the server.

I set params like this

const queryParams = new HttpParams(
      {
        fromObject: {
          page: this.paginator.pageIndex.toString(),
          pageSize: this.paginator.pageSize.toString(),
          search: this.searchKey,
          sortBy: this.selectedFilterByStatusValue,
          sortByType: this.selectedFilterSortByValue
        }
      });

And in my service

 getData(params: HttpParams) {
    return this.apiService.get<IResponseList<IData>>(`${this.url}/list`, params);
  }

Problem is, when some filter is not selected, because I don't need them, and it is set like undefined, but this is not correct... I need to remove undefined params.

Here is console.log for queryParams

cloneFrom: null
encoder: HttpUrlEncodingCodec {}
map: Map(5)
  [[Entries]]
  0: {"page" => Array(1)}
  1: {"pageSize" => Array(1)}
      key: "pageSize"
      value: ["3"]
  2: {"search" => Array(1)}
  3: {"sortBy" => Array(1)}
  4: {"sortByType" => Array(1)}

I try to use .set("page", this.paginator.pageIndex) and also .append(...) but I always get same structure

Also, I try directly in service fix this, but this not working, I again get undefined

this.httpClient.get(`${this.url}/list`, {
  params: Object.entries(queryParameterObject).reduce((queryParams, [key, value]) => queryParams.set(key, value), new HttpParams());
});

Thnx


问:
"Wrap with try...catch" in IntelliJ?
Can I select a block of code and have IntelliJ wrap it with a "try...catch" ?

Is there a keyboard shortcut?

答: Select the code block to surround and then press Ctrl + Alt + T (or right-click the selection and select Surround with… from the menu). IntelliJ IDEA will show a list of options to choose from.

ContentLicense: CC BY-SA 2.5

Title: "Wrap with try...catch" in IntelliJ?


问:
How to add text inside the hole of the Donut Pie Chart in Grafana
I would like to add centered text in the middle of donut hole pie chart in Grafana like the image below

https://i.stack.imgur.com/XVAAg.png
I am using pie chart plugin of Grafana

答:
In file C:\Program Files\GrafanaLabs\grafana\data\plugins\piechart-panel\src\rendering.ts there is function "addPieChart".

Need to add these raws:

let sumData = 0
    ctrl.data.forEach((elem: any) => {
      sumData = sumData + elem.data;
    });  //.reduce(reducer)
    const plotCanvas = $('

 '+ sumData + '

');
    ```
</div>
</div>
</p>

<p>in line with: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const plotCanvas = $('<div><div');</code>```

Body:
In file C:\Program Files\GrafanaLabs\grafana\data\plugins\piechart-panel\src\rendering.ts there is function "addPieChart".

Need to add these raws:

let sumData = 0
    ctrl.data.forEach((elem: any) => {
      sumData = sumData + elem.data;
    });  //.reduce(reducer)
    const plotCanvas = $('<div><div style="position: absolute;left: 49%;top: 40%;z-index: 1000;"> '+ sumData + '</div></div>');

in line with:

const plotCanvas = $('<div><div');


问:
Ec2 Instance on stop and restart the instance cannot be accessed by that url
Recently I stopped my instance for 2 days and I again stated that the status is showing running. However, if I hit that IP in the browser it is not opening. It shows this error:

答:
It sounds like you are not using an Elastic IP Address. Go to the console and there should be a new public IP address.

If you're planning to use this instance more permanently you should take a look at adding an Elastic IP Address.

More documentation available: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-instance-addressing-eips-allocating


问:
Reasonable SELECT ... INTO Oracle solution for case of multiple OR no rows
I just want to SELECT values into variables from inside a procedure.

SELECT blah1,blah2 INTO var1_,var2_
FROM ...

Sometimes a large complex query will have no rows sometimes it will have more than one -- both cases lead to exceptions.  I would love to replace the exception behavior with implicit behavior similiar to:

No rows = no value change, Multiple rows = use last

I can constrain the result set easily enough for the "multiple rows" case but "no rows" is much more difficult for situations where you can't use an aggregate function in the SELECT.

Is there any special workarounds or suggestions?  Looking to avoid significantly rewriting queries or executing twice to get a rowcount before executing SELECT INTO.

答:
Whats wrong with using an exception block?</p>

```<code>  create or replace
procedure p(v_job VARCHAR2) IS
 v_ename VARCHAR2(255);
begin

 select ename into v_ename
 from (
  select ename
  from scott.emp
  where job = v_job
  order by v_ename desc )
 where rownum = 1;

 DBMS_OUTPUT.PUT_LINE('Found Rows Logic Here -> Found ' || v_ename);
 EXCEPTION WHEN NO_DATA_FOUND THEN
  DBMS_OUTPUT.PUT_LINE('No Rows found logic here');

end;

SQL>  begin
   p('FOO');
   p('CLERK');
  end;  2    3    4
  5  /
No Rows found logic here
Found Rows Logic Here -> Found SMITH

PL/SQL procedure successfully completed.

SQL>
</code>```

OwnerDisplayName: Einstein

Body:
Whats wrong with using an exception block?

  create or replace
procedure p(v_job VARCHAR2) IS
 v_ename VARCHAR2(255);
begin

 select ename into v_ename
 from (
  select ename
  from scott.emp
  where job = v_job
  order by v_ename desc )
 where rownum = 1;

 DBMS_OUTPUT.PUT_LINE('Found Rows Logic Here -> Found ' || v_ename);
 EXCEPTION WHEN NO_DATA_FOUND THEN
  DBMS_OUTPUT.PUT_LINE('No Rows found logic here');

end;

SQL>  begin
   p('FOO');
   p('CLERK');
  end;  2    3    4
  5  /
No Rows found logic here
Found Rows Logic Here -> Found SMITH

PL/SQL procedure successfully completed.

SQL>

OwnerDisplayName: Matthew Watson