问:
Quarkus extension (io.quarkus:quarkus-spring-data-jpa) repository can't return Collection of Strings
I'm migrating my service to Quarkus from SpringBoot stack.
Why the following code doesn't work in Quarkus? Is that a bug?

```<code>public interface GenericDictionaryRepository extends
        JpaRepository<Dictionary, UUID> {

    @Query("select distinct(d.type) from Dictionary d order by d.type")
    List<String> findAllTypes();

}
</code>```

Error message

```<code>io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.spring.data.deployment.SpringDataJPAProcessor#build threw an exception: java.lang.IllegalStateException: java.lang.String was not part of the Quarkus index
</code>```

My version properties for Gradle:

```<code>quarkusPluginVersion=1.3.1.Final
quarkusPlatformArtifactId=quarkus-universe-bom
quarkusPlatformGroupId=io.quarkus
quarkusPlatformVersion=1.3.1.Final
</code>```

答:
I had the same problem and it was a method naming problem. I had to put a break point in the quarkus code to find what method was wrongly spelled.

In my case the method was findAllOrderByNameAsc and when I used findAllByOrderByNameAsc, it worked.

To debug the app you have to execute the command ./mvnw quarkus:dev -Ddebug -Dsuspend=true and connect to remote from your IDE.

Hope it helps.

Body:
I'm migrating my service to Quarkus from SpringBoot stack.
Why the following code doesn't work in Quarkus? Is that a bug?

public interface GenericDictionaryRepository extends
        JpaRepository<Dictionary, UUID> {

    @Query("select distinct(d.type) from Dictionary d order by d.type")
    List<String> findAllTypes();

}

Error message

io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.spring.data.deployment.SpringDataJPAProcessor#build threw an exception: java.lang.IllegalStateException: java.lang.String was not part of the Quarkus index

My version properties for Gradle:

quarkusPluginVersion=1.3.1.Final
quarkusPlatformArtifactId=quarkus-universe-bom
quarkusPlatformGroupId=io.quarkus
quarkusPlatformVersion=1.3.1.Final


来源: stackexchange

问:
Spark - get tables from database
I have to perform an operation on all the tables from given databases(s) and so I am using following code.

However, it gives me views as well, is there a way I can filter only tables?

code

  def getTables(databaseName: String)(implicit spark: SparkSession): Array[String] = {
    val tables = spark.sql(s"show tables from ${databaseName}").collect().map(_(1).asInstanceOf[String])
    logger.debug(s"${tables.mkString(",")} found")
    tables
  }
```

<p>also, `show views shows error" </p>

<pre class="lang-scala prettyprint-override"><code>scala> spark.sql("show views from gshah03;").show
org.apache.spark.sql.catalyst.parser.ParseException:
missing 'FUNCTIONS' at 'from'(line 1, pos 11)

== SQL ==
show views from gshah03;
-----------^^^

  at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:241)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:117)
  at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:48)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parsePlan(ParseDriver.scala:69)
  at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:643)
  ... 49 elided

</code>```

答:
Try this-

  val df = spark.range(1, 5)
    df.createOrReplaceTempView("df_view")
    println(spark.catalog.currentDatabase)
    val db: Database = spark.catalog.getDatabase(spark.catalog.currentDatabase)
    val tables: Dataset[Table] = spark.catalog.listTables(db.name)
    tables.show(false)

    /**
      * default
      * +-------+--------+-----------+---------+-----------+
      * |name   |database|description|tableType|isTemporary|
      * +-------+--------+-----------+---------+-----------+
      * |df_view|null    |null       |TEMPORARY|true       |
      * +-------+--------+-----------+---------+-----------+
      */
```

ContentLicense: CC BY-SA 4.0

Title: Spark - get tables from database

Body:
I have to perform an operation on all the tables from given databases(s) and so I am using following code.

However, it gives me views as well, is there a way I can filter only tables?

code

  def getTables(databaseName: String)(implicit spark: SparkSession): Array[String] = {
    val tables = spark.sql(s"show tables from ${databaseName}").collect().map(_(1).asInstanceOf[String])
    logger.debug(s"${tables.mkString(",")} found")
    tables
  }

also, `show views shows error"

scala> spark.sql("show views from gshah03;").show
org.apache.spark.sql.catalyst.parser.ParseException:
missing 'FUNCTIONS' at 'from'(line 1, pos 11)

== SQL ==
show views from gshah03;
-----------^^^

  at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:241)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:117)
  at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:48)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parsePlan(ParseDriver.scala:69)
  at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:643)
  ... 49 elided


问:
How do you return a plain text string from an ORDS REST endpoint?
When creating a REST Data Services module handler in Oracle Rest Data Services (ORDS), it auto-formats the response as a JSON for PL/SQL procedures -- that is, any OUT parameters that you create get turned into a JSON. How do you return a plain-text string in the HTTP response without it being turned into a JSON?

A lot of my initial searches point to this resource for returning a raw JSON in ORDS, but this doesn't work for my situation since you can't change the Source Type if you're writing a PL/SQL endpoint (e.g. a method handler that's not auto-generated from a database object).

答:
Eventually, I found this documentation which is for something else entirely; however, it shows some example code using the HTP.p() method to print plain-text directly to the response. Below is a simple example of how to return a plain-text response in your ORDS REST Data Services module method handler:

```<code>BEGIN
  OWA_UTIL.mime_header('text/plain');
  HTP.p('Hello world!');
END;
</code>```

Body:
Eventually, I found this documentation which is for something else entirely; however, it shows some example code using the HTP.p() method to print plain-text directly to the response. Below is a simple example of how to return a plain-text response in your ORDS REST Data Services module method handler:

BEGIN
  OWA_UTIL.mime_header('text/plain');
  HTP.p('Hello world!');
END;


问:
How to check if a file is modified in Deno?
Basically given a file example.txt and a time t, I want to know whether the version of that file at t is the same as the version now.

I need to know how to do this in order to perform cache invalidation.

答:
You can use Deno.stat and check mtime.

const stat = await Deno.stat(filepath);
console.log(stat.mtime);
```

.stat requires --allow-read flag.

Body:
You can use Deno.stat and check mtime.

const stat = await Deno.stat(filepath);
console.log(stat.mtime);

.stat requires --allow-read flag.


问:
Lists that have a VStack containing a NavigationLink makes the whole area of the VStack tappable instead of only the SubView
When I put a VStack in a List and one of the SubViews of the VStack is a NavigationLink the whole area of the VStack becomes tappable to trigger the transition as opposed to just the SubView.

This is a simplified example of my problem:

```<code>struct Test: View {
    var body: some View {
        NavigationView {
            List {
                VStack {  // Entire VStack is tappable.
                    Rectangle()
                        .frame(width: 100, height: 200)
                        .foregroundColor(.red)

                    NavigationLink(destination: Destination()) {
                        Rectangle()  // I only want this Rectangle to be tappable.
                            .frame(width: 50, height: 100)
                            .foregroundColor(.red)
                    }
                }
            }
        }
    }
}
</code>```

```<code>struct Destination: View {
    var body: some View {
        Text("Hello")
    }
}
</code>```

I've tried using BorderlessButtonStyle() everywhere since it's worked before, but for some reason it isn't solving my problem now.

Why exactly does behaviour like this occur?

答:
Try this.</p>

```<code>  struct ContentView: View {
    @State var isSelected: Bool = false
    var body: some View {
        NavigationView {
            VStack {
                Rectangle()
                    .frame(width: 100, height: 200)
                    .foregroundColor(.red)

                Button(action: {
                    self.isSelected.toggle()
                }) {
                    Rectangle()
                        .frame(width: 100, height: 50)
                        .foregroundColor(.red)
                        .cornerRadius(10)
                }
                NavigationLink(destination: SecondView(), isActive: self.$isSelected) {
                    EmptyView()
                }
            }
            .navigationBarTitle("First Page")
        }
    }
}

struct SecondView: View {
    var body: some View {
        VStack {
            Text("Second Page")
        }
    .navigationBarTitle("Second Page")
    }
}
</code>```

Body:
When I put a VStack in a List and one of the SubViews of the VStack is a NavigationLink the whole area of the VStack becomes tappable to trigger the transition as opposed to just the SubView.

This is a simplified example of my problem:

struct Test: View {
    var body: some View {
        NavigationView {
            List {
                VStack {  // Entire VStack is tappable.
                    Rectangle()
                        .frame(width: 100, height: 200)
                        .foregroundColor(.red)

                    NavigationLink(destination: Destination()) {
                        Rectangle()  // I only want this Rectangle to be tappable.
                            .frame(width: 50, height: 100)
                            .foregroundColor(.red)
                    }
                }
            }
        }
    }
}

struct Destination: View {
    var body: some View {
        Text("Hello")
    }
}

I've tried using BorderlessButtonStyle() everywhere since it's worked before, but for some reason it isn't solving my problem now.

Why exactly does behaviour like this occur?

Body:
Try this.

  struct ContentView: View {
    @State var isSelected: Bool = false
    var body: some View {
        NavigationView {
            VStack {
                Rectangle()
                    .frame(width: 100, height: 200)
                    .foregroundColor(.red)

                Button(action: {
                    self.isSelected.toggle()
                }) {
                    Rectangle()
                        .frame(width: 100, height: 50)
                        .foregroundColor(.red)
                        .cornerRadius(10)
                }
                NavigationLink(destination: SecondView(), isActive: self.$isSelected) {
                    EmptyView()
                }
            }
            .navigationBarTitle("First Page")
        }
    }
}

struct SecondView: View {
    var body: some View {
        VStack {
            Text("Second Page")
        }
    .navigationBarTitle("Second Page")
    }
}


问:
How to use negative value in primeng p-slider?
I use p-slider component of primeng ( version ^4.1.3 ).

I want p-slider's range is [-100,100].

My html code like as below :

```<code><div class="col-md-6">
  <label class="my form-inline">
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[0]"
          name="filter.priceEditingPercent[0]" />
   -
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[1]"
          name="filter.priceEditingPercent[1]" />

    {{l('PriceChangePercent')}}
  </label>

   <p-slider [(ngModel)]="filter.priceEditingPercent"
             name="filter.priceEditingPercent"
             [range]="true">
   </p-slider>
</div>
</code>```

My typeScript code like as below:

```<code>export class ItemPriceEditingComponent extends AppComponentBase implements OnInit {

    filter = {
        priceEditingPercent: [-100, 100]
    }

    constructor(injector: Injector) {
        super(injector);
    }

    ngOnInit() {
    }

}
</code>```

I initialize filter.priceEditingPercent with [-100,100], but p-slider not render correctly. Negative values not shown.

答:
I solved this problem with use [max] and [min] inputs of p-slider component. I set -100 to [min]'s value   and set 100 to [max]'s value in HTML.

My correct html code like as below :

```<code><div class="col-md-6">
  <label class="my form-inline">
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[0]"
          name="filter.priceEditingPercent[0]" />
   -
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[1]"
          name="filter.priceEditingPercent[1]" />

    {{l('PriceChangePercent')}}
  </label>

   <p-slider [(ngModel)]="filter.priceEditingPercent"
             name="filter.priceEditingPercent"
             [range]="true"
             [min]="-100"
             [max]="100">
   </p-slider>
</div>
</code>```

Body:
I use p-slider component of primeng ( version ^4.1.3 ).

I want p-slider's range is [-100,100].

My html code like as below :

   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[0]"
          name="filter.priceEditingPercent[0]" />
   -
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[1]"
          name="filter.priceEditingPercent[1]" />

    {{l('PriceChangePercent')}}

My typeScript code like as below:

export class ItemPriceEditingComponent extends AppComponentBase implements OnInit {

    filter = {
        priceEditingPercent: [-100, 100]
    }

    constructor(injector: Injector) {
        super(injector);
    }

    ngOnInit() {
    }

}

I initialize filter.priceEditingPercent with [-100,100], but p-slider not render correctly. Negative values not shown.

Body:
I solved this problem with use [max] and [min] inputs of p-slider component. I set -100 to [min]'s value   and set 100 to [max]'s value in HTML.

My correct html code like as below :

<div class="col-md-6">
  <label class="my form-inline">
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[0]"
          name="filter.priceEditingPercent[0]" />
   -
   <input type="number"
          class="form-control input-sm"
          min="-100"
          max="100"
          [(ngModel)]="filter.priceEditingPercent[1]"
          name="filter.priceEditingPercent[1]" />

   &nbsp;{{l('PriceChangePercent')}}
  </label>

   <p-slider [(ngModel)]="filter.priceEditingPercent"
             name="filter.priceEditingPercent"
             [range]="true"
             [min]="-100"
             [max]="100">
   </p-slider>
</div>


问:
Cannot use the grid system in Materialize.css in react
I am trying to use the Materialize.css grid system in my react component, but the cards are not lining up next to each-other instead they are stacked.  here is my code of both components.

component Pillows.js

```<code>import React, {Fragment, useContext, useEffect} from 'react';
import SinglePillow from "./SinglePillow";

import {GlobalContext} from "../../context/GlobalState";

const Pillows = () => {
    const {pillows, getPillows} = useContext(GlobalContext);

    useEffect(() => {
        getPillows();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <Fragment>
            <div className="pillows">
                {pillows.map(pillow => (
                    <SinglePillow pillow={pillow}/>
                ))}
            </div>
        </Fragment>
    );
};

export default Pillows;
</code>```

component SinglePillow.js

```<code>import React from 'react';
//import pillow from "../pages/img/pillow1.jpg";

const SinglePillow = ({pillow}) => {
    return (
        <section id="popular" className="section section-popular scrollspy">
            <div className="container">
                <div className="row">
                    <div className="col s12 m4">
                        <div className="card">
                            <div className="card-image">
                                <img src={pillow.imageUrl} alt=""/>
                                <span className="card-title">Custom pillow</span>
                            </div>
                            <div className="card-content">
                                <p>
                                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab consequuntur dolor
                                    maiores obcaecati, sit tenetur?
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
};

export default SinglePillow;
</code>```

Please assist

答: The container and row class should not be in the SinglePillow to create side by side SinglePillows. As there are multiple SinglePillows, these are creating multiple rows and stacking on top of one another. You can move the container and row class to parent component.</p>

Body:
I am trying to use the Materialize.css grid system in my react component, but the cards are not lining up next to each-other instead they are stacked.  here is my code of both components.

component Pillows.js

import React, {Fragment, useContext, useEffect} from 'react';
import SinglePillow from "./SinglePillow";

import {GlobalContext} from "../../context/GlobalState";

const Pillows = () => {
    const {pillows, getPillows} = useContext(GlobalContext);

    useEffect(() => {
        getPillows();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <Fragment>

                {pillows.map(pillow => (
                    <SinglePillow pillow={pillow}/>
                ))}

        </Fragment>
    );
};

export default Pillows;

component SinglePillow.js

import React from 'react';
//import pillow from "../pages/img/pillow1.jpg";

const SinglePillow = ({pillow}) => {
    return (

                                Custom pillow

                                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab consequuntur dolor
                                    maiores obcaecati, sit tenetur?

    );
};

export default SinglePillow;

Please assist


问:
 Sprite Issue
I have the following code

```<code><ul id ="menu">
    <%foreach (var pckg in Model)
    { %>

        <li style = "text-align:center;width:60px;" class = "top-<%=pckg.Controller.ToLower() %>">
            li-text
        </li>

    <%} %>

</ul>
</code>```

and following is the sprite CSS

```<code>.top-pkg1{ background-position: -184px 0; width: 36px; height: 36px; }
.top-pkg2{ background-position: -270px 0; width: 36px; height: 36px; }
.top-pkg3{ background-position: -356px 0; width: 36px; height: 36px; }
.top-pkg4{ background-position: -517px 0; width: 36px; height: 36px; }
.top-pkg5{ background-position: -603px 0; width: 36px; height: 31px; }
.top-pkg5{ background-position: -689px 0; width: 36px; height: 36px; }
.top-pkg6{ background-position: -775px 0; width: 36px; height: 36px; }
.top-pkg7{ background-position: -861px 0; width: 36px; height: 36px; }
</code>```

and here is the container css

```<code> #menu li
    {
         display:block;
         background: url(/Content/images/TopMenu/topmenu.png) no-repeat top left;

    }
    #menu li a
    {
        margin-top:35px;
        text-align:center;
    }
</code>```

But when i ran this code i get the first image of the sprite partially shown on all li tags Couldn't figure out the problem. I created the css from Here
Fiddle link is
http://jsfiddle.net/tassadaque/LnGqX/1/

答:
@tassadaque; You already define background-position in your li  image  url top left

```<code>background: url(/Content/images/TopMenu/topmenu.png) no-repeat top left;
</code>```

So remove top left position from your li image url and write like this:

```<code>background: url(/Content/images/TopMenu/topmenu.png) no-repeat;
</code>```

Edit
write :

```<code>#menu li {background: url(/Content/images/TopMenu/topmenu.png) no-repeat;}

#menu li.top-pkg1{ background-position: -184px 0; width: 36px; height: 36px; }
#menu li.top-pkg2{ background-position: -270px 0; width: 36px; height: 36px; }
#menu li.top-pkg3{ background-position: -356px 0; width: 36px; height: 36px; }
#menu li.top-pkg4{ background-position: -20px 0; width: 36px; height: 36px; }
#menu li.top-pkg5{ background-position: -603px 0; width: 36px; height: 31px; }
#menu li.top-pkg5{ background-position: -689px 0; width: 36px; height: 36px; }
#menu li.top-pkg6{ background-position: -775px 0; width: 36px; height: 36px; }
#menu li.top-pkg7{ background-position: -861px 0; width: 36px; height: 36px; }
</code>```

ContentLicense: CC BY-SA 3.0

Title: <ul> Sprite Issue

Body:
I have the following code

    <%foreach (var pckg in Model)
    { %>

        <li style = "text-align:center;width:60px;" class = "top-<%=pckg.Controller.ToLower() %>">
            li-text

    <%} %>

and following is the sprite CSS

.top-pkg1{ background-position: -184px 0; width: 36px; height: 36px; }
.top-pkg2{ background-position: -270px 0; width: 36px; height: 36px; }
.top-pkg3{ background-position: -356px 0; width: 36px; height: 36px; }
.top-pkg4{ background-position: -517px 0; width: 36px; height: 36px; }
.top-pkg5{ background-position: -603px 0; width: 36px; height: 31px; }
.top-pkg5{ background-position: -689px 0; width: 36px; height: 36px; }
.top-pkg6{ background-position: -775px 0; width: 36px; height: 36px; }
.top-pkg7{ background-position: -861px 0; width: 36px; height: 36px; }

and here is the container css

 #menu li
    {
         display:block;
         background: url(/Content/images/TopMenu/topmenu.png) no-repeat top left;

    }
    #menu li a
    {
        margin-top:35px;
        text-align:center;
    }

But when i ran this code i get the first image of the sprite partially shown on all li tags Couldn't figure out the problem. I created the css from Here
Fiddle link is
http://jsfiddle.net/tassadaque/LnGqX/1/

Body:
@tassadaque; You already define background-position in your li  image  url top left

background: url(/Content/images/TopMenu/topmenu.png) no-repeat top left;

So remove top left position from your li image url and write like this:

background: url(/Content/images/TopMenu/topmenu.png) no-repeat;

Edit
write :

#menu li {background: url(/Content/images/TopMenu/topmenu.png) no-repeat;}

#menu li.top-pkg1{ background-position: -184px 0; width: 36px; height: 36px; }
#menu li.top-pkg2{ background-position: -270px 0; width: 36px; height: 36px; }
#menu li.top-pkg3{ background-position: -356px 0; width: 36px; height: 36px; }
#menu li.top-pkg4{ background-position: -20px 0; width: 36px; height: 36px; }
#menu li.top-pkg5{ background-position: -603px 0; width: 36px; height: 31px; }
#menu li.top-pkg5{ background-position: -689px 0; width: 36px; height: 36px; }
#menu li.top-pkg6{ background-position: -775px 0; width: 36px; height: 36px; }
#menu li.top-pkg7{ background-position: -861px 0; width: 36px; height: 36px; }


问:
Ajax multiple value
Did anyone know how i can send all this stuff with ajax to a search.php? it is already working but only with a search bar. I want to add to the search bar these variables. Its only important for the sort variable(the div with the sort id) to send the data on the beginning.
i think it would work to save the var into divs and get the values with document.getElementById('').getAttribute('value') but i still need to find out how to add this line of code to this ajax and that the ajax constantly check for changes in this divs. i still want that the ajax file send a output before i even touched the searchbar and the divs

```<code>$(document).ready(function(){
    load_data();
    function load_data(query)
    {
        $.ajax({
            url:"search.php",
            method:"post",
            data:{search:query},
            success:function(data)
            {
                $('#result').html(data);
            }
        });
    }

    $('#search_text').keyup(function(){
        var search = $(this).val();
        if(search != '')
        {
            load_data(search);
        }
        else
        {
            load_data();
        }
    });
});
</code>```

```<code>
function gettagValue() {
    var checks = document.getElementsByClassName('tag');
    var strtag = '';

    for ( i = 0; i<checks.length; i++) {
        if ( checks[i].checked === true ) {
            str += checks[i].value + "#";
        }
    }
    alert(strtag);
}
</code>```

```<code>
function getblacklistValue() {
    var checks = document.getElementsByClassName('blacklist');
    var strblacklist = '';

    for ( i = 0; i<checks.length; i++) {
        if ( checks[i].checked === true ) {
            strblacklist += checks[i].value + "#";
        }
    }
    alert(strblacklist);
}
</code>```

```<code>
function getbrandValue() {
    var checks = document.getElementsByClassName('brand');
    var strbrand = '';

    for ( i = 0; i<checks.length; i++) {
        if ( checks[i].checked === true ) {
            strbrand += checks[i].value + "#";
        }
    }
    alert(strbrand);
}
</code>```

```<code> alert(document.getElementById('sort').getAttribute('value'));
</code>```

答:
Do you mean that you want to send the values you're currently alerting?  For starters, return those values instead of just alerting them:

```<code>function gettagValue() {
    // ...
    return strtag;
}

// same for the getblacklistValue and getbrandValue functions
</code>```

Then in your AJAX code, call those functions to get those values and include them in the data:

```<code>function load_data(query)
{
    let tagValue = gettagValue();
    let blacklistValue = getblacklistValue();
    let brandValue = getbrandValue();
    $.ajax({
        url:"search.php",
        method:"post",
        data:{
            search:query,
            tagValue:tagValue,
            blacklistValue:blacklistValue,
            brandValue:brandValue
        },
        success:function(data)
        {
            $('#result').html(data);
        }
    });
}
</code>```

Title: Ajax multiple value

Body:
Did anyone know how i can send all this stuff with ajax to a search.php? it is already working but only with a search bar. I want to add to the search bar these variables. Its only important for the sort variable(the div with the sort id) to send the data on the beginning.
i think it would work to save the var into divs and get the values with document.getElementById('').getAttribute('value') but i still need to find out how to add this line of code to this ajax and that the ajax constantly check for changes in this divs. i still want that the ajax file send a output before i even touched the searchbar and the divs

$(document).ready(function(){
    load_data();
    function load_data(query)
    {
        $.ajax({
            url:"search.php",
            method:"post",
            data:{search:query},
            success:function(data)
            {
                $('#result').html(data);
            }
        });
    }

    $('#search_text').keyup(function(){
        var search = $(this).val();
        if(search != '')
        {
            load_data(search);
        }
        else
        {
            load_data();
        }
    });
});

function gettagValue() {
    var checks = document.getElementsByClassName('tag');
    var strtag = '';

    for ( i = 0; i<checks.length; i++) {
        if ( checks[i].checked === true ) {
            str += checks[i].value + "#";
        }
    }
    alert(strtag);
}

function getblacklistValue() {
    var checks = document.getElementsByClassName('blacklist');
    var strblacklist = '';

    for ( i = 0; i<checks.length; i++) {
        if ( checks[i].checked === true ) {
            strblacklist += checks[i].value + "#";
        }
    }
    alert(strblacklist);
}

function getbrandValue() {
    var checks = document.getElementsByClassName('brand');
    var strbrand = '';

    for ( i = 0; i<checks.length; i++) {
        if ( checks[i].checked === true ) {
            strbrand += checks[i].value + "#";
        }
    }
    alert(strbrand);
}

 alert(document.getElementById('sort').getAttribute('value'));

Body:
Do you mean that you want to send the values you're currently alerting?  For starters, return those values instead of just alerting them:

function gettagValue() {
    // ...
    return strtag;
}

// same for the getblacklistValue and getbrandValue functions

Then in your AJAX code, call those functions to get those values and include them in the data:

function load_data(query)
{
    let tagValue = gettagValue();
    let blacklistValue = getblacklistValue();
    let brandValue = getbrandValue();
    $.ajax({
        url:"search.php",
        method:"post",
        data:{
            search:query,
            tagValue:tagValue,
            blacklistValue:blacklistValue,
            brandValue:brandValue
        },
        success:function(data)
        {
            $('#result').html(data);
        }
    });
}


问:
Operator Overloading as member function
Why is it giving the error.

```<code> class Complex{
    int real,imaginary;
    public:
    Complex():real(0),imaginary(0){};
    Complex(int real, int imaginary):real(real),imaginary(imaginary){};
    int getreal()const{return real;}

    int getimaginary()const{return imaginary;};
    Complex &operator=(const Complex& );
    Complex operator*(){
      return Complex(real,-imaginary);
    }
    Complex  operator+(const Complex &a, const Complex &d){

      return  Complex (d.getreal()+a.getreal(),a.getimaginary()+d.getimaginary());
    }

  };
</code>```

When trying to overload the assingment operator.
Eroor says: too many parameter

What operators can we overload as member function and what not

答:
When defining an overloaded operator as a member function, the object pointed at by the this pointer is implicitly the first argument. So your operator overload needs to look like:

```<code>class Complex {
  // ...
  Complex  operator+(const Complex &d) const {
    return  Complex (real + d.real, imaginary + d.imaginary);
  }
};
</code>```

Note that you don't need the getter functions, since you already have access to the data members inside the class.

Outside the class, i.e. as a non-member function, your overloaded operator is perfectly fine.

Title: Operator Overloading as member function

Body:
Why is it giving the error.

 class Complex{
    int real,imaginary;
    public:
    Complex():real(0),imaginary(0){};
    Complex(int real, int imaginary):real(real),imaginary(imaginary){};
    int getreal()const{return real;}

    int getimaginary()const{return imaginary;};
    Complex &operator=(const Complex& );
    Complex operator*(){
      return Complex(real,-imaginary);
    }
    Complex  operator+(const Complex &a, const Complex &d){

      return  Complex (d.getreal()+a.getreal(),a.getimaginary()+d.getimaginary());
    }

  };

When trying to overload the assingment operator.
Eroor says: too many parameter

What operators can we overload as member function and what not

Body:
When defining an overloaded operator as a member function, the object pointed at by the this pointer is implicitly the first argument. So your operator overload needs to look like:

class Complex {
  // ...
  Complex  operator+(const Complex &d) const {
    return  Complex (real + d.real, imaginary + d.imaginary);
  }
};

Note that you don't need the getter functions, since you already have access to the data members inside the class.

Outside the class, i.e. as a non-member function, your overloaded operator is perfectly fine.


问:
How to rank observations in panel data?
I have a panel dataset in Stata with several countries and each country containing groups. I would like to rank the groups by country, according to the variable var1.

The structure of my dataset is as follows (the rank column is what I would like to achieve). Note that var1 is indeed constant within groups (it is just the within group average of another variable).

```<code>--country--|--groupId--|---time----|---var1----|---rank---
     1     |     1     |     1     |    50     |    3
     1     |     1     |     2     |    50     |    3
     1     |     1     |     3     |    50     |    3
     1     |     2     |     1     |    90     |    1
     1     |     2     |     2     |    90     |    1
     1     |     2     |     3     |    90     |    1
     1     |     3     |     1     |    60     |    2
     1     |     3     |     2     |    60     |    2
     1     |     3     |     3     |    60     |    2
     2     |     4     |     1     |    15     |    2
     2     |     4     |     2     |    15     |    2
     2     |     4     |     3     |    15     |    2
     2     |     5     |     1     |    10     |    3
     2     |     5     |     2     |    10     |    3
     2     |     5     |     3     |    10     |    3
     2     |     6     |     1     |    80     |    1
     2     |     6     |     2     |    80     |    1
     2     |     6     |     3     |    80     |    1
</code>```

Among the options I have tried is:

```<code>sort country groupId
by country (groupId): egen rank = rank(var1)
</code>```

However, I cannot achieve the desired result.

答:
Thanks for the data example. There are two problems with your code. One is that as you want to rank from highest to lowest, you need to negate the argument to rank(). The second is that given the repetitions, you need to rank on one time only and then copy those ranks to other times.

This works with your data example, here edited to be input code. (See also the Stata tag wiki for that principle.)

```<code>clear
input   country    groupId     time       var1       rank
     1          1          1         50         3
     1          1          2         50         3
     1          1          3         50         3
     1          2          1         90         1
     1          2          2         90         1
     1          2          3         90         1
     1          3          1         60         2
     1          3          2         60         2
     1          3          3         60         2
     2          4          1         15         2
     2          4          2         15         2
     2          4          3         15         2
     2          5          1         10         3
     2          5          2         10         3
     2          5          3         10         3
     2          6          1         80         1
     2          6          2         80         1
     2          6          3         80         1
end

bysort country : egen wanted = rank(-var) if time == 1
bysort country groupId (time) : replace wanted = wanted[1]
assert rank == wanted
</code>```

Title: How to rank observations in panel data?

Body:
I have a panel dataset in Stata with several countries and each country containing groups. I would like to rank the groups by country, according to the variable var1.

The structure of my dataset is as follows (the rank column is what I would like to achieve). Note that var1 is indeed constant within groups (it is just the within group average of another variable).

--country--|--groupId--|---time----|---var1----|---rank---
     1     |     1     |     1     |    50     |    3
     1     |     1     |     2     |    50     |    3
     1     |     1     |     3     |    50     |    3
     1     |     2     |     1     |    90     |    1
     1     |     2     |     2     |    90     |    1
     1     |     2     |     3     |    90     |    1
     1     |     3     |     1     |    60     |    2
     1     |     3     |     2     |    60     |    2
     1     |     3     |     3     |    60     |    2
     2     |     4     |     1     |    15     |    2
     2     |     4     |     2     |    15     |    2
     2     |     4     |     3     |    15     |    2
     2     |     5     |     1     |    10     |    3
     2     |     5     |     2     |    10     |    3
     2     |     5     |     3     |    10     |    3
     2     |     6     |     1     |    80     |    1
     2     |     6     |     2     |    80     |    1
     2     |     6     |     3     |    80     |    1

Among the options I have tried is:

sort country groupId
by country (groupId): egen rank = rank(var1)

However, I cannot achieve the desired result.

Body:
Thanks for the data example. There are two problems with your code. One is that as you want to rank from highest to lowest, you need to negate the argument to rank(). The second is that given the repetitions, you need to rank on one time only and then copy those ranks to other times.

This works with your data example, here edited to be input code. (See also the Stata tag wiki for that principle.)

clear
input   country    groupId     time       var1       rank
     1          1          1         50         3
     1          1          2         50         3
     1          1          3         50         3
     1          2          1         90         1
     1          2          2         90         1
     1          2          3         90         1
     1          3          1         60         2
     1          3          2         60         2
     1          3          3         60         2
     2          4          1         15         2
     2          4          2         15         2
     2          4          3         15         2
     2          5          1         10         3
     2          5          2         10         3
     2          5          3         10         3
     2          6          1         80         1
     2          6          2         80         1
     2          6          3         80         1
end

bysort country : egen wanted = rank(-var) if time == 1
bysort country groupId (time) : replace wanted = wanted[1]
assert rank == wanted


问:
Equivalent of as: :json when performing a call in ruby on rails
I'm unfamiliar with this syntax as: :json

I can convert the following:

```<code>session.put-= '/animals', params: data, headers:{"test-auth": token_key}
</code>```

to the following function: (where session represents open_session)

```<code>session.put(route, params:data, headers:{"test-auth": token_key})
</code>```

However, how would I set the following that uses as: :json

```<code> session.put '/animals', params: data, as: :json, headers:{"test-auth": token_key}
</code>```

答:
```<code>  session.put(route, params: data, as: :json, headers: {..})
</code>```

The signature of the method is probably something along the lines of:

```<code>def put(route, params = {params: {}, as: 'default', headers: {}})
... block of coode
end
</code>```

The colon after as: is saying that as is a key in a hash. :json is just a ruby symbol.

Body:
I'm unfamiliar with this syntax as: :json

I can convert the following:

session.put-= '/animals', params: data, headers:{"test-auth": token_key}

to the following function: (where session represents open_session)

session.put(route, params:data, headers:{"test-auth": token_key})

However, how would I set the following that uses as: :json

 session.put '/animals', params: data, as: :json, headers:{"test-auth": token_key}

Body:
  session.put(route, params: data, as: :json, headers: {..})

The signature of the method is probably something along the lines of:

def put(route, params = {params: {}, as: 'default', headers: {}})
... block of coode
end

The colon after as: is saying that as is a key in a hash. :json is just a ruby symbol.


问:
"sun.security.validator.ValidatorException: PKIX path building failed: Exception: unable to find valid certification path to requested target"
I am trying to get response code for this site "https://www.ssfcu.org/en-us/Pages/default.aspx".
The code snippet is:

```<code>try{
     HttpURLConnection connection = pingUrl(location);
     responseCode = connection.getResponseCode();
}catch(Exception e) {
}

public HttpURLConnection pingUrl(String url) throws Exception{

    int count = 0;
    HttpURLConnection conn = null;

    conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(2000);
    conn.setInstanceFollowRedirects(false);
    conn.setReadTimeout(10000);
    conn.connect();
    Thread.sleep(1000);

    return conn;
}
</code>```

But I am getting an exception:

```<code>sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
</code>```

How can I resolve this?

答:
An old COMODO root certificate expired on May 30.

https://www.reddit.com/r/linux/comments/gshh70/sectigo_root_ca_expiring_may_not_be_handled_well/

https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020

Don't know if this affects www.ssfcu.org, but you might try importing updated certs to your java keystore:

Fetch https://crt.sh/?d=1720081 and https://crt.sh/?d=1199354

Convert crt files to der files: openssl x509 -in 1720081.crt -outform der -out 1720081.der

keytool -import -file 1720081.der -keystore your-keystore -alias Comodo (or alias UserTrust for 1199354)

Your keystore is in your JRE_HOME directory in the file lib/security/cacerts.  You'll need root privilege to edit the cacerts file.

Edit: I looked closer and Comodo isn't involved in www.sfcu.org's certificate chain, but the instructions above are correct as long as you can identify the root or intermediate certificate that has expired.  We coincidentally ran into an issue with linkedin.com today.  Like www.ssfcu.org, they too use a certificate chain from DigiCert, so perhaps they had some certs expire recently, too.

Body:
I am trying to get response code for this site "https://www.ssfcu.org/en-us/Pages/default.aspx".
The code snippet is:

try{
     HttpURLConnection connection = pingUrl(location);
     responseCode = connection.getResponseCode();
}catch(Exception e) {
}

public HttpURLConnection pingUrl(String url) throws Exception{

    int count = 0;
    HttpURLConnection conn = null;

    conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(2000);
    conn.setInstanceFollowRedirects(false);
    conn.setReadTimeout(10000);
    conn.connect();
    Thread.sleep(1000);

    return conn;
}

But I am getting an exception:

sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target

How can I resolve this?


问:
Easier way to count users in T-SQL
I'm using this query in SQL Server 2016 to determine how many users have logged into my system.

The users.lastaccess column contains a unix timestamp, so I use DATEDIFF() to convert it to a yyyy-mm-dd hh:mm:ss date.

```<code>SELECT
    COUNT(*) AS user_logins
FROM
    (SELECT
         ROW_NUMBER() OVER(ORDER BY lastaccess DESC) AS Row
     FROM
         users
     WHERE
         lastaccess > DATEDIFF(s, '1970-01-01 02:00:00', (SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))))
)
</code>```

The result is a simple number, e.g. 75, representing the number of users who have been authenticated on the system.

答:
The following code returns the count of users. It uses cast to drop the time-of-day from the value returned by GetDate and uses ISO 8601 for the base date/time of the unix system.

```<code>select Count(*) as User_Logins
  from Users
  where LastAccess > DateDiff( s, '1970-01-01T02:00:00', Cast( GetDate() as Date ) );
</code>```

Title: Easier way to count users in T-SQL

Body:
I'm using this query in SQL Server 2016 to determine how many users have logged into my system.

The users.lastaccess column contains a unix timestamp, so I use DATEDIFF() to convert it to a yyyy-mm-dd hh:mm:ss date.

SELECT
    COUNT(*) AS user_logins
FROM
    (SELECT
         ROW_NUMBER() OVER(ORDER BY lastaccess DESC) AS Row
     FROM
         users
     WHERE
         lastaccess > DATEDIFF(s, '1970-01-01 02:00:00', (SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))))
)

The result is a simple number, e.g. 75, representing the number of users who have been authenticated on the system.

Body:
The following code returns the count of users. It uses cast to drop the time-of-day from the value returned by GetDate and uses ISO 8601 for the base date/time of the unix system.

select Count(*) as User_Logins
  from Users
  where LastAccess > DateDiff( s, '1970-01-01T02:00:00', Cast( GetDate() as Date ) );


问:
How do you make a clickable dropdown menu that pushes rest of content on page
I think it was a bit hard to explain what I mean in the title, but pretty much what I want to do is to have a text saying "View guild members", and whenever you press on this text, a list of all members fades in.

Thing is though, I have done research and found dropdown menus, but I don't want it to show the content over the content that are displayed.

Easier to explain with these two pictures:

As you can see, after pressing the button, the content (link 1-3) displays over "hello". I want to push "hello" further down the page.

How do I do this?

答:
In order to accomplish the fade-in animation you need to add these styles in your css:

```<code>.show {
  display: block;
  animation: fadeIn 600ms ease-in-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</code>```

Here is also a codepen to play around with the code.

Body:
In order to accomplish the fade-in animation you need to add these styles in your css:

.show {
  display: block;
  animation: fadeIn 600ms ease-in-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

Here is also a codepen to play around with the code.


问:
PDO MYSQL_ATTR_USE_BUFFERED_QUERY Not taking affect
I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed):

```<code>ini_set('memory_limit', '7G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2020-04-25', '2020-05-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
}
</code>```

during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB.

Testing the setattribute

```<code>var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));
</code>```

seems like it has taken affect:

```<code>bool(true)
</code>```

but the behavior doesn't change when I switch buffered or unbuffered.

```<code>$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)
</code>```

and

```<code>$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)
</code>```

Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes.

Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work.

```<code>$stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
</code>```

I've also tried moving the buffer setting to the connection with no affect:

```<code>$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
</code>```

Taking out the second connection seems to allow the unbuffered query to function as intended:

```<code>ini_set('memory_limit', '1G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
//$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
//$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2019-01-25', '2019-11-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      /*
     $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
     */
}
</code>```

This usage the memory_get_usage doesn't exceed 379999.

If I uncomment the second connection and make it unbuffered as well I receive:

```<code>Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
</code>```

The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution.

Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)):

```<code>php71u-pdo.x86_64                  7.1.19-1.ius.centos7
</code>```

Moved script to a newer machine (Amazon Linux release 2 (Karoo)):

```<code>var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));
</code>```0

and have the same behavior.

答:
The PDO::ATTR_PERSISTENT value is not boolean. It identifies the connection being used, use unique values for multiple connections. In my case:

```<code>$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => 'unbuff', PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => 'buff', PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
</code>```

Body:
I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed):

ini_set('memory_limit', '7G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2020-04-25', '2020-05-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
}

during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB.

Testing the setattribute

var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));

seems like it has taken affect:

bool(true)

but the behavior doesn't change when I switch buffered or unbuffered.

$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)

and

$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)

Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes.

Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work.

$stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

I've also tried moving the buffer setting to the connection with no affect:

$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

Taking out the second connection seems to allow the unbuffered query to function as intended:

ini_set('memory_limit', '1G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
//$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
//$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2019-01-25', '2019-11-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      /*
     $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
     */
}

This usage the memory_get_usage doesn't exceed 379999.

If I uncomment the second connection and make it unbuffered as well I receive:

Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution.

Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)):

php71u-pdo.x86_64                  7.1.19-1.ius.centos7

Moved script to a newer machine (Amazon Linux release 2 (Karoo)):

php73-pdo.x86_64                   7.3.17-1.el7.ius

and have the same behavior.

Body:
The PDO::ATTR_PERSISTENT value is not boolean. It identifies the connection being used, use unique values for multiple connections. In my case:

$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => 'unbuff', PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => 'buff', PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));


问:
React state -> h2 tag won't display updated state, just initial one
I have a hook state that should be displayed in a h2 tag in JSX. The state is updated through a fetch order. The thing is, the result only displays the initial values of the state, not the updated ones. By using console.log, I verified the state is indeed varying. First, the state is initialized, being an array of objects with 'artist' properties. Artists peter and Andrew are already in the state:

```<code>const [itemList, setItemList] = useState([{artist:'peter'},{artist:'andrew'}]);
</code>```

I also have a button that, when clicked, orders the program to fetch an array of artists from musixmatch api through a onClick() function and update the state itemList:

```<code><button onClick={onClick}>Search</button>
</code>```

The function onClick() code:

```<code>const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                response.message.body.track_list.map(item => {
                let copyItemList = itemList;
                copyItemList.push({ artist: item.track.artist_name });
                setItemList(copyItemList);
            })
        });
}
</code>```

The result should then be displayed in a h2 tag:

```<code><h2>Test:{itemList.map(item => <p>{item.artist}</p>)}</h2>
</code>```

As I said before, it shows only the initial artists, Peter and Andrew, but no new artists after I press the update state button. What is the problem here, why is the new state not being shown in the h2 tag ? I wrote another function that updates the state locally, no fetch order, and it worked as intended.

答:
The problem is that you are setting the itemlist variable once for every item inside the array you are iterating. You should put the setListItem outside the loop. Another thing is that when iterating over an array, if you are not returning any values you should use forEach instead of map. Map is used when you want a return from every iteration of your loop.

```<code>const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                const list = [];
                response.message.body.track_list.forEach(item => {
                list.push({ artist: item.track.artist_name });
            })
            setItemList(list);
        });
}
</code>```

This will replace the old array. If you want to extend the initial liost, you should make a copy using the spread operator and add all the items in the list array with the same operator, like this.

```<code>setItemList(...itemList, ...list)
</code>```

Body:
I have a hook state that should be displayed in a h2 tag in JSX. The state is updated through a fetch order. The thing is, the result only displays the initial values of the state, not the updated ones. By using console.log, I verified the state is indeed varying. First, the state is initialized, being an array of objects with 'artist' properties. Artists peter and Andrew are already in the state:

const [itemList, setItemList] = useState([{artist:'peter'},{artist:'andrew'}]);

I also have a button that, when clicked, orders the program to fetch an array of artists from musixmatch api through a onClick() function and update the state itemList:

<button onClick={onClick}>Search</button>

The function onClick() code:

const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                response.message.body.track_list.map(item => {
                let copyItemList = itemList;
                copyItemList.push({ artist: item.track.artist_name });
                setItemList(copyItemList);
            })
        });
}

The result should then be displayed in a h2 tag:

Test:{itemList.map(item =>
{item.artist}
)}

As I said before, it shows only the initial artists, Peter and Andrew, but no new artists after I press the update state button. What is the problem here, why is the new state not being shown in the h2 tag ? I wrote another function that updates the state locally, no fetch order, and it worked as intended.

Body:
The problem is that you are setting the itemlist variable once for every item inside the array you are iterating. You should put the setListItem outside the loop. Another thing is that when iterating over an array, if you are not returning any values you should use forEach instead of map. Map is used when you want a return from every iteration of your loop.

const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                const list = [];
                response.message.body.track_list.forEach(item => {
                list.push({ artist: item.track.artist_name });
            })
            setItemList(list);
        });
}

This will replace the old array. If you want to extend the initial liost, you should make a copy using the spread operator and add all the items in the list array with the same operator, like this.

setItemList(...itemList, ...list)


问:
How to convert np array to StringIO
I ran into a problem while trying to stream images over a local network. On the system with the camera I can see the images perfectly fine and I can establish a socket between the two computers. I want to send the data as a StringIO to attach the size of the current image in the String.
However my computer tells me, it cannot convert a np array  to a str .
Instead I sent it as a BytesIO , but the client cannot reconvert this data.

Is there a way to send the iages as a StringIO or to reconvert the BytesIO?

答:
I forgot to encode correctly, as furas pointed out. I had to add the size as a header via header = '{0}:'.format(packet_size) ,  header = bytes(header.encode()) and out += header.
I modeled my approach after this project: https://github.com/sabjorn/NumpySocket

furas's way should work as well, but my approach was closer to the previously mentioned project.

Title: How to convert np array to StringIO


问:
Access element by id in material-ui useStyles()
I have a simple div with three other divs nested inside of it, and each nested div has an id. I'm having trouble accessing these divs by their ids in useStyles().
here is my component:

```<code>import { useStyles } from "./components/Styles/Styles";

export const CountDown = () => {
   const classes = useStyles();

   return(
      <div className={classes.countDown}>
        <div id="hour">NA</div>
        <div id="minute">NA</div>
        <div id="second">NA</div>
      </div>
   )
}
</code>```

and this is useSyles()

```<code>export const useStyles = makeStyles({
   countDown: {
      "& #hour:before": { //not working like this
         content: "Hours",
      },
   }
})
</code>```

答:
You need to use ::

Working demo

Code snippet:

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      "& > *": {
        margin: theme.spacing(1),
        width: "25ch"
      }
    },
    countDown: {
      "& #hour": {
        background: "red"
      },
      "& #minute::before": { //<------ like this
        content: '"Minute"',
      }
    }
  })
);
```

Read more here

Body:
I have a simple div with three other divs nested inside of it, and each nested div has an id. I'm having trouble accessing these divs by their ids in useStyles().
here is my component:

import { useStyles } from "./components/Styles/Styles";

export const CountDown = () => {
   const classes = useStyles();

   return(

NA

NA

NA

   )
}

and this is useSyles()

export const useStyles = makeStyles({
   countDown: {
      "& #hour:before": { //not working like this
         content: "Hours",
      },
   }
})

Body:
You need to use ::

Working demo

Code snippet:

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      "& > *": {
        margin: theme.spacing(1),
        width: "25ch"
      }
    },
    countDown: {
      "& #hour": {
        background: "red"
      },
      "& #minute::before": { //<------ like this
        content: '"Minute"',
      }
    }
  })
);

Read more here


问:
Naming files using a split string
I'm extracting photos from a FGDB file and need to name the file using part of the name of one of our attributes. Normally this script just takes attributes and concatenates them, but I need to do the reverse and actually split a single attribute at the second "-", and then use the first string as the file name:

```<code>from arcpy import da
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

inTable = arcpy.GetParameterAsText(0)
fileLocation = arcpy.GetParameterAsText(1)

with da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'PHOTO_NAME',]) as cursor:
    for item in cursor:
        attachment = item[0]
    filename = str(item[3])
        open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())
        del item
        del filename
        del attachment
</code>```

Here's the code I'm using. I'm a little stumped on where exactly to start with this. Should I be splitting it before the function and making it a variable, or including it in the for loop?

As you can see I'm a bit new to Python, so any pointer will help

Thanks!

答:
I haven't tested this code but would something like this work?</p>

```<code>with da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'PHOTO_NAME',]) as cursor:
    for item in cursor:
        attachment = item[0]

        string_to_split = str(item[3])
        # example: 'firstpart-secondpart-thirdpart'

        string_list = string_to_split.split('-')
        # example: ['firstpart', 'secondpart', 'thirdpart']

        filename = string_list[0] + '-' + string_list[1]
        # example 'firstpart-secondpart' (probably also want a file extension here or on next line; .jpg perhaps)

        open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())
        del item
        del filename
        del attachment
</code>```

Title: Naming files using a split string

Body:
I'm extracting photos from a FGDB file and need to name the file using part of the name of one of our attributes. Normally this script just takes attributes and concatenates them, but I need to do the reverse and actually split a single attribute at the second "-", and then use the first string as the file name:

from arcpy import da
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

inTable = arcpy.GetParameterAsText(0)
fileLocation = arcpy.GetParameterAsText(1)

with da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'PHOTO_NAME',]) as cursor:
    for item in cursor:
        attachment = item[0]
    filename = str(item[3])
        open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())
        del item
        del filename
        del attachment

Here's the code I'm using. I'm a little stumped on where exactly to start with this. Should I be splitting it before the function and making it a variable, or including it in the for loop?

As you can see I'm a bit new to Python, so any pointer will help

Thanks!

Body:
I haven't tested this code but would something like this work?

with da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'PHOTO_NAME',]) as cursor:
    for item in cursor:
        attachment = item[0]

        string_to_split = str(item[3])
        # example: 'firstpart-secondpart-thirdpart'

        string_list = string_to_split.split('-')
        # example: ['firstpart', 'secondpart', 'thirdpart']

        filename = string_list[0] + '-' + string_list[1]
        # example 'firstpart-secondpart' (probably also want a file extension here or on next line; .jpg perhaps)

        open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())
        del item
        del filename
        del attachment


问:
Connect to a site presenting an expired root certificate in the certificate bundle with curl in PHP
Over the weekend, the Sectigo AddTrust External CA Root expired. For modern browsers, this should not have made any difference for users of affected sites.

Our PHP application connects to a site which we don't control, which includes this expired root in its certificate bundle. We connect using curl, and verify the certificates. But since this root is now expired, curl is now refusing to connect, with an error that the certificate is expired.

There is a sample site which exhibits the same behaviour at https://addtrustchain.test.certificatetest.com/

And sample code which exhibits the same behaviour is

$ch = curl_init();

$url = 'https://addtrustchain.test.certificatetest.com/';
//$url = 'https://google.com';
$caPath = '/path/to/cacert.pem';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_CAINFO, $caPath);

$output = curl_exec($ch);

var_dump($output);
var_dump(curl_getinfo($ch));
var_dump(curl_errno($ch));
var_dump(curl_error($ch));

curl_close($ch);
```

Is there a workaround from the php side where we can ignore the expired root certificate provided in the bundle? We're trying to work with the parties on the other side to remove/update the expired root from their bundle, but it would be great to have a solution from our side for the next time this comes up.

I have tried updating our local cacert.pem to include the actual certificate itself, and the provided intermediaries, but neither of those seems to fix the issue.

答:
you need to remove AddTrust External Root from your cacert.pem.

For those who are wondering, you can take the cacert.pem from Mozilla there: https://curl.haxx.se/docs/caextract.html
You then need to remove AddTrust External Root.

Removing AddTrust External Root force software to use correct path certification (when you have multiple ones).

For example, twinoid.com has 3 paths. Two of them are valid, the last contain AddTrust External Root. https://www.ssllabs.com/ssltest/analyze.html?d=twinoid.com&hideResults=on (you can check the 3 paths there)

Body:
Over the weekend, the Sectigo AddTrust External CA Root expired. For modern browsers, this should not have made any difference for users of affected sites.

Our PHP application connects to a site which we don't control, which includes this expired root in its certificate bundle. We connect using curl, and verify the certificates. But since this root is now expired, curl is now refusing to connect, with an error that the certificate is expired.

There is a sample site which exhibits the same behaviour at https://addtrustchain.test.certificatetest.com/

And sample code which exhibits the same behaviour is

$ch = curl_init();

$url = 'https://addtrustchain.test.certificatetest.com/';
//$url = 'https://google.com';
$caPath = '/path/to/cacert.pem';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_CAINFO, $caPath);

$output = curl_exec($ch);

var_dump($output);
var_dump(curl_getinfo($ch));
var_dump(curl_errno($ch));
var_dump(curl_error($ch));

curl_close($ch);

Is there a workaround from the php side where we can ignore the expired root certificate provided in the bundle? We're trying to work with the parties on the other side to remove/update the expired root from their bundle, but it would be great to have a solution from our side for the next time this comes up.

I have tried updating our local cacert.pem to include the actual certificate itself, and the provided intermediaries, but neither of those seems to fix the issue.


问:
c# Class Names - Convention on how to name classes

Possible Duplicate:

  (Conventions) C# Class names

I use Entity framework (or even with Nhibernate or linq to sql) you usually have a series of entity classes that get passed around a solution. I usually, have these classes in a VS Project called [SolutionName].Data

At some stage these will be used by another class which might carryout some business logic prior to saving and deleting them. In this situation I then have these action classes in a project called [SolutionName].Core

I have seen some developers suffix these classes with Logic or Manager e.g. RegistrationManager which would then have a Save(), Delete(), Update(). A prime example of this is the open source NopCommerce.

Some put them into a  folder called Bll but leave the name unchanged e.g. the namespace would be [SolutionName].Core.Bll with a class in that called Registration. They would then reply on the namespace distinguishing whether this is a database entity or a business logic class.

The question is how should I be naming classes? Should I just suffix everything with Logic/Manager/Service or is there a better solution?

答:
You should not suffix everything and thats all.

You have to create different projects not folders for different layers.


问:
Cannot resize the image in HTML page using bootstrap carousel
Cannot resize the image in my webpage. images are displayed in full size. I am using Bootstrap 4 carousel component. But the images seem to be non-responsive.

.carousel-item {
    width: 100%;
    height: auto;
    object-fit: cover;
}

The corresponding carousel part is as follows:```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="carouselExampleInterval" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active" data-interval="10000">
                <img src="{% static 'images/car4-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item" data-interval="2000">
                <img src="{% static 'images/car2-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item">
                <img src="{% static 'images/car3-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
        </div>

            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>

            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>

    </div></code>```

Please help.

答:
you have to specify the img attribute if you want to resize the image:

.carousel-item img {
    width: 100%;
    height: auto;
    object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="carouselExampleInterval" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active" data-interval="10000">
                <img src="{% static 'images/car4-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item" data-interval="2000">
                <img src="{% static 'images/car2-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item">
                <img src="{% static 'images/car3-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
        </div>

            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>

            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>

    </div></code>```

Body:
Cannot resize the image in my webpage. images are displayed in full size. I am using Bootstrap 4 carousel component. But the images seem to be non-responsive.

.carousel-item {
    width: 100%;
    height: auto;
    object-fit: cover;
}

The corresponding carousel part is as follows:

            Previous

            Next

Please help.

Body:
you have to specify the img attribute if you want to resize the image:

.carousel-item img {
    width: 100%;
    height: auto;
    object-fit: cover;
}

<div id="carouselExampleInterval" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active" data-interval="10000">
                <img src="{% static 'images/car4-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item" data-interval="2000">
                <img src="{% static 'images/car2-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item">
                <img src="{% static 'images/car3-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
        </div>
        <a class="carousel-control-prev" href="#carouselExampleInterval" role="button" data-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next" href="#carouselExampleInterval" role="button" data-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>


问:
MCTS UCT with a scoring system
I'm trying to solve a variant of 2048 by a Monte-Carlo Tree Search. I found that UCT could a good way to have some trade-off between exploration/exploitation.

My only issue is that all the versions I've seen assume that the score is a win percentage. How can I adapt it to a game where the score is the value of the board at the last state, and thus going from 1-MAX and not a win.

I could normalize the score using the constant c by dividing by MAX but then it would overweight exploration at early stage of the game (since you get bad average score) and overweight exploitation at late stage of the game.

答:
Indeed most of the literature assumes your games are either lost or won and award a score of 0 or 1, which will turn into a win ratio when averaged over the number of games played. Then exploration parameter C is usually set to sqrt(2) which is optimal for the UCB in bandit problems.

To find out what a good C is in general you have to step back a bit and see what the UCT is really doing. If one node in your tree had an exceptionally bad score in the one rollout it had then exploitation says you should never choose it again. But you've only played that node once, so it might have just been bad luck. To acknowledge this you give that node a bonus. How much? Enough to make it a viable choice even if its average score is the lowest possible and some other node has the highest average score possible. Because with enough plays it might turn out that the one rollout your bad node had was indeed a fluke, and the node actually turns out to be pretty reliable with good scores. Of course, if you get more bad scores then it will likely not be bad luck so it won't deserve more rollouts.

So with scores ranging from 0 to 1 a C of sqrt(2) is a good value. If your game has a maximum achievable score then you can normalize your scores by dividing by the max and force your scores into to 0-1 range to suit a C of sqrt(2). Alternatively you don't normalize the scores but multiply C by your maximum score. The effect is the same: the UCT exploration bonus is large enough to give your underdog nodes some rollouts and a chance to prove themselves.

There is an alternative way of setting C dynamically that has given me good results. As you play, you keep track of the highest and lowest scores you've ever seen in each node (and subtree). This is the range of scores possible and this gives you a hint of how big C should be in order to give not well explored underdog nodes a fair chance. Every time i descend into the tree and pick a new root i adjust C to be sqrt(2) * score range for the new root. In addition, as rollouts complete and their scores turn out the be a new highest or lowest score i adjust C in the same way. By continually adjusting C this way as you play but also as you pick a new root you keep C as large as it needs to be to converge but as small as it can be to converge fast. Note that the minimum score is as important as the max: if every rollout will yield at minimum a certain score then C won't need to overcome it. Only the difference between max and min matters.

Title: MCTS UCT with a scoring system


问:
How do I fix the NotImplementedError in Python?
I am a beginner coding so I don't know a lot about python, but if you answered this it would be much appreciated.

This is what I have so far:

```<code>import turtle
def clear1():
  import os
  os.system('cls' if os.name == 'nt' else "printf '\033c'")
</code>```

then a bunch of turtle code. Then after the turtle code:

```<code>choice = input("Want to get started? ")
while choice == "yes" or choice == "Yes":
  clear1()
</code>```

Output:

```<code>NotImplementedError: os is not yet implemented in Skulpt on line 1
</code>```

And I am very confused because I use the exact same algorithm in a different project and it works

Link to current project: https://repl.it/@WeirdDragon/RPS#main.py

Link to project it worked on: https://repl.it/@WeirdDragon/Fortune-teller#main.py

答: From what I can tell, Skulpt uses old and unsupported Python 2.7 for "Python (with turtle)" projects but modern Python 3.8 for non-turtle projects. Apparently, Skulpt's 2.7 does not support the module os. So, you can use either turtle or os but not both.

Body:
I am a beginner coding so I don't know a lot about python, but if you answered this it would be much appreciated.

This is what I have so far:

import turtle
def clear1():
  import os
  os.system('cls' if os.name == 'nt' else "printf '\033c'")

then a bunch of turtle code. Then after the turtle code:

choice = input("Want to get started? ")
while choice == "yes" or choice == "Yes":
  clear1()

Output:

NotImplementedError: os is not yet implemented in Skulpt on line 1

And I am very confused because I use the exact same algorithm in a different project and it works

Link to current project: https://repl.it/@WeirdDragon/RPS#main.py

Link to project it worked on: https://repl.it/@WeirdDragon/Fortune-teller#main.py


问:
TypeError: Cannot read property 'RichEmbed' of undefined
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now Took More Than 2 Days To Find A Solution So I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : TypeError: Cannot read property 'RichEmbed' of undefined(18:35)

My Code :

```<code>1:  module.exports.run = async (bot, message, args) => {
2:
3:      let target = message.guild.member(message.mentions.users.first());
4:      let reason = args.slice(1).join(' ');
5:      let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");
6:
7:      // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
8:
9:      if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
10:
11:      if (!target) return message.reply('please specify a member to ban!');
12:      if (!reason) return message.reply('please specify a reason for this ban!');
13:      if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
14:
15:      let embed = new discord.cache.RichEmbed()
16:          .setColor('RANDOM')
17:          .setThumbnail(target.user.avatarURL)
18:          .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
19:          .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
20:          .addField('Banned Time', message.createdAt)
21:          .addField('Banned At', message.channel)
22:          .addField('Banned Reason', reason)
23:          .addFooter('Banned user information', target.user.displayAvatarURL);
24:
25:      message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
26:      target.ban(reason);
27:      logs.send(embed);
28:  };
</code>```

答:
You have 2 problems with your code:
The first one is that discord is not defined,
and RichEmbed was replaced with MessageEmbed in v12, so you should add this to the top of your code:

```<code>const discord = require('discord.js'); // defines discord.js
</code>```

and if you are using discord.js v12, replace "new discord.cache.RichEmbed()" with:

```<code>let embed = new discord.MessageEmbed(); // define the embed you want to use
</code>```

Body:
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now Took More Than 2 Days To Find A Solution So I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : TypeError: Cannot read property 'RichEmbed' of undefined(18:35)

My Code :

1:  module.exports.run = async (bot, message, args) => {
2:
3:      let target = message.guild.member(message.mentions.users.first());
4:      let reason = args.slice(1).join(' ');
5:      let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");
6:
7:      // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
8:
9:      if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
10:
11:      if (!target) return message.reply('please specify a member to ban!');
12:      if (!reason) return message.reply('please specify a reason for this ban!');
13:      if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
14:
15:      let embed = new discord.cache.RichEmbed()
16:          .setColor('RANDOM')
17:          .setThumbnail(target.user.avatarURL)
18:          .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
19:          .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
20:          .addField('Banned Time', message.createdAt)
21:          .addField('Banned At', message.channel)
22:          .addField('Banned Reason', reason)
23:          .addFooter('Banned user information', target.user.displayAvatarURL);
24:
25:      message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
26:      target.ban(reason);
27:      logs.send(embed);
28:  };

Body:
You have 2 problems with your code:
The first one is that discord is not defined,
and RichEmbed was replaced with MessageEmbed in v12, so you should add this to the top of your code:

const discord = require('discord.js'); // defines discord.js

and if you are using discord.js v12, replace "new discord.cache.RichEmbed()" with:

let embed = new discord.MessageEmbed(); // define the embed you want to use


问:
How to get http request origin in php
I want to create an API, and to authenticate API consumers, I will provide an API KEY, App-id and App-Secret. The problem is that I want to know where the http Request is coming from, so that I can know if the Host that is making que request is the registered Host. For example : www.someone.com has an app-id :0001, app-secret:1200 and api-key:458. If this credentials are used to make A request, I want to know if the requester is really www.someone.com</p>

答:
Technically neither origin nor referer are required HTTP headers, all of these answers are based on specific browser headers sent, and basing your system on different behaviors of clients is a bad idea.

The correct answer is you can't reliably get the client origin on every request because it isn't required as part of the HTTP specification.

Title: How to get http request origin in php


问:
Pandas count occurence of value in dictionary
Given a DF:

```<code>pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })
</code>```

How do i get a count of number of times "Closed" appears in the dict?

```<code>A  B    count
1 {..}  2
2 {..}  1
3 {..}  0
</code>```

I really don't know how to start on this to try

答:
You can try converting the series of dictionary into a dataframe and then stack , then take sum of Closed values on level=0 to get Count per row:

```<code>df['Count_closed'] = pd.DataFrame(df['B'].tolist()).stack().eq("Closed").sum(level=0)
</code>```

```<code>   A                                                  B  Count_closed
0  1  {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'}           2.0
1  2    {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'}           1.0
2  3      {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'}           0.0
</code>```

Body:
Given a DF:

pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })

How do i get a count of number of times "Closed" appears in the dict?

A  B    count
1 {..}  2
2 {..}  1
3 {..}  0

I really don't know how to start on this to try

Body:
You can try converting the series of dictionary into a dataframe and then stack , then take sum of Closed values on level=0 to get Count per row:

df['Count_closed'] = pd.DataFrame(df['B'].tolist()).stack().eq("Closed").sum(level=0)

   A                                                  B  Count_closed
0  1  {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'}           2.0
1  2    {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'}           1.0
2  3      {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'}           0.0


问:
node dotenv won't work with pm2
I have an application where locally (without pm2) all the environment variables in the .env file work just fine using dotenv.

But on the server where I'm using pm2 to run the app, the environment variables remain undefined.

The pm2 commands I'm using to run the app on server are:

```<code>pm2 start myapp/app.js
pm2 startup
pm2 save
</code>```

答:
I had the same problem but it wasnt explained clearly so here is the solution based on
github user vmarchaud comment.
This also fixes the issue people had with @Andy Lorenz solution.

In my case i wanted to create an ecosystem file for multiple apps but i was keep getting

```<code>Error: Cannot find module 'dotenv/config'
</code>```

The solution was easy.
You have to declar cwd, aka the project folder where the dotenv/config will be read from.

```<code>module.exports = {
  apps: [{
    name: 'app1 name',
    script: 'app1.js',
    cwd: '/path/to/folder/',
    exec_mode: 'fork_mode',
    node_args: '-r dotenv/config',
  }, {
    name: 'app2 name',
    script: 'app2.js',
    cwd: '/path/to/folder/',
    instances: 'max',
    exec_mode: 'cluster',
    node_args: '-r dotenv/config',
  }],
};
</code>```

Title: node dotenv won't work with pm2

Body:
I have an application where locally (without pm2) all the environment variables in the .env file work just fine using dotenv.

But on the server where I'm using pm2 to run the app, the environment variables remain undefined.

The pm2 commands I'm using to run the app on server are:

pm2 start myapp/app.js
pm2 startup
pm2 save

Body:
I had the same problem but it wasnt explained clearly so here is the solution based on
github user vmarchaud comment.
This also fixes the issue people had with @Andy Lorenz solution.

In my case i wanted to create an ecosystem file for multiple apps but i was keep getting

Error: Cannot find module 'dotenv/config'

The solution was easy.
You have to declar cwd, aka the project folder where the dotenv/config will be read from.

module.exports = {
  apps: [{
    name: 'app1 name',
    script: 'app1.js',
    cwd: '/path/to/folder/',
    exec_mode: 'fork_mode',
    node_args: '-r dotenv/config',
  }, {
    name: 'app2 name',
    script: 'app2.js',
    cwd: '/path/to/folder/',
    instances: 'max',
    exec_mode: 'cluster',
    node_args: '-r dotenv/config',
  }],
};


问:
Date-time always giving 1200HRS
I'm working on a chatbot and using Dialogflow's sys.date-time entity. So when I'm presenting some dates to the bot, like "Today", or "Feb 14", I always get

```<code>"parameters": {
  "date-time": "2021-02-14T12:00:00Z"
}
</code>```

whereas I want

```<code>"parameters": {
  "date-time": "2021-02-14T00:00:00Z"
}
</code>```

Right now I'm using my app to replace the datetime with hours=0, however, I also want the bot to give

```<code>"parameters": {
  "date-time": "2021-02-14T08:00:00Z"
}
</code>```

when I say "feb 14 8AM" (hour is explictly mentioned), but the app will replace the hours. So gonna have to fix it from Dialogflow side. Any solutions please?

答:
for Dialogflow system entity @sys.date-time this is the default behavior as per ISO-8601 format , what you can do as the fix for this is to instead of using @sys.date-time follow these steps :

use two separate parameters for date and time @sys.date and @sys.time.

Make @sys.date as required and @sys.time as optional.

Set some appropriate default value for @sys.time as 00:00:00 so when time is not given like FEB 14 it will take time as default value .

In your app you can use these two values .

Sample intent

Hope it helps !

Title: Date-time always giving 1200HRS

Body:
I'm working on a chatbot and using Dialogflow's sys.date-time entity. So when I'm presenting some dates to the bot, like "Today", or "Feb 14", I always get

"parameters": {
  "date-time": "2021-02-14T12:00:00Z"
}

whereas I want

"parameters": {
  "date-time": "2021-02-14T00:00:00Z"
}

Right now I'm using my app to replace the datetime with hours=0, however, I also want the bot to give

"parameters": {
  "date-time": "2021-02-14T08:00:00Z"
}

when I say "feb 14 8AM" (hour is explictly mentioned), but the app will replace the hours. So gonna have to fix it from Dialogflow side. Any solutions please?


问:
how to make Widget attributs optiobal in flutter
How can I make widget property as optional in flutter for example :
if widget.image is not null user image property to set background and if it null use color property

```<code>container(
  BoxDecoration(

         if(widget.image){
           image: AssetImage("images/background/background1.jpg",),fit: BoxFit.cover),
         }
         else {
           color : Colors.white
         }
)
</code>```

答:
```<code>Container(
  decoration: widget.image!=null ?
   BoxDecoration(
    image: AssetImage("images/background/background1.jpg",),
    fit: BoxFit.cover
   ):
   BoxDecoration(color : Colors.white)
)
</code>```

Body:
How can I make widget property as optional in flutter for example :
if widget.image is not null user image property to set background and if it null use color property

container(
  BoxDecoration(

         if(widget.image){
           image: AssetImage("images/background/background1.jpg",),fit: BoxFit.cover),
         }
         else {
           color : Colors.white
         }
)


答:
You can do an apply:

```<code>df['count'] = df.B.apply(pd.Series).eq('Closed').sum(1)
</code>```

Output:

```<code>   A                                                  B  count
0  1  {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'}      2
1  2    {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'}      1
2  3      {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'}      0
</code>```

Title: Pandas count occurence of value in dictionary

Body:
You can do an apply:

df['count'] = df.B.apply(pd.Series).eq('Closed').sum(1)

Output:

   A                                                  B  count
0  1  {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'}      2
1  2    {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'}      1
2  3      {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'}      0


问:
MongoDB Atlas Cluster Authecation Failed
I am not able to connect to the MongoDB Atlas cluster that I have made. I entered in the given line of code after I created the cluster and received the error:

I am not able to find any solution to this problem. Please help me

Please see the error here

答:
Follow the instructions on link:
https://docs.atlas.mongodb.com/reference/api/whitelist-api/index.html
It's simple, you have to add your api on the whitelist</p>