问:
ElasticSearch in Windows docker image vm max map count
I am new to Docker and Elasticsearch.
I am using a Windows 7 machine. I am using docker-compose up to bring up the docker container. My yml file has

```<code>elasticsearch:
  image: elasticsearch:5.1.1
  environment:
    ES_JAVA_OPTS: "-Xms1g -Xmx1g"
</code>```

along with other linked images.

I am using docker to bring up the elasticsearch image and when I do so I get the following error

```<code>[36melasticsearch_1   |←[0m ERROR: bootstrap checks failed
[36melasticsearch_1   |←[0m max virtual memory areas vm.max_map_count [65530]  is too low, increase to at least [262144]
[36melasticsearch_1   |←[0m [2017-02-08T11:06:51,752][INFO ][o.e.n.Node
</code>```

I googled for a solution and everywhere they suggest to use
sudo sysctl vm.max_map_count=262144, but in Windows sysctl is not available. No clear steps are given for Windows.

Some other Docker images are up and running on my machine so Docker is working.

Can someone give any clues to solve this issue?

答:
Currently, following this issue, the way to make it work is by wsl -d docker-desktop and sysctl -w vm.max_map_count=262144 there.

Some people got it to work persistently by echo "vm.max_map_count = 262144" > /etc/sysctl.d/99-docker-desktop.conf or echo -e "\nvm.max_map_count = 262144\n" >> /etc/sysctl.d/00-alpine.conf, but none of these worked for me.

Body:
I am new to Docker and Elasticsearch.
I am using a Windows 7 machine. I am using docker-compose up to bring up the docker container. My yml file has

elasticsearch:
  image: elasticsearch:5.1.1
  environment:
    ES_JAVA_OPTS: "-Xms1g -Xmx1g"

along with other linked images.

I am using docker to bring up the elasticsearch image and when I do so I get the following error

[36melasticsearch_1   |←[0m ERROR: bootstrap checks failed
[36melasticsearch_1   |←[0m max virtual memory areas vm.max_map_count [65530]  is too low, increase to at least [262144]
[36melasticsearch_1   |←[0m [2017-02-08T11:06:51,752][INFO ][o.e.n.Node

I googled for a solution and everywhere they suggest to use
sudo sysctl vm.max_map_count=262144, but in Windows sysctl is not available. No clear steps are given for Windows.

Some other Docker images are up and running on my machine so Docker is working.

Can someone give any clues to solve this issue?


来源: stackexchange

问:
Why json hijacking can be prevented using POST method?
I came across the following ASP.NET MVC error, when returning json in a Get method:

This request has been blocked because sensitive information could be
  disclosed to third party web sites when this is used in a GET request.
  To allow GET requests, set JsonRequestBehavior to AllowGet.

Apparently this vulnerability is called json Hijacking. This article explains that a website could be exploited when returning json using Get. But returning json in a Post method is safe.

Why changing Get to Post prevents this attack?

ContentLicense: CC BY-SA 4.0

Body:
Having the request as a POST will prevent any request coming form other domains based on CORS policy unless you configure your server to allow it, which turns this issue to another thing. GET requests on the other hand are allowed by browsers to retrieve resources, like javascript that might have sensitive data from your domain and it happen to be an array not an object.

Updated answer:

You will not actually find a source tells you how GET, POST requests are different for JSON Hijacking attacks. The difference actually is how web servers and browsers are dealing with those requests. JSON hijacking vulnerability is about  malicious websites using an endpoint in your website/app that provides JSON data and response to a GET request (a request that by default allow resources, e.g js, images, text files to be  download), if you change it to POST, they will not be able to include <script> that do a POST request from the src attribute, even inside the script tag POST requests will be prevented by CORS policy.

In the modern browser era we no longer have this type of vulnerability (at least in the form mentioned in the discovery article by Jeremiah Grossman) because of CORS policy.

This also referenced in other related questions


问:
iOS: How to use default web view?
Hi I am using custom webview in iOS for linkedin Auth. I can see google & facebook seems using exactly same view controller interface for their web-view based authentication. but I can't find such view controller.

Is there any webview with defualt interface? Thanks in advance...

Facebook:

Google:

答:
That is a zero-tab modal used by iOS Applications for external authentication. It can look different apps.

This cannot be set to the default Style for a web browser unless the browser is designed that way.

Title: iOS: How to use default web view?


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: Yes C# is considered a high level language.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: zodeus


问:
Connect to MSSQL Database using Flask-SQLAlchemy
I'm trying to connect to a local MSSQL DB through Flask-SQLAlchemy.

Here's a code excerpt from my __init__.py file:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pyodbc://HARRISONS-THINK/LendApp'
db = SQLAlchemy(app)

SQLALCHEMY_TRACK_MODIFICATIONS = False
</code>```

As you can see in SQL Server Management Studio, this information seems to match:

Here is the creation of a simple table in my models.py file:

```<code>from LendApp import db

class Transaction(db.model):
    transactionID = db.Column(db.Integer, primary_key=True)
    amount = db.Column(db.Integer)
    sender = db.Column(db.String(80))
    receiver = db.Column(db.String(80))

    def __repr__(self):
        return 'Transaction ID: {}'.format(self.transactionID)
</code>```

I am then connecting to the database using a Python Console within Pycharm via the execution of these two lines:

```<code>>>> from LendApp import db
>>> db.create_all()
</code>```

This is resulting in the following error:

```<code>DBAPIError: (pyodbc.Error) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
</code>```

The only thing that I can think of is that my database connection string is incorrect. I have tried altering it to more of a standard Pyodbc connection string and including driver={SQL SERVER} but to no prevail.

If anyone could help me out with this it would be highly appreciated.

Thanks

答:
using below solution i get resolve my connection issue with MSSQL server

```<code>params = urllib.parse.quote_plus('DRIVER={SQL Server};SERVER=HARRISONS-THINK;DATABASE=LendApp;Trusted_Connection=yes;')
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params
</code>```

If you are getting any Login failed for User error then please go to this
http://itproguru.com/expert/2014/09/how-to-fix-login-failed-for-user-microsoft-sql-server-error-18456-step-by-step-add-sql-administrator-to-sql-management-studio/.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to connect to a local MSSQL DB through Flask-SQLAlchemy.

Here's a code excerpt from my __init__.py file:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pyodbc://HARRISONS-THINK/LendApp'
db = SQLAlchemy(app)

SQLALCHEMY_TRACK_MODIFICATIONS = False

As you can see in SQL Server Management Studio, this information seems to match:

Here is the creation of a simple table in my models.py file:

from LendApp import db

class Transaction(db.model):
    transactionID = db.Column(db.Integer, primary_key=True)
    amount = db.Column(db.Integer)
    sender = db.Column(db.String(80))
    receiver = db.Column(db.String(80))

    def __repr__(self):
        return 'Transaction ID: {}'.format(self.transactionID)

I am then connecting to the database using a Python Console within Pycharm via the execution of these two lines:

>>> from LendApp import db
>>> db.create_all()

This is resulting in the following error:

DBAPIError: (pyodbc.Error) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

The only thing that I can think of is that my database connection string is incorrect. I have tried altering it to more of a standard Pyodbc connection string and including driver={SQL SERVER} but to no prevail.

If anyone could help me out with this it would be highly appreciated.

Thanks

Body:
using below solution i get resolve my connection issue with MSSQL server

params = urllib.parse.quote_plus('DRIVER={SQL Server};SERVER=HARRISONS-THINK;DATABASE=LendApp;Trusted_Connection=yes;')
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params

If you are getting any Login failed for User error then please go to this
http://itproguru.com/expert/2014/09/how-to-fix-login-failed-for-user-microsoft-sql-server-error-18456-step-by-step-add-sql-administrator-to-sql-management-studio/.


问:
How to write a SQL query to find values which contain '%' symbol?
Value is a string which contains alphanumeric characters and special characters also. And I am trying to display values which contains '%'.

答:
You could just use string functions:

```<code>select val from mytable where locate(val, '%')
</code>```

If you want to do this with like, you need the escape option:

```<code>select val from mytable where val like '%|%%' escape '|';
</code>```

Body:
You could just use string functions:

select val from mytable where locate(val, '%')

If you want to do this with like, you need the escape option:

select val from mytable where val like '%|%%' escape '|';


问:
How to record video call using QuickBlox
I am using QuickbloxWebRTC framework in ios for video calling. But i don't see any option to record this video call. Can anyone help me if i'm missing something.

My Quickblox sdk version is 2.6.5
I am following this sample for video calling.

sample-videochat-webrtc

Thanks

答: Oh! If that's the case, maybe you can also use the tool I installed. You can visit the official site of AceThinker Screen Grabber Pro to install it. Then, click the "Record" button and hit "Fullscreen" to start recording your video call on QuickBlox. Next, just simply hit the "Stop" button on the floating toolbar to end and save your recorded call automatically. </p>


问:
How do I solve this inheritance problem in rust?
first of all the obligatory "I am new to Rust": I am.

So I have the following problem:

I have two(or more) structs of data, that all implement some common behaviour in addition their own behaviour. I have a list of these structs (or rather: of the 'supertype'), I need to access some of their shared behaviour and some of their individual behaviour.
My Question is: how do I do that in Rust.

To further illustrate my question I have come up with a code comparision between Kotlin and Rust. Kotlin works as I want it to, Rust does not (yet).

In Kotlin the code may look like this(using the plain, old inheritance abstraction):

```<code>interface Animal {
    fun eat()
    fun sleep()
}
class Cat(val name: String) : Animal {
    fun meow()              { println("meow") }

    override fun eat()      { println("cat $name is eating fish(or lasagne)") }
    override fun sleep()    { println("cat $name sleeps inside") }
}
class Lion(val tag_id: Int) : Animal {
    fun roar()              { println("roar") }

    override fun eat()      { println("lion(tag=${tag_id} is eating gazelle") }
    override fun sleep()    { println("lion(tag=${tag_id} sleeps outside") }
}

var animals: MutableList<Animal> = ArrayList()
fun main() {
    animals.add(Cat("Garfield"))
    animals.add(Lion(12))
    //later:
    for (animal in animals) {
        animal.sleep()
        if (animal is Lion)
            animal.roar()
    }
}
</code>```

In Rust I came up with the following code (which does not allow an 'instance_of' type function):

```<code>trait Animal {
    fn eat(&self);
    fn sleep(&self);
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals {
        animal.sleep()
        //HOW DO I ACCESS THE CONCRETE STRUCT HERE?
    }
}
</code>```

Playground

I realize this may be a stupid question, or show how I am 'still trapped in the non-Rust thinking', but I am at kind of an Impass here and need just a little bit of assistence.

答:
Type checked conditions can be implemented by providing a as_<type> function for every subtype:

```<code>trait Animal {
    fn eat(&self);
    fn sleep(&self);
    fn as_roaring(&self)->Option<&dyn Roaring>;
    fn as_meowing(&self)->Option<&dyn Meowing>;
}
</code>```

The implementation of Lion would look like:

```<code>impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
    fn as_roaring(&self)->Option<&dyn Roaring> {Some(self)}
    fn as_meowing(&self)->Option<&dyn Meowing> {None}
}
</code>```

and of the loop:

```<code>    for animal in animals {
        animal.sleep();
        if let Some(roaring) = animal.as_roaring() {
          roaring.roar();
        }
    }
</code>```

Playground.

Body:
first of all the obligatory "I am new to Rust": I am.

So I have the following problem:

I have two(or more) structs of data, that all implement some common behaviour in addition their own behaviour. I have a list of these structs (or rather: of the 'supertype'), I need to access some of their shared behaviour and some of their individual behaviour.
My Question is: how do I do that in Rust.

To further illustrate my question I have come up with a code comparision between Kotlin and Rust. Kotlin works as I want it to, Rust does not (yet).

In Kotlin the code may look like this(using the plain, old inheritance abstraction):

interface Animal {
    fun eat()
    fun sleep()
}
class Cat(val name: String) : Animal {
    fun meow()              { println("meow") }

    override fun eat()      { println("cat $name is eating fish(or lasagne)") }
    override fun sleep()    { println("cat $name sleeps inside") }
}
class Lion(val tag_id: Int) : Animal {
    fun roar()              { println("roar") }

    override fun eat()      { println("lion(tag=${tag_id} is eating gazelle") }
    override fun sleep()    { println("lion(tag=${tag_id} sleeps outside") }
}

var animals: MutableList<Animal> = ArrayList()
fun main() {
    animals.add(Cat("Garfield"))
    animals.add(Lion(12))
    //later:
    for (animal in animals) {
        animal.sleep()
        if (animal is Lion)
            animal.roar()
    }
}

In Rust I came up with the following code (which does not allow an 'instance_of' type function):

trait Animal {
    fn eat(&self);
    fn sleep(&self);
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals {
        animal.sleep()
        //HOW DO I ACCESS THE CONCRETE STRUCT HERE?
    }
}

Playground

I realize this may be a stupid question, or show how I am 'still trapped in the non-Rust thinking', but I am at kind of an Impass here and need just a little bit of assistence.

Body:
Type checked conditions can be implemented by providing a as_<type> function for every subtype:

trait Animal {
    fn eat(&self);
    fn sleep(&self);
    fn as_roaring(&self)->Option<&dyn Roaring>;
    fn as_meowing(&self)->Option<&dyn Meowing>;
}

The implementation of Lion would look like:

impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
    fn as_roaring(&self)->Option<&dyn Roaring> {Some(self)}
    fn as_meowing(&self)->Option<&dyn Meowing> {None}
}

and of the loop:

    for animal in animals {
        animal.sleep();
        if let Some(roaring) = animal.as_roaring() {
          roaring.roar();
        }
    }

Playground.


问:
Create React App SyntaxError: Unexpected Token
I am following a tutorial and I cannot get create-react-app to start because it keeps running into this syntax error. I am using node v8.1.4 and npm v6.14.5. The following is my code. Not sure what the error is. </p>

```<code>yeryndo@Yeryn:/mnt/c/Users/yeryn/desktop/Exercise Files/ch02/02_02/start$ create-react-app react-is-fun
/usr/local/lib/node_modules/create-react-app/node_modules/chalk/source/index.js:103
        ...styles,
        ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/create-react-app/createReactApp.js:37:15)
</code>```

答:
The problem is caused by this function call in the chalk library:

```<code>const proto = Object.defineProperties(() => {}, {
    ...styles,
    level: {
         // omitted
    }
}
</code>```

According to MDN, spread syntax in object literals (as used in ...styles) has been supported since Node.js 8.3.0 (8.0.0 when running with the --harmony flag).

Since you're using version 8.1.4, you have two basic options:

Upgrade Node.js

Run Node.js with the --harmony flag

Body:
I am following a tutorial and I cannot get create-react-app to start because it keeps running into this syntax error. I am using node v8.1.4 and npm v6.14.5. The following is my code. Not sure what the error is.

yeryndo@Yeryn:/mnt/c/Users/yeryn/desktop/Exercise Files/ch02/02_02/start$ create-react-app react-is-fun
/usr/local/lib/node_modules/create-react-app/node_modules/chalk/source/index.js:103
        ...styles,
        ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/create-react-app/createReactApp.js:37:15)

Body:
The problem is caused by this function call in the chalk library:

const proto = Object.defineProperties(() => {}, {
    ...styles,
    level: {
         // omitted
    }
}

According to MDN, spread syntax in object literals (as used in ...styles) has been supported since Node.js 8.3.0 (8.0.0 when running with the --harmony flag).

Since you're using version 8.1.4, you have two basic options:

Upgrade Node.js

Run Node.js with the --harmony flag


问:
Javascript Border and button line break question
I'm having a few issues with my javascript webpage. My first question is how to create a small border that wraps around a title? The bottom portion of my professor's sample webpage looks like this: https://i.imgur.com/4DVozv9.png

The bottom portion of my webpage so far looks like this: https://i.imgur.com/8STmOGd.png

I don't understand how to make that small border that circles around the "Shipping Method", "Shipping Address", and "Payment Details" titles.

Also for some reason the "
" tag on my "Complete Payment" button isn't placing my button on the next line for some reason. Here is my code so far, note though that it's incomplete so my functions and other features aren't ready yet, right now I'm just focusing purely on presentation. Thank you for your time.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>YOUR NAME  Final Project Checkout</title>
    <link href="layout.css" type="text/css" rel="stylesheet">

<script type="text/javascript" src="guest-functions.js"></script>
<script type="text/javascript" src="cart-functions.js"></script>

<script>
window.onload=function(){
    setGuest();
    updateCartTotal();
}

</script>

</head>

<body>
<header><img src="90s-Gamers-Logo.png" width="798" height="82" alt="My Company"/></header>
<nav>
<form id="form1" name="form1" method="post">
<p>Choose a page to visit:<br>
  <select name="select" id="select" onchange="location = this.options[this.selectedIndex].value;">
    <option value="index.html">Home</option>
    <option value="shop.html">Shop</option>
    <option value="cart.html">Cart</option>
    <option value="checkout.html" selected="selected">Checkout</option>
  </select>
</p><br>

<p><b>Welcome Guest!</b></p>
<p>Enter your name:</p>
<input id="sign-in-text"><br>
<button onclick="setGuest()" id="sign-in-button">Sign-In</button><br><br>
<p>Your shopping cart is now</p>
<!--Need variable here-->
<p><b>empty!</b></p>
</form>

<p> </p>

<div id="divGuestArea"> </div>
<p> </p>

<div id="divCartSummary"> </div>

</nav>

<div id="main">
<h1>Checkout</h1>
<!--<p>This is where the transaction would take place so create a form here to take care of that final process as appropriate. Such form fields as contact info, shipping method, payment method, receipt, etc. Use HTML attributes wisely to help with validation and write JavaScript to validate any needed fields that are not sure to be validated by this HTML.</p>
<p>Connect your form to a "thankyou.html" page that you create so that after the form is submitted and found to be filled out properly, you thank them by name on "thankyou.html".</p>-->
<table border="1" cellspacing="0" cellpadding="6" summary="Table of Quantity, Description, Price, and Product Totals">
            <tbody>
               <tr>
                <td><b>Quantity</b></td>
                <td><b>Description</b></td>
                <td><b>Price</b></td>
                <td><b>Product Total</b></td>
              </tr>
              <tr style="text-align:right">
                <td>later</td>
                <td>later</td>
                <td>later</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td>later</td>
                <td>later</td>
                <td>later</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td colspan="3">Subtotal:</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td colspan="3">Tax:</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td colspan="3"><b>Grand total:</b></td>
                <td><b>later</b></td>
              </tr>
            </tbody>
        </table><br>
<p>Display total amount</p>
<p>Shipping Method</p>
<p> <input type="radio" name="ShipType" id="standard" value="2">
                <label for="standard">Standard Shipping ($2)</label>
                <input type="radio" name="ShipType" id="2-day" value="5">
                <label for="2-day">2-Day Shipping ($5)</label>
                <input type="radio" name="ShipType" id="overnight" value="10">
                <label for="overnight">Overnight Shipping ($10)</label>
                <br>

<p>Shipping Address</p>
    Full Name:
    <input type="text" id="FullName" name="FullName">
    Street Address:
    <input type="text" id="StreetAddress" name="StreetAddress"><br><br>
    City:
    <input type="text" id="City" name="City">
    State/Province/Region:
    <input type="text" id="State" name="State"><br><br>
    ZIP:
    <input type="text" id="Zip" name="Zip">
    Country:
    <input type="text" id="Country" name="Country"><br><br>
    Phone Number:
    <input type="text" id="PhoneNumber" name="PhoneNumber"><br>

    <p>Payment Details</p>
    <select id="selPayment" name="selPayment" onChange="getSelectValue();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="Visa">Visa Credit</option>
                    <option value="MasterCard">MasterCard Credit</option>
                    <option value="American Express">American Express Credit</option>
                    <option value="Debit Card">Debit Card</option>
                    <option value="Pay Pal">Paypal</option>
                </select> <br><br>

    Card #:
    <input type="text" id="CardNumber" name="CardNumber"><br><br>

    Expiration Month:
    <select id="selMonth" name="selMonth" onChange="getSelectMonth();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="January">January</option>
                    <option value="February">Febraury</option>
                    <option value="March">March</option>
                    <option value="April">April</option>
                    <option value="May">May</option>
                    <option value="June">June</option>
                    <option value="July">July</option>
                    <option value="August">August</option>
                    <option value="September">September</option>
                    <option value="October">October</option>
                    <option value="November">November</option>
                    <option value="December">December</option>
                </select> <br><br>
    Expiration Year:
    <select id="selYear" name="selYear" onChange="getSelectYear();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="2020">2020</option>
                    <option value="2021">2021</option>
                    <option value="2022">2022</option>
                    <option value="2023">2023</option>
                    <option value="2024">2024</option>

        <br><p>
        <input type="button" value="Complete Payment"
               onclick="storeAndGo();">
    </p>
<footer>
Copyright 2020, 90's Gamers.
</footer>
</div>
</body>
</html>
</code>```

答: You can add a div to your 3 sections, and you can set border to this.</p>

Body:
I'm having a few issues with my javascript webpage. My first question is how to create a small border that wraps around a title? The bottom portion of my professor's sample webpage looks like this: https://i.imgur.com/4DVozv9.png

The bottom portion of my webpage so far looks like this: https://i.imgur.com/8STmOGd.png

I don't understand how to make that small border that circles around the "Shipping Method", "Shipping Address", and "Payment Details" titles.

Also for some reason the "
" tag on my "Complete Payment" button isn't placing my button on the next line for some reason. Here is my code so far, note though that it's incomplete so my functions and other features aren't ready yet, right now I'm just focusing purely on presentation. Thank you for your time.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>YOUR NAME  Final Project Checkout</title>
    <link href="layout.css" type="text/css" rel="stylesheet">

<form id="form1" name="form1" method="post">

Choose a page to visit:

  <select name="select" id="select" onchange="location = this.options[this.selectedIndex].value;">
    <option value="index.html">Home</option>
    <option value="shop.html">Shop</option>
    <option value="cart.html">Cart</option>
    <option value="checkout.html" selected="selected">Checkout</option>
  </select>

Welcome Guest!

Enter your name:

<input id="sign-in-text">

<button onclick="setGuest()" id="sign-in-button">Sign-In</button>

Your shopping cart is now

empty!

</form>

Checkout

                Quantity
                Description
                Price
                Product Total

                later
                later
                later
                later

                later
                later
                later
                later

                Subtotal:
                later

                Tax:
                later

                Grand total:
                later

Display total amount

Shipping Method

 <input type="radio" name="ShipType" id="standard" value="2">
                Standard Shipping ($2)
                <input type="radio" name="ShipType" id="2-day" value="5">
                2-Day Shipping ($5)
                <input type="radio" name="ShipType" id="overnight" value="10">
                Overnight Shipping ($10)

Shipping Address

    Full Name:
    <input type="text" id="FullName" name="FullName">
    Street Address:
    <input type="text" id="StreetAddress" name="StreetAddress">

    City:
    <input type="text" id="City" name="City">
    State/Province/Region:
    <input type="text" id="State" name="State">

    ZIP:
    <input type="text" id="Zip" name="Zip">
    Country:
    <input type="text" id="Country" name="Country">

    Phone Number:
    <input type="text" id="PhoneNumber" name="PhoneNumber">

Payment Details

    <select id="selPayment" name="selPayment" onChange="getSelectValue();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="Visa">Visa Credit</option>
                    <option value="MasterCard">MasterCard Credit</option>
                    <option value="American Express">American Express Credit</option>
                    <option value="Debit Card">Debit Card</option>
                    <option value="Pay Pal">Paypal</option>
                </select>

    Card #:
    <input type="text" id="CardNumber" name="CardNumber">

    Expiration Month:
    <select id="selMonth" name="selMonth" onChange="getSelectMonth();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="January">January</option>
                    <option value="February">Febraury</option>
                    <option value="March">March</option>
                    <option value="April">April</option>
                    <option value="May">May</option>
                    <option value="June">June</option>
                    <option value="July">July</option>
                    <option value="August">August</option>
                    <option value="September">September</option>
                    <option value="October">October</option>
                    <option value="November">November</option>
                    <option value="December">December</option>
                </select>

    Expiration Year:
    <select id="selYear" name="selYear" onChange="getSelectYear();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="2020">2020</option>
                    <option value="2021">2021</option>
                    <option value="2022">2022</option>
                    <option value="2023">2023</option>
                    <option value="2024">2024</option>

        <input type="button" value="Complete Payment"
               onclick="storeAndGo();">

Copyright 2020, 90's Gamers.


问:
Eclipse Search Menus disabled randomly
I use Eclipse 3.3 in my daily work, and have also used Eclipse 3.2 extensively as well.  In both versions, sometimes the Search options (Java Search, File Search, etc) in the menu get disabled, seemingly at random times.  However, with Ctrl+H, I am able to access the search functionality.  Does anyone know why this happens?  Has it been fixed in Eclipse 3.4?

答:
A late comment for anyone getting bitten by this, but I found "eclipse -clean" fixed it => this does a cleanup of the workspace before starting

Thanks http://letsgetdugg.com/2009/04/19/recovering-a-corrupt-eclipse-workspace/ for the tip, after I guessed my workspace might be corrupt.

Title: Eclipse Search Menus disabled randomly

LastEditorDisplayName: Craig Angus


问:
Objective-C Blocks: Incompatible block pointer types
I'm trying to implement a block call. Here is my method:

```<code>- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL) = ^(id obj, NSUInteger idx, BOOL stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];

    [videoGames enumerateObjectsUsingBlock:MyBlock];
}
</code>```

But on this line:

[videoGames enumerateObjectsUsingBlock:MyBlock];

I'm getting this error:

Incompatible block pointer types sending 'void (^__strong)(__strong id, NSUInteger, BOOL)' to parameter of type 'void (^ _Nonnull)(id  _Nonnull __strong, NSUInteger, BOOL * _Nonnull)'

Any of you knows what I'm doing wrong or how can I fix this?

I'll really appreciate your help.

答:
The 3rd parameter of MyBlock should be the pointer of BOOL.

So, add * like below

```<code>     void (^MyBlock)(id, NSUInteger, BOOL*) = ^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"Video game %@", (NSString *)obj);
     };
</code>```

https://developer.apple.com/documentation/foundation/nsarray/1415846-enumerateobjectsusingblock?language=objc

(void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block;

Body:
I'm trying to implement a block call. Here is my method:

- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL) = ^(id obj, NSUInteger idx, BOOL stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];

    [videoGames enumerateObjectsUsingBlock:MyBlock];
}

But on this line:

[videoGames enumerateObjectsUsingBlock:MyBlock];

I'm getting this error:

Incompatible block pointer types sending 'void (^__strong)(__strong id, NSUInteger, BOOL)' to parameter of type 'void (^ _Nonnull)(id  _Nonnull __strong, NSUInteger, BOOL * _Nonnull)'

Any of you knows what I'm doing wrong or how can I fix this?

I'll really appreciate your help.

Body:
The 3rd parameter of MyBlock should be the pointer of BOOL.

So, add * like below

     void (^MyBlock)(id, NSUInteger, BOOL*) = ^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"Video game %@", (NSString *)obj);
     };

https://developer.apple.com/documentation/foundation/nsarray/1415846-enumerateobjectsusingblock?language=objc

(void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block;


问:
R - rbind an lapply output with the list of dataframes by matching names

Goal

My primary aim is to add a mean row at by somehow rbind the mean from the mean list to the dataframe list I have create to create larger dataframes within the data frame list. I wrote a lot for this question so I hope you could help me in my case. If anything is unclear, please comment!

Code

Suppose you have three different data frames that you want to create below:

```<code>df1 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
                  bb = sample(1:10, 5, replace = TRUE),
                  cc = sample(1:10, 5, replace = TRUE),
                  row.names = c("a", "b", "c", "d", "e"))

df2 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
                  bb = sample(1:10, 5, replace = TRUE),
                  cc = sample(1:10, 5, replace = TRUE),
                  row.names = c("a", "b", "c", "d", "e"))

df3 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
                  bb = sample(1:10, 5, replace = TRUE),
                  cc = sample(1:10, 5, replace = TRUE),
                  row.names = c("a", "b", "c", "d", "e"))
</code>```

Doing this will yield these outputs in the console for this example:

```<code>> df1 #the arrow on the left specifies the console entry
  aa bb cc
a  6  9  5
b  2  6  4
c  6  2  3
d 10  4  8
e  3  1  3
> df2
  aa bb cc
a  7  9 10
b  2  7  5
c  1  5  7
d  8  5  5
e  9  3  5
> df3
  aa bb cc
a  2  6  8
b  3  7  7
c  1  4  2
d  4  9  9
e  8  7  3
</code>```

Now I want to put these in a list so save the amount of work I have to do (hopefully!):

```<code>df_list <- list(df1=df1, df2=df2, df3=df3)
#Kept the names for future reference (so that I could write df_list$df1 instead of df_list[[1]]
</code>```

Giving me a respectable list identical to the df1-3 outputs, just all together:

```<code>> df_list
$df1
  aa bb cc
a  6  9  5
b  2  6  4
c  6  2  3
d 10  4  8
e  3  1  3

$df2
  aa bb cc
a  7  9 10
...
</code>```

Now I wanted to create perform basically a colMean across my data but I didn't find a more efficient way to do this other than to use lapplywith mean:

```<code>mean_lst <- lapply(df_list, function(x) {lapply(x[,1:ncol(x)], mean)}) #finding means of columns
</code>```

The code above is nested in a weird way but it gave the result that I was looking for (if there is a better way to achieve nearly identical, feel free to comment about that). It gave me an interesting result that looks usable...? I'm new to R so I am not sure how to use this properly. Take a look at the mean_lst output:

```<code>> mean_lst
$df1
$df1$aa
[1] 5.4

$df1$bb
[1] 4.4

...

$df3$cc
[1] 5.8
</code>```

The Struggle(is.Real) and Question

I have tried rbind to no avail and I don't quite understand how I can use this output (or any other output) so that I can calculate each dataframe means without having to do them one by one, without having to extract dataframes from the list and write identical code. My dream output would look something like this, applying the mean_lst output to each dataframe within the df_list using rbind:

```<code>> df_list$df1
      aa  bb  cc
   a   6   9   5
   b   2   6   4
   c   6   2   3
   d  10   4   8
   e   3   1   3
mean 5.4 4.4 4.6
</code>```

Would anyone know how to write such code, if it exists? Or is there a more efficient to write colMeans for each of these columns in dataframes within lists, without having to explicitly write out the dataframe names? Thank you so much in advance!

答:
Instead of using lapply to calculate column mean, you can use colMeans to calculate column wise mean of the entire dataframe and rbind to your original data.

```<code>df_list <- lapply(df_list, function(x) rbind(x, mean = colMeans(x, na.rm = TRUE)))
df_list

#$df1
#      aa  bb   cc
#a    1.0 3.0  2.0
#b    4.0 2.0  9.0
#c    5.0 9.0 10.0
#d    1.0 1.0  4.0
#e    1.0 9.0  2.0
#mean 2.4 4.8  5.4

#$df2
#       aa bb  cc
#a    10.0  3 7.0
#b     4.0  6 6.0
#c     7.0  7 1.0
#d     4.0  3 9.0
#e     9.0  6 3.0
#mean  6.8  5 5.2

#$df3
#      aa  bb   cc
#a    5.0 5.0 10.0
#b    6.0 3.0  4.0
#c    7.0 6.0  8.0
#d    5.0 6.0 10.0
#e    4.0 2.0  2.0
#mean 5.4 4.4  6.8
</code>```

Body:
Goal

My primary aim is to add a mean row at by somehow rbind the mean from the mean list to the dataframe list I have create to create larger dataframes within the data frame list. I wrote a lot for this question so I hope you could help me in my case. If anything is unclear, please comment!

Code

Suppose you have three different data frames that you want to create below:

df1 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
                  bb = sample(1:10, 5, replace = TRUE),
                  cc = sample(1:10, 5, replace = TRUE),
                  row.names = c("a", "b", "c", "d", "e"))

df2 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
                  bb = sample(1:10, 5, replace = TRUE),
                  cc = sample(1:10, 5, replace = TRUE),
                  row.names = c("a", "b", "c", "d", "e"))

df3 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
                  bb = sample(1:10, 5, replace = TRUE),
                  cc = sample(1:10, 5, replace = TRUE),
                  row.names = c("a", "b", "c", "d", "e"))

Doing this will yield these outputs in the console for this example:

> df1 #the arrow on the left specifies the console entry
  aa bb cc
a  6  9  5
b  2  6  4
c  6  2  3
d 10  4  8
e  3  1  3
> df2
  aa bb cc
a  7  9 10
b  2  7  5
c  1  5  7
d  8  5  5
e  9  3  5
> df3
  aa bb cc
a  2  6  8
b  3  7  7
c  1  4  2
d  4  9  9
e  8  7  3

Now I want to put these in a list so save the amount of work I have to do (hopefully!):

df_list <- list(df1=df1, df2=df2, df3=df3)
#Kept the names for future reference (so that I could write df_list$df1 instead of df_list[[1]]

Giving me a respectable list identical to the df1-3 outputs, just all together:

> df_list
$df1
  aa bb cc
a  6  9  5
b  2  6  4
c  6  2  3
d 10  4  8
e  3  1  3

$df2
  aa bb cc
a  7  9 10
...

Now I wanted to create perform basically a colMean across my data but I didn't find a more efficient way to do this other than to use lapplywith mean:

mean_lst <- lapply(df_list, function(x) {lapply(x[,1:ncol(x)], mean)}) #finding means of columns

The code above is nested in a weird way but it gave the result that I was looking for (if there is a better way to achieve nearly identical, feel free to comment about that). It gave me an interesting result that looks usable...? I'm new to R so I am not sure how to use this properly. Take a look at the mean_lst output:

> mean_lst
$df1
$df1$aa
[1] 5.4

$df1$bb
[1] 4.4

...

$df3$cc
[1] 5.8

The Struggle(is.Real) and Question

I have tried rbind to no avail and I don't quite understand how I can use this output (or any other output) so that I can calculate each dataframe means without having to do them one by one, without having to extract dataframes from the list and write identical code. My dream output would look something like this, applying the mean_lst output to each dataframe within the df_list using rbind:

> df_list$df1
      aa  bb  cc
   a   6   9   5
   b   2   6   4
   c   6   2   3
   d  10   4   8
   e   3   1   3
mean 5.4 4.4 4.6

Would anyone know how to write such code, if it exists? Or is there a more efficient to write colMeans for each of these columns in dataframes within lists, without having to explicitly write out the dataframe names? Thank you so much in advance!

Body:
Instead of using lapply to calculate column mean, you can use colMeans to calculate column wise mean of the entire dataframe and rbind to your original data.

df_list <- lapply(df_list, function(x) rbind(x, mean = colMeans(x, na.rm = TRUE)))
df_list

#$df1
#      aa  bb   cc
#a    1.0 3.0  2.0
#b    4.0 2.0  9.0
#c    5.0 9.0 10.0
#d    1.0 1.0  4.0
#e    1.0 9.0  2.0
#mean 2.4 4.8  5.4

#$df2
#       aa bb  cc
#a    10.0  3 7.0
#b     4.0  6 6.0
#c     7.0  7 1.0
#d     4.0  3 9.0
#e     9.0  6 3.0
#mean  6.8  5 5.2

#$df3
#      aa  bb   cc
#a    5.0 5.0 10.0
#b    6.0 3.0  4.0
#c    7.0 6.0  8.0
#d    5.0 6.0 10.0
#e    4.0 2.0  2.0
#mean 5.4 4.4  6.8


问:
Flutter project for Parsing Json Array
I have two types of Json for my project ,i want to parse this json from from URL & I have one TextField in my App if i enter Register number in Textfield i want to get back the Halllocation or name.

```<code>{
   "Sheet1":[
      {
         "RegisterNumber":1718301002,
         "HallLocation":"224-MBA Block"
      },
      {
         "RegisterNumber":1718301005,
         "HallLocation":"224-MBA Block"
      }
   ]
}
</code>```

and

```<code>{
   "Sheet1":[
      {
         "":"",
         "id":1517102001,
         "name":"103 - AI Building"
      }
   ]
}
</code>```

答:
After fetching that list of data you can use where to filter out the object which has the inserted Register Number in TextField,

Here is the example:

```<code>http.Response responseData = await http.get(url);
dynamic apiData = jsonDecode(responseData.body).where((item) =>
 item["RegisterNumber" ].toLowerCase() == insertedRegisterNumber.toLowerCase()
);

</code>```

Now use that returned apiData object to retrieve any value stored in it.

Here is a link to source code which does exactly this but with Flutter api json data.

https://github.com/TheKetan2/stackoverflow_answers/blob/master/lib/flutter_api_example.dart

Title: Flutter project for Parsing Json Array

Body:
I have two types of Json for my project ,i want to parse this json from from URL & I have one TextField in my App if i enter Register number in Textfield i want to get back the Halllocation or name.

{
   "Sheet1":[
      {
         "RegisterNumber":1718301002,
         "HallLocation":"224-MBA Block"
      },
      {
         "RegisterNumber":1718301005,
         "HallLocation":"224-MBA Block"
      }
   ]
}

and

{
   "Sheet1":[
      {
         "":"",
         "id":1517102001,
         "name":"103 - AI Building"
      }
   ]
}

Body:
After fetching that list of data you can use where to filter out the object which has the inserted Register Number in TextField,

Here is the example:

http.Response responseData = await http.get(url);
dynamic apiData = jsonDecode(responseData.body).where((item) =>
 item["RegisterNumber" ].toLowerCase() == insertedRegisterNumber.toLowerCase()
);

Now use that returned apiData object to retrieve any value stored in it.

Here is a link to source code which does exactly this but with Flutter api json data.

https://github.com/TheKetan2/stackoverflow_answers/blob/master/lib/flutter_api_example.dart


答:
We can loop over the list with lapply and rbind with the colMeans of the data

```<code>df_list <- lapply(df_list, function(x) rbind(x, mean = colMeans(x)))

df_list
#$df1
#      aa  bb   cc
#a    8.0 2.0  9.0
#b    5.0 8.0  3.0
#c    8.0 9.0  3.0
#d    7.0 4.0  7.0
#e    5.0 5.0 10.0
#mean 6.6 5.6  6.4

#$df2
#      aa bb cc
#a    4.0  3  9
#b    8.0  9  6
#c    2.0  6  4
#d    1.0  5  8
#e    7.0  2  8
#mean 4.4  5  7

#$df3
#      aa  bb cc
#a    9.0 5.0  1
#b    4.0 5.0  9
#c    8.0 9.0  7
#d    9.0 5.0  9
#e    1.0 3.0  9
#mean 6.2 5.4  7
</code>```

Or with a Map/lapply

```<code>Map(rbind, df_list, mean =lapply(df_list, colMeans))
</code>```

Or with purrr

```<code>library(purrr)
library(tibble)
library(dplyr)
df_list <- map(df_list, ~  colMeans(.x) %>%
                                     bind_rows(.x, .))
</code>```

Or using summarise/across

```<code>df_list %>%
    map(~ .x %>%
            summarise(across(where(is.numeric), mean)) %>%
              `row.names<-`(., 'mean') %>%
           bind_rows(.x, .))
</code>```

Title: R - rbind an lapply output with the list of dataframes by matching names

Body:
We can loop over the list with lapply and rbind with the colMeans of the data

df_list <- lapply(df_list, function(x) rbind(x, mean = colMeans(x)))

df_list
#$df1
#      aa  bb   cc
#a    8.0 2.0  9.0
#b    5.0 8.0  3.0
#c    8.0 9.0  3.0
#d    7.0 4.0  7.0
#e    5.0 5.0 10.0
#mean 6.6 5.6  6.4

#$df2
#      aa bb cc
#a    4.0  3  9
#b    8.0  9  6
#c    2.0  6  4
#d    1.0  5  8
#e    7.0  2  8
#mean 4.4  5  7

#$df3
#      aa  bb cc
#a    9.0 5.0  1
#b    4.0 5.0  9
#c    8.0 9.0  7
#d    9.0 5.0  9
#e    1.0 3.0  9
#mean 6.2 5.4  7

Or with a Map/lapply

Map(rbind, df_list, mean =lapply(df_list, colMeans))

Or with purrr

library(purrr)
library(tibble)
library(dplyr)
df_list <- map(df_list, ~  colMeans(.x) %>%
                                     bind_rows(.x, .))

Or using summarise/across

df_list %>%
    map(~ .x %>%
            summarise(across(where(is.numeric), mean)) %>%
              `row.names<-`(., 'mean') %>%
           bind_rows(.x, .))


问:
Is an init-declarator a prvalue expression

int c = 0;
```

Consider the above code,thereof,c = 0 is an init-declarator and it's also an expression,Becuase of these rules:

init-declarator:

  declarator initializer(opt)

A full-expression is:

  [...]

  an init-declarator or a mem-initializer, including the constituent expressions of the initializer,

As long as an expression,it will have a value category.

A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears.

The evaluation of a = 0 will initialize object a.So, Is the full-expression c=0 a prvalue expression?If I misunderstand it,please correct me.

答:
Consider the above code,thereof,c = 0 is an init-declarator and it's also an expression

That's not how C++ parsing works. c = 0 by itself may be an expression (if it is within a context where expressions are allowed), but that's not how int c = 0; gets parsed. You have to follow the actual C++ grammar rules.

int c = 0; is a simple-declaration, containing a decl-specifier-seq and an optional init-declarator-list. The latter is a sequence of one or more init-declarator terms. And this grammar has two components: a declarator and an optional initializer. Grammatically speaking, the decl-specifier-seq is where int goes, the declarator is the c part, and the initializer is the = 0 bit.

The text of an init-declarator is something that may in some cases be parsed as an expression. But what something is parsed as is determined by the grammar rules. And the grammar rules of simple-declaration does not allow a decl-specifier-seq followed by expression. Therefore, what follows it is not parsed as an expression even if it could be.

So init-declarator is not an expression, even if the text looks like it could be.

Now, there is the concept of a "full-expression". One of the things that get to be called a "full-expressions" are init-declarator grammar.

The part that's confusing you is the difference between a "full-expression" and an expression. An expression is a specific piece of C++ grammar. A full-expression is not; it's a language concept which includes a number of different pieces of grammar, but full-expression is not itself grammar.

Therefore, while the grammatical construct init-declarator is a "full-expression" that does not make it an expression. The grammar construct expression is well defined, and int c = 0; doesn't fit that grammar. The init-declarator may contain an expression (or multiple expressions, depending on the initializer), but it is not itself an expression.

And only expressions have value categories. Therefore, asking about the value category of a thing which is not an expression is not a valid question.

Body:
int c = 0;

Consider the above code,thereof,c = 0 is an init-declarator and it's also an expression,Becuase of these rules:

init-declarator:

  declarator initializer(opt)

A full-expression is:

  [...]

  an init-declarator or a mem-initializer, including the constituent expressions of the initializer,

As long as an expression,it will have a value category.

A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears.

The evaluation of a = 0 will initialize object a.So, Is the full-expression c=0 a prvalue expression?If I misunderstand it,please correct me.


问:
Error with HoltWinters from a TS "Error in xy.coords(x, y) : 'x' and 'y' lengths differ"
I'm converting a ts object into a HoltWinters prediction. My data looks like this:

```<code>TP  Year    Day Temp
1     1996  1     98
2     1996  2     97
3     1996  3     97
4     1996  4     90
</code>```

And my code looks like this:

```<code>temps <- read.delim("temps2.txt")

ts <- ts(temps, start=c(1996,1), frequency = 123)

plot(ts, main="raw ts")

hw <- HoltWinters(ts, beta = FALSE, gamma = TRUE)

plot(hw)
</code>```

I'm getting this error:

```<code>Error in xy.coords(x, y) : 'x' and 'y' lengths differ
</code>```

But the confusing thing to me is I know I want my x to be time and my y to be the values from the Temp column, but I didn't ever tell that to hw, so I don't know how to fix it. Once I get the hw object created correctly I want to make a exponential smoothing prediction for the future.

Suggestions welcome:) Thanks

答:
It worked as soon as I gave the temp to the ts object like this:</p>

```<code>ts <- ts(temps$Temp, start=1996, frequency = 123)
</code>```

Body:
I'm converting a ts object into a HoltWinters prediction. My data looks like this:

TP  Year    Day Temp
1     1996  1     98
2     1996  2     97
3     1996  3     97
4     1996  4     90

And my code looks like this:

temps <- read.delim("temps2.txt")

ts <- ts(temps, start=c(1996,1), frequency = 123)

plot(ts, main="raw ts")

hw <- HoltWinters(ts, beta = FALSE, gamma = TRUE)

plot(hw)

I'm getting this error:

Error in xy.coords(x, y) : 'x' and 'y' lengths differ

But the confusing thing to me is I know I want my x to be time and my y to be the values from the Temp column, but I didn't ever tell that to hw, so I don't know how to fix it. Once I get the hw object created correctly I want to make a exponential smoothing prediction for the future.

Suggestions welcome:) Thanks

Body:
It worked as soon as I gave the temp to the ts object like this:

ts <- ts(temps$Temp, start=1996, frequency = 123)


问:
How to convert values in list of strings into Pandas DataFrame
I would like to convert this list of strings into a Pandas DataFrame with columns ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘PeriodVolume’, OpenInterest’ and ‘Datetime’ as index. How can I extract the values and create the DataFrame? Thanks for your help!</p>

```<code>['RequestId: , Datetime: 5/28/2020 12:00:00 AM, High: 323.44, Low: 315.63, Open: 316.77, Close: 318.25, PeriodVolume: 33449103, OpenInterest: 0',

 'RequestId: , Datetime: 5/27/2020 12:00:00 AM, High: 318.71, Low: 313.09, Open: 316.14, Close: 318.11, PeriodVolume: 28236274, OpenInterest: 0',

 'RequestId: , Datetime: 5/26/2020 12:00:00 AM, High: 324.24, Low: 316.5, Open: 323.5, Close: 316.73, PeriodVolume: 31380454, OpenInterest: 0',

 'RequestId: , Datetime: 5/22/2020 12:00:00 AM, High: 319.23, Low: 315.35, Open: 315.77, Close: 318.89, PeriodVolume: 20450754, OpenInterest: 0']
</code>```

答:
```<code>import pandas as pd
ls=['10', '75', '25', '100', '50', '5.5,5/22/2020', '12:00:00 AM']
dataframe=pd.DataFrame(ls,columns=[‘Open’, ‘High’, ‘Low’, ‘Close’, ‘PeriodVolume’, 'OpenInterest’‘Datetime’])
print(dataframe)
</code>```

Body:
I would like to convert this list of strings into a Pandas DataFrame with columns ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘PeriodVolume’, OpenInterest’ and ‘Datetime’ as index. How can I extract the values and create the DataFrame? Thanks for your help!

['RequestId: , Datetime: 5/28/2020 12:00:00 AM, High: 323.44, Low: 315.63, Open: 316.77, Close: 318.25, PeriodVolume: 33449103, OpenInterest: 0',

 'RequestId: , Datetime: 5/27/2020 12:00:00 AM, High: 318.71, Low: 313.09, Open: 316.14, Close: 318.11, PeriodVolume: 28236274, OpenInterest: 0',

 'RequestId: , Datetime: 5/26/2020 12:00:00 AM, High: 324.24, Low: 316.5, Open: 323.5, Close: 316.73, PeriodVolume: 31380454, OpenInterest: 0',

 'RequestId: , Datetime: 5/22/2020 12:00:00 AM, High: 319.23, Low: 315.35, Open: 315.77, Close: 318.89, PeriodVolume: 20450754, OpenInterest: 0']


问:
How to perform multiclass multioutput classification using lstm
I have multiclass multioutput classification (see https://scikit-learn.org/stable/modules/multiclass.html for details). In other words, my dataset looks as follows.

```<code>node_name, timeseries_1, timeseries_2, label_1, label_2
node1, [1.2, ...], [1.8, ...], 0, 2
node2, [1.0, ...], [1.1, ...], 1, 1
node3, [1.9, ...], [1.2, ...], 0, 3
...
...
...
</code>```

So, my label_1 could be either 0 or 1, whereas my label_2 could be either 0, 1, or 2.

My current code is as follows.

```<code>def create_network():
    model = Sequential()
    model.add(LSTM(200, input_shape=(16,2)))
    model.add(Dense(100))
    model.add(Dropout(0.2))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    return model

neural_network = KerasClassifier(build_fn=create_network, epochs=100, batch_size=100, verbose=0)

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)

scores = cross_validate(neural_network, my_features, label_data_encoded, cv=k_fold, scoring = ('accuracy', 'precision_weighted', 'recall_weighted', 'f1_weighted', 'roc_auc'))
</code>```

My questions are as follows.

Since I have two labels (i.e. label_1 and label_2), how to fit these labels to lstm model? Do I have to do something like keras.utils.to_categorical(label_1, 2) and keras.utils.to_categorical(label_2, 3)?

How to change the model in order to make it suitable for multiclass multioutput classification?

I am happy to provide more details if needed.

答:
If I understand correctly, label_1 is binary, whereas label_2 is a multiclass problem, so we need the model to have two outputs with separate loss functions; binary and categorical crossentropy respectively.

However, Sequential API does not allow multiple input/output.

The Sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs.

You can use the functional API to create two output layers, and compile the model with required loss functions.

```<code>X=Input(input_shape)
X=Layer(X)
'
'
'
'
out1=Dense(1, activation='sigmoid')(X)
out2=Dense(3, activation='softmax')(X)
model = Model(inputs = input, outputs = [out1,out2])
model.compile(loss = ['binary_crossentropy','categorical_crossentropy'], loss_weights = [l1,l2], ...)

model.fit(input,[label_1, label_2_toCategotical]
</code>```

The loss that the network will minimize will be the weighted sum of the 2 losses, weighted by l1 and l2.

Hope this helps :)

Body:
I have multiclass multioutput classification (see https://scikit-learn.org/stable/modules/multiclass.html for details). In other words, my dataset looks as follows.

node_name, timeseries_1, timeseries_2, label_1, label_2
node1, [1.2, ...], [1.8, ...], 0, 2
node2, [1.0, ...], [1.1, ...], 1, 1
node3, [1.9, ...], [1.2, ...], 0, 3
...
...
...

So, my label_1 could be either 0 or 1, whereas my label_2 could be either 0, 1, or 2.

My current code is as follows.

def create_network():
    model = Sequential()
    model.add(LSTM(200, input_shape=(16,2)))
    model.add(Dense(100))
    model.add(Dropout(0.2))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    return model

neural_network = KerasClassifier(build_fn=create_network, epochs=100, batch_size=100, verbose=0)

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)

scores = cross_validate(neural_network, my_features, label_data_encoded, cv=k_fold, scoring = ('accuracy', 'precision_weighted', 'recall_weighted', 'f1_weighted', 'roc_auc'))

My questions are as follows.

Since I have two labels (i.e. label_1 and label_2), how to fit these labels to lstm model? Do I have to do something like keras.utils.to_categorical(label_1, 2) and keras.utils.to_categorical(label_2, 3)?

How to change the model in order to make it suitable for multiclass multioutput classification?

I am happy to provide more details if needed.

Body:
If I understand correctly, label_1 is binary, whereas label_2 is a multiclass problem, so we need the model to have two outputs with separate loss functions; binary and categorical crossentropy respectively.

However, Sequential API does not allow multiple input/output.

The Sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs.

You can use the functional API to create two output layers, and compile the model with required loss functions.

X=Input(input_shape)
X=Layer(X)
'
'
'
'
out1=Dense(1, activation='sigmoid')(X)
out2=Dense(3, activation='softmax')(X)
model = Model(inputs = input, outputs = [out1,out2])
model.compile(loss = ['binary_crossentropy','categorical_crossentropy'], loss_weights = [l1,l2], ...)

model.fit(input,[label_1, label_2_toCategotical]

The loss that the network will minimize will be the weighted sum of the 2 losses, weighted by l1 and l2.

Hope this helps :)


问:
Blue dot location mapkit
I'm trying to make a maps application using Mapkit. but I can't seem to access the blue dot when i run the app on the simulator. i'm still new to Mapkit and any tips would be really appreciated. here's my code. p.s: i'm coding using Swift 4.2 and Xcode 11

```<code>import UIKit
import MapKit
import CoreLocation

class mapViewController: UIViewController {

    let locationManager = CLLocationManager()

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        checkLocationServices()

    }

    func setupLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func centerViewOnUserLocation() {
        if let location = locationManager.location?.coordinate {
            let region = MKCoordinateRegion.init(center: location, latitudinalMeters: 10000, longitudinalMeters: 10000)
            mapView.setRegion(region, animated: true)
        }
    }

    func checkLocationServices() {
        if CLLocationManager.locationServicesEnabled() {
            setupLocationManager()
            checkLocationAuthorization()
        } else {

        }

    }

    func checkLocationAuthorization() {
        let pin = MKPointAnnotation()

        switch CLLocationManager.authorizationStatus() {
        case .authorizedWhenInUse:
            mapView.showsUserLocation = true
            mapView.addAnnotation(pin)
            break
        case .denied:
            break
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            break
        case .restricted:
            break
        case .authorizedAlways:
            break
        }
    }

}

extension mapViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // we'll be back
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        //we'll be back
    }

}
</code>```

答: Check Simulator menu: Features > Location > Custom Location

Title: Blue dot location mapkit

Body:
I'm trying to make a maps application using Mapkit. but I can't seem to access the blue dot when i run the app on the simulator. i'm still new to Mapkit and any tips would be really appreciated. here's my code. p.s: i'm coding using Swift 4.2 and Xcode 11

import UIKit
import MapKit
import CoreLocation

class mapViewController: UIViewController {

    let locationManager = CLLocationManager()

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        checkLocationServices()

    }

    func setupLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func centerViewOnUserLocation() {
        if let location = locationManager.location?.coordinate {
            let region = MKCoordinateRegion.init(center: location, latitudinalMeters: 10000, longitudinalMeters: 10000)
            mapView.setRegion(region, animated: true)
        }
    }

    func checkLocationServices() {
        if CLLocationManager.locationServicesEnabled() {
            setupLocationManager()
            checkLocationAuthorization()
        } else {

        }

    }

    func checkLocationAuthorization() {
        let pin = MKPointAnnotation()

        switch CLLocationManager.authorizationStatus() {
        case .authorizedWhenInUse:
            mapView.showsUserLocation = true
            mapView.addAnnotation(pin)
            break
        case .denied:
            break
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            break
        case .restricted:
            break
        case .authorizedAlways:
            break
        }
    }

}

extension mapViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // we'll be back
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        //we'll be back
    }

}


问:
How to use translateZ( ) transform with rotateY( ) using CSS?
I was trying to use translateZ with rotateY to see clear differences but as soon as i hover the div the rotateY retrieves. The code is as follows-

.box {
  width: 350px;
  height: 250px;
  background: tomato;
  transform: rotateY(70deg);
  transition: transform 2s ease;
}

.box:hover {
  transform: perspective(500px) translateZ(300px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="box">Some text</div>
</div></code>```

This same thing also happens when i try to use translateX instead of Z. Please help..

答:
You need to specify rotateY on :hover as well because on transform property in .box:hover will override the transform property in .box

.box {
  width: 350px;
  height: 250px;
  background: tomato;
  transform: rotateY(70deg);
  transition: transform 2s ease;
}

.box:hover {
  transform: perspective(500px) translateZ(300px) rotateY(70deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="box">Some text</div>
</div></code>```

Body:
I was trying to use translateZ with rotateY to see clear differences but as soon as i hover the div the rotateY retrieves. The code is as follows-

.box {
  width: 350px;
  height: 250px;
  background: tomato;
  transform: rotateY(70deg);
  transition: transform 2s ease;
}

.box:hover {
  transform: perspective(500px) translateZ(300px);
}

Some text

This same thing also happens when i try to use translateX instead of Z. Please help..

Body:
You need to specify rotateY on :hover as well because on transform property in .box:hover will override the transform property in .box

.box {
  width: 350px;
  height: 250px;
  background: tomato;
  transform: rotateY(70deg);
  transition: transform 2s ease;
}

.box:hover {
  transform: perspective(500px) translateZ(300px) rotateY(70deg);
}

<div class="parent">
  <div class="box">Some text</div>
</div>


问:
Installed chrome driver and added it to path yet error shows Chromedriver needs to be in path
hey guys so im trying to make a Chegg bot which needs the chromedriver and
I downloaded the chrome webdriver and imported selenium using my command line. i added the webdriver in path and I specified the location yet weeoes show that the file cannot be located and that the chromedriver needs to be in path

if anyone needs more information ill be glad to provide, I would greatly appreciate is someone tried to test the code out for me, just let me know so I can share it on github

subprocess.py

```<code>self._execute_child(args, executable, preexec_fn, close_fds,
                                pass_fds, cwd, env,
                                startupinfo, creationflags, shell,
                                p2cread, p2cwrite,
                                c2pread, c2pwrite,
                                errread, errwrite,
                                restore_signals, start_new_session)

 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         int(not close_fds),
                                         creationflags,
                                         env,
                                         cwd,
                                         startupinfo)
</code>```

service.py

```<code>self.process = subprocess.Popen(cmd, env=self.env,
                                            close_fds=platform.system() != 'Windows',
                                            stdout=self.log_file,
                                            stderr=self.log_file,
                                            stdin=PIPE)

raise WebDriverException(
                    "'%s' executable needs to be in PATH. %s" % (
                        os.path.basename(self.path), self.start_error_message

</code>```

Webdriver.py

```<code>  self.service = Service(
            executable_path,
            port=port,
            service_args=service_args,
            log_path=service_log_path)
        self.service.start()
</code>```

Davids_Chegg.py

```<code>chrome_driver = r'C:\Webdrivers\chromedriver.exe\'

if __name__ == '__main__':
    browser = webdriver.Chrome("C:\Webdrivers\chromedriver.exe")
    signin()
    client.run(bot_token)
    # test comment
</code>```

```<code>ERRORS:

Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Python38\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Python38\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\david\Desktop\Python\chegg_bot\David_s Chegg.py", line 282, in <module>
    browser = webdriver.Chrome(executable_path="chromedriver", options=opts)
  File "C:\Python38\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
</code>```

答:
You can try the code below and you don't need to worry about the path setting or webdriver installation according to the web browser version.

Just install webdriver_manager to use this code using a command: pip install webdriver_manager

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
</code>```

I am using this for web scraping and it works perfectly.

Body:
hey guys so im trying to make a Chegg bot which needs the chromedriver and
I downloaded the chrome webdriver and imported selenium using my command line. i added the webdriver in path and I specified the location yet weeoes show that the file cannot be located and that the chromedriver needs to be in path

if anyone needs more information ill be glad to provide, I would greatly appreciate is someone tried to test the code out for me, just let me know so I can share it on github

subprocess.py

self._execute_child(args, executable, preexec_fn, close_fds,
                                pass_fds, cwd, env,
                                startupinfo, creationflags, shell,
                                p2cread, p2cwrite,
                                c2pread, c2pwrite,
                                errread, errwrite,
                                restore_signals, start_new_session)

 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         int(not close_fds),
                                         creationflags,
                                         env,
                                         cwd,
                                         startupinfo)

service.py

self.process = subprocess.Popen(cmd, env=self.env,
                                            close_fds=platform.system() != 'Windows',
                                            stdout=self.log_file,
                                            stderr=self.log_file,
                                            stdin=PIPE)

raise WebDriverException(
                    "'%s' executable needs to be in PATH. %s" % (
                        os.path.basename(self.path), self.start_error_message

Webdriver.py

  self.service = Service(
            executable_path,
            port=port,
            service_args=service_args,
            log_path=service_log_path)
        self.service.start()

Davids_Chegg.py

chrome_driver = r'C:\Webdrivers\chromedriver.exe\'

if __name__ == '__main__':
    browser = webdriver.Chrome("C:\Webdrivers\chromedriver.exe")
    signin()
    client.run(bot_token)
    # test comment

ERRORS:

Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Python38\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Python38\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\david\Desktop\Python\chegg_bot\David_s Chegg.py", line 282, in <module>
    browser = webdriver.Chrome(executable_path="chromedriver", options=opts)
  File "C:\Python38\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

Body:
You can try the code below and you don't need to worry about the path setting or webdriver installation according to the web browser version.

Just install webdriver_manager to use this code using a command: pip install webdriver_manager

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

I am using this for web scraping and it works perfectly.


问:
TypeError: Fetch argument None has invalid type <class 'NoneType'> on operation that seems to be not none
N.B. Tensorflow version less than 2.0

In the following reproducible code, wd_d_op=sess.run([wd_d_op], feed_dict={X: x}) run successfully but grads_and_vars=sess.run([grad_and_vars], feed_dict={X: x}) raises the mentioned noneType error. If grad_and_vars then how come the next operation run successfully?

```<code>import tensorflow as tf
import numpy as np
from sklearn.datasets import make_blobs

##function for creating layer with fixed weight, don't worry about this
def fc_layer(input_tensor, input_dim, output_dim, component_name,act=tf.nn.relu, input_type='dense'):
#         weight = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=1. / tf.sqrt(input_dim / 2.)), name='weight')
        if component_name=="weight1":
            weight=tf.Variable([[-0.46401197, -0.02868146, -0.02945778, -0.19310321],[-0.06130088, -0.3782992 , -1.4025078 , -0.8482222 ]])
            bias=tf.Variable([0.1,0.1,0.1,0.1])
        else:
            weight=tf.Variable([[ 0.27422005],[-1.2150304 ],[-0.43404067],[-0.3352416 ]])
            bias=tf.Variable([0.1])

#         weight=tf.Print(weight,[weight],component_name,summarize=-1)

        bias = tf.Variable(tf.constant(0.1, shape=[output_dim]), name='bias')
#         bias=tf.Print(bias,[type(bias)],component_name+"bias",summarize=-1)
        weight=tf.cast(weight, tf.float32)
        bias=tf.cast(bias, tf.float32)
        input_tensor=tf.cast(input_tensor, tf.float32)
        if input_type == 'sparse':
            activations = act(tf.sparse_tensor_dense_matmul(input_tensor, weight) + bias)
        else:
            activations = act(tf.matmul(input_tensor, weight) + bias,name="features")
        return activations

"""fixed input"""

x=np.array([[-0.9233333412304945, -0.5148649076298134],[-0.9366679176350374, -2.086600005395918],[50.366624846708156, -9.02965996391532],[51.09416621163187, -12.101430685982692]])

lr_wd_D = 1e-3
with tf.name_scope('input'):
    X = tf.placeholder(dtype=tf.float32,name="exmaple")

with tf.name_scope('generator'):
    h1 = fc_layer(X, 2, 4,component_name="weight1",input_type='dense')
    output = fc_layer(h1, 4, 1,component_name="weight2",act=tf.identity,input_type='dense')
#     output=tf.Print(output,[output],"output",summarize=-1)

output=tf.convert_to_tensor(output, dtype=tf.float32)
critic_s = tf.slice(output, [0, 0], [2, -1])
critic_t = tf.slice(output, [2, 0], [2, -1])

wd_loss = (tf.reduce_mean(critic_s) - tf.reduce_mean(critic_t))
# wd_loss=tf.convert_to_tensor(wd_loss, dtype=tf.float32)

theta_C = [v for v in tf.global_variables() if 'generator' in v.name]

wd_op=tf.train.AdamOptimizer(lr_wd_D)

"""only calling this operation does not work, raised the mentioned error"""
grad_and_vars = wd_op.compute_gradients(wd_loss,var_list=theta_C)

"""But the following operation works even that use the previous variable"""
wd_d_op=wd_op.apply_gradients(grad_and_vars)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    #this works
    wd_loss,theta_C=sess.run([wd_loss,theta_C], feed_dict={X: x})

    print("wd_loss")
    print(wd_loss)

    print("theta_C")
    print(theta_C)

    #this does works
    wd_d_op=sess.run([wd_d_op], feed_dict={X: x})

    #this does not work , even though grads_and_vars used by  wd_d_op
    grads_and_vars=sess.run([grad_and_vars], feed_dict={X: x})
</code>```

答:
Solution:

If you comment out the following two lines of code, it will run correctly.

```<code># bias=tf.Variable([0.1,0.1,0.1,0.1])

# bias=tf.Variable([0.1])
</code>```

Explain：

Gradients are returned None if there are no explicit connections between wd_loss and theta_C in the graph. If you print theta_C, you will find two bias variables. These two bias variables don't actually participate in the calculation of wd_loss.

I give an example of an error below when w3 does not participate in the calculation of y but differentiates it.

```<code>import tensorflow as tf
w1 = tf.Variable([[1.,2.]])
w2 = tf.Variable([[9.],[10.]])
w3 = tf.Variable([[5.,6.]])

y = tf.matmul(w1, w2)
# this work
grads = tf.gradients(y,[w1,w2])
# this does not work, TypeError: Fetch argument None has invalid type <class 'NoneType'>
# grads = tf.gradients(y,[w1,w2,w3])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    gradval = sess.run(grads)
    print(gradval)
</code>```

Body:
N.B. Tensorflow version less than 2.0

In the following reproducible code, wd_d_op=sess.run([wd_d_op], feed_dict={X: x}) run successfully but grads_and_vars=sess.run([grad_and_vars], feed_dict={X: x}) raises the mentioned noneType error. If grad_and_vars then how come the next operation run successfully?

import tensorflow as tf
import numpy as np
from sklearn.datasets import make_blobs

##function for creating layer with fixed weight, don't worry about this
def fc_layer(input_tensor, input_dim, output_dim, component_name,act=tf.nn.relu, input_type='dense'):
#         weight = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=1. / tf.sqrt(input_dim / 2.)), name='weight')
        if component_name=="weight1":
            weight=tf.Variable([[-0.46401197, -0.02868146, -0.02945778, -0.19310321],[-0.06130088, -0.3782992 , -1.4025078 , -0.8482222 ]])
            bias=tf.Variable([0.1,0.1,0.1,0.1])
        else:
            weight=tf.Variable([[ 0.27422005],[-1.2150304 ],[-0.43404067],[-0.3352416 ]])
            bias=tf.Variable([0.1])

#         weight=tf.Print(weight,[weight],component_name,summarize=-1)

        bias = tf.Variable(tf.constant(0.1, shape=[output_dim]), name='bias')
#         bias=tf.Print(bias,[type(bias)],component_name+"bias",summarize=-1)
        weight=tf.cast(weight, tf.float32)
        bias=tf.cast(bias, tf.float32)
        input_tensor=tf.cast(input_tensor, tf.float32)
        if input_type == 'sparse':
            activations = act(tf.sparse_tensor_dense_matmul(input_tensor, weight) + bias)
        else:
            activations = act(tf.matmul(input_tensor, weight) + bias,name="features")
        return activations

"""fixed input"""

x=np.array([[-0.9233333412304945, -0.5148649076298134],[-0.9366679176350374, -2.086600005395918],[50.366624846708156, -9.02965996391532],[51.09416621163187, -12.101430685982692]])

lr_wd_D = 1e-3
with tf.name_scope('input'):
    X = tf.placeholder(dtype=tf.float32,name="exmaple")

with tf.name_scope('generator'):
    h1 = fc_layer(X, 2, 4,component_name="weight1",input_type='dense')
    output = fc_layer(h1, 4, 1,component_name="weight2",act=tf.identity,input_type='dense')
#     output=tf.Print(output,[output],"output",summarize=-1)

output=tf.convert_to_tensor(output, dtype=tf.float32)
critic_s = tf.slice(output, [0, 0], [2, -1])
critic_t = tf.slice(output, [2, 0], [2, -1])

wd_loss = (tf.reduce_mean(critic_s) - tf.reduce_mean(critic_t))
# wd_loss=tf.convert_to_tensor(wd_loss, dtype=tf.float32)

theta_C = [v for v in tf.global_variables() if 'generator' in v.name]

wd_op=tf.train.AdamOptimizer(lr_wd_D)

"""only calling this operation does not work, raised the mentioned error"""
grad_and_vars = wd_op.compute_gradients(wd_loss,var_list=theta_C)

"""But the following operation works even that use the previous variable"""
wd_d_op=wd_op.apply_gradients(grad_and_vars)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    #this works
    wd_loss,theta_C=sess.run([wd_loss,theta_C], feed_dict={X: x})

    print("wd_loss")
    print(wd_loss)

    print("theta_C")
    print(theta_C)

    #this does works
    wd_d_op=sess.run([wd_d_op], feed_dict={X: x})

    #this does not work , even though grads_and_vars used by  wd_d_op
    grads_and_vars=sess.run([grad_and_vars], feed_dict={X: x})

Body:
Solution:

If you comment out the following two lines of code, it will run correctly.

# bias=tf.Variable([0.1,0.1,0.1,0.1])

# bias=tf.Variable([0.1])

Explain：

Gradients are returned None if there are no explicit connections between wd_loss and theta_C in the graph. If you print theta_C, you will find two bias variables. These two bias variables don't actually participate in the calculation of wd_loss.

I give an example of an error below when w3 does not participate in the calculation of y but differentiates it.

import tensorflow as tf
w1 = tf.Variable([[1.,2.]])
w2 = tf.Variable([[9.],[10.]])
w3 = tf.Variable([[5.,6.]])

y = tf.matmul(w1, w2)
# this work
grads = tf.gradients(y,[w1,w2])
# this does not work, TypeError: Fetch argument None has invalid type <class 'NoneType'>
# grads = tf.gradients(y,[w1,w2,w3])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    gradval = sess.run(grads)
    print(gradval)


问:
Accurate method to add months in PHP 5.1?
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

```<code>date('Y-m-d',strtotime( '+1 month', strtotime('now')));
</code>```

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?

答:
Since this seems to be a fairly confusing topic here is some information on it:

You are actually getting an accurate result it is literally increasing the month by 1, the day remains 31, therefore the date is 2011-06-31.  If you do echo date('Y-m-d', strtotime('2011-06-31')); you'll see it displays 2011-07-01.

Here is one method of making this work as "expected" in PHP 5.1 (and before)

```<code>function next_month($timestamp)
{
    $next_month = date('m', $timestamp);
    $next_month++;

    $next_year = date('Y', $timestamp);

    if($next_month == 12)
    {
        $next_year++;
    }

    if(date('d', $timestamp) <= date('t', mktime(0, 0, 0, $next_month, 1, $next_year)))
    {
        return date('Y-m-d',strtotime( '+1 month', $timestamp));
    }
    else
    {
        return date('Y-m-d', mktime(0, 0, 0, $next_month, date('t', mktime(0, 0, 0, $next_month, 1, $next_year)), $next_year));
    }
}

echo next_month(strtotime('2011-05-31'));

echo next_month(strtotime('2011-05-01'));
</code>```

This is modified code from a library I wrote a while ago -- I've never found an elegant solution.

For PHP 5.3+

Refer to PHP DateTime::modify adding and subtracting months for a detailed Q/A on this topic.

Body:
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

date('Y-m-d',strtotime( '+1 month', strtotime('now')));

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?

Body:
Since this seems to be a fairly confusing topic here is some information on it:

You are actually getting an accurate result it is literally increasing the month by 1, the day remains 31, therefore the date is 2011-06-31.  If you do echo date('Y-m-d', strtotime('2011-06-31')); you'll see it displays 2011-07-01.

Here is one method of making this work as "expected" in PHP 5.1 (and before)

function next_month($timestamp)
{
    $next_month = date('m', $timestamp);
    $next_month++;

    $next_year = date('Y', $timestamp);

    if($next_month == 12)
    {
        $next_year++;
    }

    if(date('d', $timestamp) <= date('t', mktime(0, 0, 0, $next_month, 1, $next_year)))
    {
        return date('Y-m-d',strtotime( '+1 month', $timestamp));
    }
    else
    {
        return date('Y-m-d', mktime(0, 0, 0, $next_month, date('t', mktime(0, 0, 0, $next_month, 1, $next_year)), $next_year));
    }
}

echo next_month(strtotime('2011-05-31'));

echo next_month(strtotime('2011-05-01'));

This is modified code from a library I wrote a while ago -- I've never found an elegant solution.

For PHP 5.3+

Refer to PHP DateTime::modify adding and subtracting months for a detailed Q/A on this topic.


问:
How to use Regex to verify data input from keyboard is real numbers with C languages?
I try to research for REGEX in C and try to understand but I have trouble with pattern of the string type.
In this program I want to verify string input is a number(only digits number, not characters, space, or special characters)

```<code> #include<stdio.h>
 #include <regex.h>
 void print_result(int return_value){
  if (return_value == 0){
    printf("Pattern found.\n");
  }
  else if (return_value == REG_NOMATCH){
    printf("Pattern not found.\n");
  }
  else{
    printf("An error occured.\n");
  }
}
int main() {
  regex_t regex;
  int return_value;
  int return_value2;
  return_value = regcomp(&regex,"[^a-fA-F_][0-9]+",0);
  return_value = regexec(&regex, "4324", 0, NULL, 0);
  return_value2 = regcomp(&regex,"\d+",0);
  return_value = regexec(&regex, "4324", 0, NULL, 0);
  print_result(return_value);  //not found
  print_result(return_value); //no found
  print_result(return_value2);
  return 0;
}
</code>```

Can you give me some ideas to verify the input. I want find another way without use ASCII values

答:
If you specify the flags as 0 in regcomp:

```<code>return_value = regcomp(&regex,"[^a-fA-F_][0-9]+",0);
</code>```

then you are accepting the default regex syntax, which is a so-called Basic Regular Expression (BRE). The only sensible thing that can be said about BREs is "don't use them." Always specify the REG_EXTENDED flag (at least), and then you will be working with a regular expression syntax that at least bears a passing resemblance to what you expect. (Otherwise, your strings will be dominated by what's technically called "leaning timber": \ characters which enable metacharacters in the regex, and more \ characters so that the \ characters you need are not treated as escape characters in the character string.)

Take a look at man regexec and man 7 regex for more details. Make sure you read the second link thoroughly (although you can ignore basic regular expression syntax :-) ) because there are many commonly-used syntaxes in more modern regex libraries which are not present in Posix regexes, not even extended ones. (That includes \d, used in your second regex. Posix has named character classes, such as [[:digit:]].)

Body:
I try to research for REGEX in C and try to understand but I have trouble with pattern of the string type.
In this program I want to verify string input is a number(only digits number, not characters, space, or special characters)

 #include<stdio.h>
 #include <regex.h>
 void print_result(int return_value){
  if (return_value == 0){
    printf("Pattern found.\n");
  }
  else if (return_value == REG_NOMATCH){
    printf("Pattern not found.\n");
  }
  else{
    printf("An error occured.\n");
  }
}
int main() {
  regex_t regex;
  int return_value;
  int return_value2;
  return_value = regcomp(&regex,"[^a-fA-F_][0-9]+",0);
  return_value = regexec(&regex, "4324", 0, NULL, 0);
  return_value2 = regcomp(&regex,"\d+",0);
  return_value = regexec(&regex, "4324", 0, NULL, 0);
  print_result(return_value);  //not found
  print_result(return_value); //no found
  print_result(return_value2);
  return 0;
}

Can you give me some ideas to verify the input. I want find another way without use ASCII values

Body:
If you specify the flags as 0 in regcomp:

return_value = regcomp(&regex,"[^a-fA-F_][0-9]+",0);

then you are accepting the default regex syntax, which is a so-called Basic Regular Expression (BRE). The only sensible thing that can be said about BREs is "don't use them." Always specify the REG_EXTENDED flag (at least), and then you will be working with a regular expression syntax that at least bears a passing resemblance to what you expect. (Otherwise, your strings will be dominated by what's technically called "leaning timber": \ characters which enable metacharacters in the regex, and more \ characters so that the \ characters you need are not treated as escape characters in the character string.)

Take a look at man regexec and man 7 regex for more details. Make sure you read the second link thoroughly (although you can ignore basic regular expression syntax :-) ) because there are many commonly-used syntaxes in more modern regex libraries which are not present in Posix regexes, not even extended ones. (That includes \d, used in your second regex. Posix has named character classes, such as [[:digit:]].)


问:
Is it possible to Change Ant designs theme as dynamic
Is there any way available to change Ant design theme during runtime in react 16.7 CRA.
Config-overides.js file looks like this

const { override, fixBabelImports } = require('customize-cra');

 module.exports = override(
   fixBabelImports('import', {
     libraryName: 'antd',
     libraryDirectory: 'es',
     style: 'css',
   }),
addLessLoader({
   javascriptEnabled: true,
   modifyVars: { '@primary-color': '#1DA57A' },
 })
 );```

This code changes the color as static but How can I make it as dynamic

答:
Another way to implement this is to make another set of css only for the dark mode, and to scope them.

The less compiler handles this somehow, but you need to be extra careful in the order of feeding less files for compilation in your code. You might need to try and error for this. The basic idea is:

```<code>import './styles/dark.less';
import './styles/index.less';
</code>```

in the dark.less you will have more or less

```<code>[data-theme^="dark"] {
  @import "./your.less";
}
</code>```

Now you can select the mode dynamically by assigning the value in your root html tag.
As for this, this link might be helpful: https://medium.com/missive-app/make-your-electron-app-dark-mode-compatible-c23dcfdd0dfa

Body:
Is there any way available to change Ant design theme during runtime in react 16.7 CRA.
Config-overides.js file looks like this

const { override, fixBabelImports } = require('customize-cra');

 module.exports = override(
   fixBabelImports('import', {
     libraryName: 'antd',
     libraryDirectory: 'es',
     style: 'css',
   }),
addLessLoader({
   javascriptEnabled: true,
   modifyVars: { '@primary-color': '#1DA57A' },
 })
 );

This code changes the color as static but How can I make it as dynamic

Body:
Another way to implement this is to make another set of css only for the dark mode, and to scope them.

The less compiler handles this somehow, but you need to be extra careful in the order of feeding less files for compilation in your code. You might need to try and error for this. The basic idea is:

import './styles/dark.less';
import './styles/index.less';

in the dark.less you will have more or less

[data-theme^="dark"] {
  @import "./your.less";
}

Now you can select the mode dynamically by assigning the value in your root html tag.
As for this, this link might be helpful: https://medium.com/missive-app/make-your-electron-app-dark-mode-compatible-c23dcfdd0dfa