问:
Failed to find data source: ignite
I have a three node spark cluster and three node ignite cluster.
Spark version: 2.3
Ignite version: 2.7

This is how I set the classpath in Spark's spark-default.conf:

```<code>spark.driver.extraClassPath /home/user/apache-ignite-2.7.0-bin/libs/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-indexing/*:/home/user/apache-ignite-2.7.0-bin/libs/optional/ignite-spark/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-spring/*
</code>```

In my Spark (Java) code, I am creating a dataframe and writing to Ignite like this:

```<code>df.write()
.format(IgniteDataFrameSettings.FORMAT_IGNITE())
.option(IgniteDataFrameSettings.OPTION_CONFIG_FILE(), confPath)
.option(IgniteDataFrameSettings.OPTION_TABLE(), tableName)
.mode(SaveMode.Append)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PRIMARY_KEY_FIELDS(), primaryKey)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PARAMETERS(), "template=partitioned")
.save();
</code>```

I am getting the following error in Spark:

```<code>java.lang.ClassNotFoundException: Failed to find data source: ignite. Please find packages at http://spark.apache.org/third-party-projects.html
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:635)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:241)

Caused by: java.lang.ClassNotFoundException: ignite.DefaultSource
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at scala.util.Try.orElse(Try.scala:84)
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:618)
</code>```

What else should I do to resolve this issue? Any help is highly appreciated.
Thank you.

答:
Update :
as mentioned in the ignite deployment docs you should also mention executor classpath along with driver classpath

spark.executor.extraClassPath
  /opt/ignite/libs/:/opt/ignite/libs/optional/ignite-spark/:/opt/ignite/libs/optional/ignite-log4j/:/opt/ignite/libs/optional/ignite-yarn/:/opt/ignite/libs/ignite-spring/*

I think this is the real issue.

http://apache-ignite-users.70518.x6.nabble.com/Spark-Ignite-connection-using-Config-file-td21827.html

seems like you have to lower version of ignite.

For ignite 2.6:

```<code><dependency>
    <groupId>org.apache.ignite</groupId>
    <artifactId>ignite-spark</artifactId>
    <version>2.6.0</version>
</dependency>
</code>```

You can see (source):

```<code>  <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>2.3.0</version>
      <scope>compile</scope>
    </dependency>
</code>```

Also see

1) IGNITE-8534 they fixed in 2.6 version of Ignite

2) Discussion-Upgrade-Ignite-Spark-Module-s-Spark-version-to-2-3-0

call the below func in your driver which will give all the classpath entries to debug what jars in your classpath. In this ignite-spark jar should be present at runtime

Caller would be...

```<code>val  urls = urlsinclasspath(getClass.getClassLoader).foreach(println)

def urlsinclasspath(cl: ClassLoader): Array[java.net.URL] = cl match {
    case null => Array()
    case u: java.net.URLClassLoader => u.getURLs() ++ urlsinclasspath(cl.getParent)
    case _ => urlsinclasspath(cl.getParent)
  }
</code>```

If you want to add jar dependencies with out using wildcards you can see my answer which will add all the jars from a folder dynamically to path you provided.

Spark spark-submit --jars arguments wants comma list, how to declare a directory of jars?

you should have the above mentioned ignite-spark jar in this folder.
  /home/user/apache-ignite-2.7.0-bin/libs/optional/ignite-spark/*
  use the above approach and add the jar by folder.

Title: Failed to find data source: ignite

Body:
I have a three node spark cluster and three node ignite cluster.
Spark version: 2.3
Ignite version: 2.7

This is how I set the classpath in Spark's spark-default.conf:

spark.driver.extraClassPath /home/user/apache-ignite-2.7.0-bin/libs/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-indexing/*:/home/user/apache-ignite-2.7.0-bin/libs/optional/ignite-spark/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-spring/*

In my Spark (Java) code, I am creating a dataframe and writing to Ignite like this:

df.write()
.format(IgniteDataFrameSettings.FORMAT_IGNITE())
.option(IgniteDataFrameSettings.OPTION_CONFIG_FILE(), confPath)
.option(IgniteDataFrameSettings.OPTION_TABLE(), tableName)
.mode(SaveMode.Append)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PRIMARY_KEY_FIELDS(), primaryKey)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PARAMETERS(), "template=partitioned")
.save();

I am getting the following error in Spark:

java.lang.ClassNotFoundException: Failed to find data source: ignite. Please find packages at http://spark.apache.org/third-party-projects.html
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:635)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:241)

Caused by: java.lang.ClassNotFoundException: ignite.DefaultSource
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at scala.util.Try.orElse(Try.scala:84)
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:618)

What else should I do to resolve this issue? Any help is highly appreciated.
Thank you.

Body:
Update :
as mentioned in the ignite deployment docs you should also mention executor classpath along with driver classpath

spark.executor.extraClassPath
  /opt/ignite/libs/:/opt/ignite/libs/optional/ignite-spark/:/opt/ignite/libs/optional/ignite-log4j/:/opt/ignite/libs/optional/ignite-yarn/:/opt/ignite/libs/ignite-spring/*

I think this is the real issue.

http://apache-ignite-users.70518.x6.nabble.com/Spark-Ignite-connection-using-Config-file-td21827.html

seems like you have to lower version of ignite.

For ignite 2.6:

<dependency>
    <groupId>org.apache.ignite</groupId>
    <artifactId>ignite-spark</artifactId>
    <version>2.6.0</version>
</dependency>

You can see (source):

  <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>2.3.0</version>
      <scope>compile</scope>
    </dependency>

Also see

1) IGNITE-8534 they fixed in 2.6 version of Ignite

2) Discussion-Upgrade-Ignite-Spark-Module-s-Spark-version-to-2-3-0

call the below func in your driver which will give all the classpath entries to debug what jars in your classpath. In this ignite-spark jar should be present at runtime

Caller would be...

val  urls = urlsinclasspath(getClass.getClassLoader).foreach(println)

def urlsinclasspath(cl: ClassLoader): Array[java.net.URL] = cl match {
    case null => Array()
    case u: java.net.URLClassLoader => u.getURLs() ++ urlsinclasspath(cl.getParent)
    case _ => urlsinclasspath(cl.getParent)
  }

If you want to add jar dependencies with out using wildcards you can see my answer which will add all the jars from a folder dynamically to path you provided.

Spark spark-submit --jars arguments wants comma list, how to declare a directory of jars?

you should have the above mentioned ignite-spark jar in this folder.
  /home/user/apache-ignite-2.7.0-bin/libs/optional/ignite-spark/*
  use the above approach and add the jar by folder.


来源: stackexchange

问:
C# MVC Query with WHERE clause and 2 params from the View
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

```<code>select * from myTable where column1=16 and column2=24
</code>```

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

```<code>    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}
</code>```

And in my View I would retrieve the values for my where clause from input fields.
Example:

```<code><input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />
</code>```

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

答:
What about this:</p>

```<code>public ActionResult(int column1, int column2)
{
     var query = from m in _db.MyTable
                  where m.Column1 == column1
                  where m.Column2 == column2
                  select m;
                  // Or this for typed model
                  // select new MyModel { Column1 = m.Column1, etc }

     var model = query.First();

     return View(model);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

select * from myTable where column1=16 and column2=24

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}

And in my View I would retrieve the values for my where clause from input fields.
Example:

<input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

Body:
What about this:

public ActionResult(int column1, int column2)
{
     var query = from m in _db.MyTable
                  where m.Column1 == column1
                  where m.Column2 == column2
                  select m;
                  // Or this for typed model
                  // select new MyModel { Column1 = m.Column1, etc }

     var model = query.First();

     return View(model);
}


问:
How to set full-window background image using React styling
I'm trying to do something very basic in React, but I am having trouble. I want to set a image to be the full-window background of my website.

With CSS styling, I managed to get the image to appear. But I was having trouble setting the image to be a full-window background. So I tried my hand at React styling.

```<code>import React, { Component } from "react";
import logo from "./logo.svg";
import code from "./code.jpg";
import "./App.css";

function App() {
  var styles = StyleSheet.create({
    bgImage: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "stretch",
      resizeMode: "stretch"
    }
  });
  return (
    <React.Fragment>
      <Image
        source={require("image!background")}
        style={styles.bgImage}
        alt="background"
      >
        pizza
      </Image>
    </React.Fragment>
  );
}

export default App;
</code>```

I'm pretty new to React. Thanks to anybody who can help me understand what is happening!

答:
You can use this CSS

```<code>var styles = StyleSheet.create({
    bgImage: {
      backgroundRepeat:'no-repeat',
      backgroundSize:'cover',
      height:'100%',
      backgroundPosition:'bottom'
    }
  });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to do something very basic in React, but I am having trouble. I want to set a image to be the full-window background of my website.

With CSS styling, I managed to get the image to appear. But I was having trouble setting the image to be a full-window background. So I tried my hand at React styling.

import React, { Component } from "react";
import logo from "./logo.svg";
import code from "./code.jpg";
import "./App.css";

function App() {
  var styles = StyleSheet.create({
    bgImage: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "stretch",
      resizeMode: "stretch"
    }
  });
  return (
    <React.Fragment>
      <Image
        source={require("image!background")}
        style={styles.bgImage}
        alt="background"
      >
        pizza
      </Image>
    </React.Fragment>
  );
}

export default App;

I'm pretty new to React. Thanks to anybody who can help me understand what is happening!

Body:
You can use this CSS

var styles = StyleSheet.create({
    bgImage: {
      backgroundRepeat:'no-repeat',
      backgroundSize:'cover',
      height:'100%',
      backgroundPosition:'bottom'
    }
  });


问:
MS 365 Access Form Dlookup #Name?
Working with MS Access for the first time and coming across a few problems if someone could please help me

I have 3 tables and 1 form：

```<code>Table Plant {PID(key), Name}；
Table Contractor {CID(key), Plant}；
Table KPI {KID(key), ServiceID, KPI1, KPI2}.
</code>```

Their relationship: Plant.Name = Contractor.Plant, Contractor.CID= KPI.ServiceID

Form KPI : (to input data into Table KPI)
simplify what I want, a combo box "cbxplant" to list all plant names , when use select 1 plant in this combo box, it will lookup CID from table contractor then retrieve the value into a text box "Service ID"
I tried like this :

```<code>=DLookUp("[CID]","Contractor","[Plant]= '" & [Form]![KPI]![cbxplant] & "'")
</code>```

It always show "#Name?" as result. But I can't see any mistake from my code.
Anyone could help?

P.S the combo box is using the table Plant not table Contractor to query the plant name, I don't know if it is linked to this pb? And I also want to know if FormID of 1 field is the lable name of this field ?

答:
Finally, I find the root cause of this problem, the combo box of Access can't save the value of another table except the primary key of this table.
It's not linked with Dlookup function. If I change the key of Table Plant from PID to Plant Name， it can work.</p>

Title: MS 365 Access Form Dlookup #Name?

Body:
Working with MS Access for the first time and coming across a few problems if someone could please help me

I have 3 tables and 1 form：

Table Plant {PID(key), Name}；
Table Contractor {CID(key), Plant}；
Table KPI {KID(key), ServiceID, KPI1, KPI2}.

Their relationship: Plant.Name = Contractor.Plant, Contractor.CID= KPI.ServiceID

Form KPI : (to input data into Table KPI)
simplify what I want, a combo box "cbxplant" to list all plant names , when use select 1 plant in this combo box, it will lookup CID from table contractor then retrieve the value into a text box "Service ID"
I tried like this :

=DLookUp("[CID]","Contractor","[Plant]= '" & [Form]![KPI]![cbxplant] & "'")

It always show "#Name?" as result. But I can't see any mistake from my code.
Anyone could help?

P.S the combo box is using the table Plant not table Contractor to query the plant name, I don't know if it is linked to this pb? And I also want to know if FormID of 1 field is the lable name of this field ?


问:
Trying to pass a prop through <Route /> or <Link />
I am trying to pass a prop through Router and have tried multiple solutions, all of which pass an empty prop.

I was initially trying to pass the match object to access the URL parameters but I have resolved to pass something...anything at this point.

Using react-router-dom which is router v4 I think.
Also I am correctly importing anything relevant here in SearchArtist.js

```<code> import ArtistDetails from './ArtistDetails'
 import {
     BrowserRouter,
     Route,
     Link
 } from 'react-router-dom'
</code>```

This is ArtistDetails.js it is unchanged through all 3 attempts

ArtistDetails.js

```<code>class ArtistDetailsComp extends React.Component {
    constructor(props) {
        super(props)
    }

    componentDidMount() {
        console.log(this.props)
    }

    render() {
        <div></div>
    }
}
</code>```

I have tried:

Attempt 1# - Using render in Route

SearchArtist.js

```<code><Link to='/artist'>

<Route path='/artist' render={(props) => (
    <ArtistDetails something='hello' {...props} />
)} />
</code>```

Console log in ArtistDetails.js returns empty props

Attempt 2# - Passing object to Link

SearchArtist.js

```<code><Link to={{ pathname: '/artist', state: { foo: 'bar'} }}>
     {item.longTitle}
</Link>

<Route path='/artist' component={ArtistDetails}/>
</code>```

Console log in ArtistDetails.js returns empty props

Attempt 3# - Using params in Link

SearchArtist.js

```<code><Link to='/artist' params={{ something: 'hello' }}>
     {item.longTitle}
</Link>

<Route path='/artist' component={ArtistDetails}/>
</code>```

Console log in ArtistDetails.js returns empty props

I receive no errors, anything in render() works I am simply unable to pass any information to my class. This is my first solo React project and I don't know if I am missing something fundamental.

Solution

I tried replicating the error in a simpler project and couldn't, found out it was how I was exporting the components.

I changed

```<code>export default function ArtistDetails(){
    return (
        <ArtistDetailsComp />
    )
}
</code>```

to just

```<code>export default ArtistDetails
</code>```

then renamed the class from ArtistDetailsComp to ArtistDetails`` and it worked.

```<code>export default function ArtistDetails(props){
    return (
        <ArtistDetailsComp props={props} />
    )
}
</code>```

This also works, turns out I wasn't passing props through at all in the export, so when I was calling props, obviously nothing was available, hopefully this helps someone else later on.

答:
i hope this would help,

try writing render(),

```<code><Route path="/artist" render={() => <ArtistDetails newProps={this.props} />} />
</code>```

try using component,

```<code><Route path="/artist" component={() => <ArtistDetails newProps={this.props} />} />
</code>```

Its Passing Props Down To React-Router Route,

```<code><Route
  path="/artist"
  render={(routeProps) => (
    <ArtistDetails {...routeProps} {...props} />
  )}
/>
</code>```

using new update its directly possible,

```<code><Route path="/artist" render={(props) => <ArtistDetails {...props} />} />

class ArtistDetails extends React.Component {
  render() {
    return (
      <React.Fragment>
        {this.props}
      </React.Fragment>
    );
  }
}
</code>```

Body:
I am trying to pass a prop through Router and have tried multiple solutions, all of which pass an empty prop.

I was initially trying to pass the match object to access the URL parameters but I have resolved to pass something...anything at this point.

Using react-router-dom which is router v4 I think.
Also I am correctly importing anything relevant here in SearchArtist.js

 import ArtistDetails from './ArtistDetails'
 import {
     BrowserRouter,
     Route,
     Link
 } from 'react-router-dom'

This is ArtistDetails.js it is unchanged through all 3 attempts

ArtistDetails.js

class ArtistDetailsComp extends React.Component {
    constructor(props) {
        super(props)
    }

    componentDidMount() {
        console.log(this.props)
    }

    render() {

    }
}

I have tried:

Attempt 1# - Using render in Route

SearchArtist.js

<Link to='/artist'>

<Route path='/artist' render={(props) => (
    <ArtistDetails something='hello' {...props} />
)} />

Console log in ArtistDetails.js returns empty props

Attempt 2# - Passing object to Link

SearchArtist.js

<Link to={{ pathname: '/artist', state: { foo: 'bar'} }}>
     {item.longTitle}
</Link>

<Route path='/artist' component={ArtistDetails}/>

Console log in ArtistDetails.js returns empty props

Attempt 3# - Using params in Link

SearchArtist.js

<Link to='/artist' params={{ something: 'hello' }}>
     {item.longTitle}
</Link>

<Route path='/artist' component={ArtistDetails}/>

Console log in ArtistDetails.js returns empty props

I receive no errors, anything in render() works I am simply unable to pass any information to my class. This is my first solo React project and I don't know if I am missing something fundamental.

Solution

I tried replicating the error in a simpler project and couldn't, found out it was how I was exporting the components.

I changed

export default function ArtistDetails(){
    return (
        <ArtistDetailsComp />
    )
}

to just

export default ArtistDetails

then renamed the class from ArtistDetailsComp to ArtistDetails`` and it worked.

export default function ArtistDetails(props){
    return (
        <ArtistDetailsComp props={props} />
    )
}

This also works, turns out I wasn't passing props through at all in the export, so when I was calling props, obviously nothing was available, hopefully this helps someone else later on.

Body:
i hope this would help,

try writing render(),

<Route path="/artist" render={() => <ArtistDetails newProps={this.props} />} />

try using component,

<Route path="/artist" component={() => <ArtistDetails newProps={this.props} />} />

Its Passing Props Down To React-Router Route,

<Route
  path="/artist"
  render={(routeProps) => (
    <ArtistDetails {...routeProps} {...props} />
  )}
/>

using new update its directly possible,

<Route path="/artist" render={(props) => <ArtistDetails {...props} />} />

class ArtistDetails extends React.Component {
  render() {
    return (
      <React.Fragment>
        {this.props}
      </React.Fragment>
    );
  }
}


问:
Query to subtract Now()-[Table].[Field]
I want to run a query that subtracts a certain amount of days from today and filters on that result. I'm working in Access 2007

This works but I need to read the 50 from a table named SetupExp.qryFilter

```<code>SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp
WHERE Now() -50;
</code>```

I've tried WHERE Now() -[SetupExp].[qryFilter]

No luck, it just prompts for a value.

I want to put the 50 in a table/field so the query can read it without user input.

答:
As I understand, you need to show records with SaleDate within the last 50 days from now and be able to store this number of days in SetupExp table. If so, you can use query like this:

```<code>SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp, SetupExp
WHERE CustItemExp.SaleDate > Now()-[qryFilter];
</code>```

If you need editable query, as suggested in comments, use DLookup:

```<code>SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp
WHERE CustItemExp.SaleDate > Now()-DLookUp("qryfilter","SetupExp")
</code>```

Title: Query to subtract Now()-[Table].[Field]

Body:
I want to run a query that subtracts a certain amount of days from today and filters on that result. I'm working in Access 2007

This works but I need to read the 50 from a table named SetupExp.qryFilter

SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp
WHERE Now() -50;

I've tried WHERE Now() -[SetupExp].[qryFilter]

No luck, it just prompts for a value.

I want to put the 50 in a table/field so the query can read it without user input.

Body:
As I understand, you need to show records with SaleDate within the last 50 days from now and be able to store this number of days in SetupExp table. If so, you can use query like this:

SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp, SetupExp
WHERE CustItemExp.SaleDate > Now()-[qryFilter];

If you need editable query, as suggested in comments, use DLookup:

SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp
WHERE CustItemExp.SaleDate > Now()-DLookUp("qryfilter","SetupExp")


问:
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

```<code>main.py
map.py
Scripts/
  script1.py
</code>```

map.py contains just an array and a function to get the correct array index:

```<code>map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]
</code>```

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
</code>```

Any suggestions?

答:
The suggestions by Mike Lewis or Simon are probably what you want, but if you really need to call a function whose name as is determined at runtime, you can do this:

```<code> result = eval(function_ptr + '()')
</code>```

where function_ptr is a string containing the function name.

Body:
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

main.py
map.py
Scripts/
  script1.py

map.py contains just an array and a function to get the correct array index:

map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.

Any suggestions?

Body:
The suggestions by Mike Lewis or Simon are probably what you want, but if you really need to call a function whose name as is determined at runtime, you can do this:

 result = eval(function_ptr + '()')

where function_ptr is a string containing the function name.


问:
Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds
I've been using Selenium for a number of months, which we're using to automate some of our internal testing processes. The scripts have been passing fine. I've recently upgraded to C# 2.40.0 webdriver using FF 27.01 and our scripts are now failing in random places with the following error.

```<code>[Portal.SmokeTest.SmokeRunTest.Booking] TearDown method failed. OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/element timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
TearDown : OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/window timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
[09:01:20]
[Portal.SmokeTest.SmokeRunTest.Booking] TearDown method failed. OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/element timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
TearDown : OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/window timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
   at OpenQA.Selenium.Support.UI.DefaultWait`1.PropagateExceptionIfNotIgnored(Exception e)
   at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
   at Portal.Test.Helpers.Process_Bookings.OpenBookings.SelectBooking(String bookingnumber)
   at Portal.SmokeTest.SmokeRunTest.Booking() in d:\TeamCityAgent\work\dac1dcea7f2e80df\SmokeTests\SmokeRunTest.cs:line 68
--WebException
   at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
--TearDown
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
   at OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Firefox.Internal.ExtensionConnection.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Close()
   at Portal.Test.Helpers.Setup.CloseWebdriver()
   at Portal.SmokeTest.SmokeRunTest.TearDown() in d:\TeamCityAgent\work\dac1dcea7f2e80df\SmokeTests\SmokeRunTest.cs:line 162
--WebException
   at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
</code>```

The latest error I've managed to track down to one single line of code:

```<code>_setup.driver.FindElement(By.XPath("//button[@class='buttonSmall lockBookingButton']")).Click();
</code>```

The annoying thing is, trying to fix the problem is proving difficult, as if I run the test on my local machine, in debug it passes.  Additionally, if I run it via the NUNIT runner on the build machine I'm running the test off, it also passes. It only seems to fail as part of our automated build running process when using Teamcity. Like I said, this has been running fine for months previously, and the only thing that has changed is the selenium webdriver kit.

I have experienced this problem before, whilst in debug, and when a Click() line of code was called, Firefox appeared to lock up, and only stopping the test would allow Firefox to continue. There are a number of suggestions on here including modifying the webdriver source? I'd like to not go down that route if possible if anyone else can offer any suggestions.

答:
The new FirefoxDriver(binary, profile, timeSpan) has been obsolete.

You can now use new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), FirefoxOptions options, TimeSpan commandTimeout) instead.

There is also a new FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options, TimeSpan commandTimeout) and it does works. But it's undocumented, and you need to manually specify geckoDriverDirectory even though it's already in Path.

Body:
I've been using Selenium for a number of months, which we're using to automate some of our internal testing processes. The scripts have been passing fine. I've recently upgraded to C# 2.40.0 webdriver using FF 27.01 and our scripts are now failing in random places with the following error.

[Portal.SmokeTest.SmokeRunTest.Booking] TearDown method failed. OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/element timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
TearDown : OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/window timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
[09:01:20]
[Portal.SmokeTest.SmokeRunTest.Booking] TearDown method failed. OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/element timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
TearDown : OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL htt(p)://localhost:7055/hub/session/56e99e88-ba17-4d12-bef1-c6a6367ccc2f/window timed out after 60 seconds.
  ----> System.Net.WebException : The operation has timed out
   at OpenQA.Selenium.Support.UI.DefaultWait`1.PropagateExceptionIfNotIgnored(Exception e)
   at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
   at Portal.Test.Helpers.Process_Bookings.OpenBookings.SelectBooking(String bookingnumber)
   at Portal.SmokeTest.SmokeRunTest.Booking() in d:\TeamCityAgent\work\dac1dcea7f2e80df\SmokeTests\SmokeRunTest.cs:line 68
--WebException
   at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
--TearDown
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
   at OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Firefox.Internal.ExtensionConnection.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Close()
   at Portal.Test.Helpers.Setup.CloseWebdriver()
   at Portal.SmokeTest.SmokeRunTest.TearDown() in d:\TeamCityAgent\work\dac1dcea7f2e80df\SmokeTests\SmokeRunTest.cs:line 162
--WebException
   at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)

The latest error I've managed to track down to one single line of code:

_setup.driver.FindElement(By.XPath("//button[@class='buttonSmall lockBookingButton']")).Click();

The annoying thing is, trying to fix the problem is proving difficult, as if I run the test on my local machine, in debug it passes.  Additionally, if I run it via the NUNIT runner on the build machine I'm running the test off, it also passes. It only seems to fail as part of our automated build running process when using Teamcity. Like I said, this has been running fine for months previously, and the only thing that has changed is the selenium webdriver kit.

I have experienced this problem before, whilst in debug, and when a Click() line of code was called, Firefox appeared to lock up, and only stopping the test would allow Firefox to continue. There are a number of suggestions on here including modifying the webdriver source? I'd like to not go down that route if possible if anyone else can offer any suggestions.


问:
Celery worker not reconnecting on network change/IP Change
I deployed celery for some tasks that need to be performed at my workplace. These tasks are huge and I bought a few high-spec machines for performing these. Before I detail my issue, let me brief about what all I've deployed:

RabbitMQ broker on a remote server

Producer that pushes tasks on another remote server

Workers at 3 machines deployed at my workplace

Now, when I started the whole process was as smooth as I tested and everything process just great!

The problem

Unfortunately, I forgot to consult my network guy about a fixed IP address, and as per our location, we do not have a fixed IP address from our ISP. So my celery workers upon network disconnect freeze and do nothing. Even when the network is running, because the IP Address changed, and the connection to the broker is not being recreated or worker is not retrying connection. I have tried configuration like BROKER_CONNECTION_MAX_RETRIES = 0 and BROKER_HEARTBEAT = 10. But I had no option but to post it out here and look for experts on this matter!

PS: I cannot restart the workers manually everytime the network changes the IP address by kill -9

答:
The issue was because I was unable to understand the nature of AMQP protocol or RabbitMQ.

When a celery worker starts it opens up a channel at RabbitMQ. This channel upon any network changes tries to reconnect, but the port/sock opened for the channel previously is registered with a different public IP address of the client. As such the negotiations between the celery worker (client) and RabbitMQ (server) cannot resume because the client has changed the address, hence a new channel needs to be established in case of a change in the public IP address of the client.

The answer by @qreOct above is due to either I was unable to express the question properly or because of the difference in our perceptions. Still thanks a lot for taking your time out!


问:
How to encode UTF-8 CloseableHttpClient request
I have a simple POST:

```<code>String url = "https://mysite";
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
   URIBuilder uriBuilder = new URIBuilder(url);
   HttpPost request = new HttpPost();
   List<NameValuePair> nameValuePairs = new ArrayList<>(params);
   request.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8.name()));
   String encodedAuthorization = URLEncoder.encode(data, StandardCharsets.UTF_8.name());

    request.addHeader("Authorization", encodedAuthorization);
   try (CloseableHttpResponse response = httpClient.execute(request)) {
</code>```

I have to support UTF-8 encoding and encoding UrlEncodedFormEntity isn't enough, but it's not clear what must be done, following several options available

Using uriBuilder.setCharset:

```<code>HttpPost request = new HttpPost(uriBuilder.setCharset(StandardCharsets.UTF_8)).build());
</code>```

Using http.protocol.content-charset parameter:

```<code>HttpPost request = new HttpPost(uriBuilder.setParameter("http.protocol.content-charset", "UTF-8").build());
</code>```

Or just adding Content-Type"` header:

```<code>request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
</code>```

Or use request.getParams():

```<code>request.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
request.getParams().setParameter("http.protocol.content-charset", "UTF-8");
</code>```

Or other obvious solution I overlooked?

答:
To properly encode I move to use parameters in  List<NameValuePair> over URIBuilder

and then encode using

```<code>URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());
</code>```

Body:
I have a simple POST:

String url = "https://mysite";
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
   URIBuilder uriBuilder = new URIBuilder(url);
   HttpPost request = new HttpPost();
   List<NameValuePair> nameValuePairs = new ArrayList<>(params);
   request.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8.name()));
   String encodedAuthorization = URLEncoder.encode(data, StandardCharsets.UTF_8.name());

    request.addHeader("Authorization", encodedAuthorization);
   try (CloseableHttpResponse response = httpClient.execute(request)) {

I have to support UTF-8 encoding and encoding UrlEncodedFormEntity isn't enough, but it's not clear what must be done, following several options available

Using uriBuilder.setCharset:

HttpPost request = new HttpPost(uriBuilder.setCharset(StandardCharsets.UTF_8)).build());

Using http.protocol.content-charset parameter:

HttpPost request = new HttpPost(uriBuilder.setParameter("http.protocol.content-charset", "UTF-8").build());

Or just adding Content-Type"` header:

request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

Or use request.getParams():

request.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
request.getParams().setParameter("http.protocol.content-charset", "UTF-8");

Or other obvious solution I overlooked?

Body:
To properly encode I move to use parameters in  List<NameValuePair> over URIBuilder

and then encode using

URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8.name());


问:
AWS CLI listing S3 buckets gives SignatureDoesNotMatch error using IAM user credentials
I am using AWS CLI on Ubuntu 16.04 LTS, I am trying to list all buckets. In aws configure I have input the IAM user access key and IAM user secret key. This IAM user has permissions to list buckets and can list buckets in the console. But using AWS CLI with these keys and running the command aws s3 ls, it is giving me this error:

```<code>A client error (SignatureDoesNotMatch) occurred when calling the ListBuckets operation: The request signature we calculated does not match the signature you provided. Check your key and signing method.
</code>```

I have created a policy to list buckets for this particular IAM user also.

I want to perform further sync operations and make all files public operations via a shell script using this IAM user credentials and do not want to use root credentials.

答:
Can happen even when the machine time is not in sync with the NT server.

sudo ntpdate ntp.ubuntu.com helped me solve this problem.

Body:
I am using AWS CLI on Ubuntu 16.04 LTS, I am trying to list all buckets. In aws configure I have input the IAM user access key and IAM user secret key. This IAM user has permissions to list buckets and can list buckets in the console. But using AWS CLI with these keys and running the command aws s3 ls, it is giving me this error:

A client error (SignatureDoesNotMatch) occurred when calling the ListBuckets operation: The request signature we calculated does not match the signature you provided. Check your key and signing method.

I have created a policy to list buckets for this particular IAM user also.

I want to perform further sync operations and make all files public operations via a shell script using this IAM user credentials and do not want to use root credentials.


问:
How to change dynamically host and port in mongodb url
I tried to set dynamically change host and port in mongodb url but its not working. Can anybody give some suggestion? How to set host and port in mongodb url?

mongodb_url.js

```<code>host="localhost"
port="27017"
user ="root"
password = "mongodb"
let url = "mongodb://{user}:{password}@{localhost}:{port}";
</code>```

url is not working how to set correctly using mongodb and node js

答:
you need to use template literals as per es6 try wrapping with ` (backtick) instead of " (quotes)
like so:

```<code>let url = `mongodb://${user}:${password}@${host}:${port}`;
</code>```

(note that it's 'host' not  'localhost' as per your definition)

Body:
I tried to set dynamically change host and port in mongodb url but its not working. Can anybody give some suggestion? How to set host and port in mongodb url?

mongodb_url.js

host="localhost"
port="27017"
user ="root"
password = "mongodb"
let url = "mongodb://{user}:{password}@{localhost}:{port}";

url is not working how to set correctly using mongodb and node js

Body:
you need to use template literals as per es6 try wrapping with ` (backtick) instead of " (quotes)
like so:

let url = `mongodb://${user}:${password}@${host}:${port}`;

(note that it's 'host' not  'localhost' as per your definition)


问:
Push a local project to new gitlab repo
I have a local git project that contains some branches (master & others)
i would like to push it to a new gitlab repo
so:
1. I created a new gitlab repo with:

Initial commit

then i run

git commit -am "some message"
git add remote gitlab <url-to-repo.git>
git push gitlab master

it dosent work and shows:

! [rejected]        master -> master (fetch first)

error: failed to push some refs to 'https://gitlab.com/myName/myrepo.git                                                                                '

hint: Updates were rejected because the remote contains work that you do

hint: not have locally. This is usually caused by another repository pushing

hint: to the same ref. You may want to first integrate the remote changes

hint: (e.g., 'git pull ...') before pushing again.

hint: See the 'Note about fast-forwards' in 'git push --help' for details.

when i tried:
git push gitlab master -f
it dosent work also, and get:

error: failed to push some refs to 'https://gitlab.com/myName/myrepo.git

and the same result if i add:
--force or -f option

答:
Try to execute "git fetch", and check if you are on the master branch.

Navigate to the branch and try git pull on here, and move to the origin branch and try git pull again.

The next step is try to push your local changes.

Title: Push a local project to new gitlab repo


答:
You need to post the values to the Action method on your controller

Using something like this in your view:

```<code><% using (Html.BeginForm("RunQuery", "ControllerName")) { %>

    <input type="text" name="column1" id="column1value" />
    <input type="text" name="column2" id="column2value" />
    <input type="submit" value="Run Query" />

<% } %>
</code>```

and then the accompanying action method

```<code>[HttpPost]
public ActionResult RunQuery(string column1, string column2)
{
    var results = GetDataFromDatabase(column1, column2);
    return View(results );
}
</code>```

Title: C# MVC Query with WHERE clause and 2 params from the View

Body:
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

select * from myTable where column1=16 and column2=24

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}

And in my View I would retrieve the values for my where clause from input fields.
Example:

<input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

Body:
You need to post the values to the Action method on your controller

Using something like this in your view:

<% using (Html.BeginForm("RunQuery", "ControllerName")) { %>

    <input type="text" name="column1" id="column1value" />
    <input type="text" name="column2" id="column2value" />
    <input type="submit" value="Run Query" />

<% } %>

and then the accompanying action method

[HttpPost]
public ActionResult RunQuery(string column1, string column2)
{
    var results = GetDataFromDatabase(column1, column2);
    return View(results );
}


问:
Is there a difference between np.matrix(np.array([0,0])) and np.matrix([0,0])?
I was reading this code, for implementing linear regression from scratch:

```<code># convert from data frames to numpy matrices
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
</code>```

When I came across this line:

```<code>np.matrix(np.array([0,0]))
</code>```

I was wondering why didn't the person just write np.matrix([0,0]).

I ran both in jupyter notebook and got the same output:

```<code>theta = np.matrix([0,0])
theta2 = np.matrix(np.array([0,0]))
print(theta,theta2,type(theta),type(theta2))
</code>```

Output:[[0 0]] [[0 0]] <class 'numpy.matrix'> <class 'numpy.matrix'>

Is there a difference between the two? Does the extra np.array somehow part add to the functionality of theta? Will the final code function properly if I replace the former with the latter?

答:
Weirdly enough, matrix(array([0,0])) creates a clean object that owns its data

```<code>>>> np.matrix(np.array([0,0])).flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> np.matrix(np.array([0,0])).base
</code>```

whereas matrix([0,0]) appears to be a view into an anonymous array.

```<code>>>> np.matrix([0,0]).flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> np.matrix([0,0]).base
array([0, 0])
</code>```

So, the extra array in matrix(array(..)) seems to avoid clutter, though the deeper reasons for that remain mysterious to me.

Body:
I was reading this code, for implementing linear regression from scratch:

# convert from data frames to numpy matrices
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))

When I came across this line:

np.matrix(np.array([0,0]))

I was wondering why didn't the person just write np.matrix([0,0]).

I ran both in jupyter notebook and got the same output:

theta = np.matrix([0,0])
theta2 = np.matrix(np.array([0,0]))
print(theta,theta2,type(theta),type(theta2))

Output:[[0 0]] [[0 0]] <class 'numpy.matrix'> <class 'numpy.matrix'>

Is there a difference between the two? Does the extra np.array somehow part add to the functionality of theta? Will the final code function properly if I replace the former with the latter?

Body:
Weirdly enough, matrix(array([0,0])) creates a clean object that owns its data

>>> np.matrix(np.array([0,0])).flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> np.matrix(np.array([0,0])).base

whereas matrix([0,0]) appears to be a view into an anonymous array.

>>> np.matrix([0,0]).flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> np.matrix([0,0]).base
array([0, 0])

So, the extra array in matrix(array(..)) seems to avoid clutter, though the deeper reasons for that remain mysterious to me.


问:
Insert array in multiple rows in postgres
I have a variable which stores an array,
eg print_r ($template);
Gives the following output

```<code>Array
(
   [0] => 351
   [1] => 352
)
</code>```

I want to insert these values in a postgres table which has 2 columns (id,template).

```<code>$sql = 'INSERT INTO "table"("id", "template") values ('."'$id'".','."'unnest($template)'".')';
$result = pg_query($sql);
</code>```

Getting the following error

```<code>invalid input syntax for integer: "unnest(Array)"
</code>```

Want the output to be like

```<code>----------
id | template
----------
12 | 351
----------
12 | 352
----------
</code>```

答:
pg_insert is more appropirate to execute this query, keys of the associative array are the column names of the table and values are data that you want to insert. You can have a look at https://www.php.net/manual/ru/function.pg-insert.php

$data = Array
(
   [id] => 351
   [template] => 352
)

 $res = pg_insert($dbconn, 'post_log', $data);

  if ($res) {
      echo "data has been inserted\n";
  } else {
      echo "an error occurred\n";
  }```
</code>```

Body:
I have a variable which stores an array,
eg print_r ($template);
Gives the following output

Array
(
   [0] => 351
   [1] => 352
)

I want to insert these values in a postgres table which has 2 columns (id,template).

$sql = 'INSERT INTO "table"("id", "template") values ('."'$id'".','."'unnest($template)'".')';
$result = pg_query($sql);

Getting the following error

invalid input syntax for integer: "unnest(Array)"

Want the output to be like

----------
id | template
----------
12 | 351
----------
12 | 352
----------


问:
How to pass NSMutableDictionary as a reference?
I have the following set up in one of my classes where I pass an NSMutableDictionary as a parameter to the initializer, then I assign it to the variable controls.

I believe the behavior is it is copying the items of the NSMutableDictonary into controls, but I need to pass it as a reference so that the changes made are reflected in the class that is passing the dictionary to MenuViewCell. This always confuses the heck out of me, how would I pass a NSMutableDictionary as a reference?

```<code>MenuViewCell.h

@interface MenuViewCell : UITableViewCell
{
    NSMutableDictionary *_controls;
}
@property(nonatomic, copy) NSMutableDictionary *controls;

MenuViewCell.m

@synthesize controls = _controls;

- (id)initWithControls:(NSMutableDictionary *)controls
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    if (self)
    {
        self.controls = controls;
    }
    return self;
}

- (void) setControls:(NSMutableDictionary *)controls
{
    if (_controls != controls)
    {
        _controls = [controls mutableCopy];
    }
}
</code>```

答:
Your issue is the use of copy on the property and the use of mutableCopy in the setter. Make the property strong.

You also don't need @synthesize or the explicit instance variable.

MenuViewCell.h

```<code>@interface MenuViewCell : UITableViewCell

@property(nonatomic, strong) NSMutableDictionary *controls;
</code>```

MenuViewCell.m

```<code>- (id)initWithControls:(NSMutableDictionary *)controls
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    if (self)
    {
        _controls = controls;
    }
    return self;
}
</code>```

No need to override the setter.

Body:
I have the following set up in one of my classes where I pass an NSMutableDictionary as a parameter to the initializer, then I assign it to the variable controls.

I believe the behavior is it is copying the items of the NSMutableDictonary into controls, but I need to pass it as a reference so that the changes made are reflected in the class that is passing the dictionary to MenuViewCell. This always confuses the heck out of me, how would I pass a NSMutableDictionary as a reference?

MenuViewCell.h

@interface MenuViewCell : UITableViewCell
{
    NSMutableDictionary *_controls;
}
@property(nonatomic, copy) NSMutableDictionary *controls;

MenuViewCell.m

@synthesize controls = _controls;

- (id)initWithControls:(NSMutableDictionary *)controls
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    if (self)
    {
        self.controls = controls;
    }
    return self;
}

- (void) setControls:(NSMutableDictionary *)controls
{
    if (_controls != controls)
    {
        _controls = [controls mutableCopy];
    }
}

Body:
Your issue is the use of copy on the property and the use of mutableCopy in the setter. Make the property strong.

You also don't need @synthesize or the explicit instance variable.

MenuViewCell.h

@interface MenuViewCell : UITableViewCell

@property(nonatomic, strong) NSMutableDictionary *controls;

MenuViewCell.m

- (id)initWithControls:(NSMutableDictionary *)controls
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    if (self)
    {
        _controls = controls;
    }
    return self;
}

No need to override the setter.


问:
Subquery must return a single row
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

```<code>SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur
</code>```

答:
Not sure what you’re trying to achieve. You don’t seem to need the subquery.

Try this:

```<code>SELECT
    c2.compteur,
    (c1.feb15 + c1.nov15 + c1.dec15) * 100 / ROUND(c1.feb15 + c1.nov15 + c1.dec15)
FROM compteur2015 c1
    INNER JOIN compteur c2
        ON c1.compteur = c2.compteur
GROUP BY
    c2.compteur
</code>```

Title: Subquery must return a single row

Body:
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur

Body:
Not sure what you’re trying to achieve. You don’t seem to need the subquery.

Try this:

SELECT
    c2.compteur,
    (c1.feb15 + c1.nov15 + c1.dec15) * 100 / ROUND(c1.feb15 + c1.nov15 + c1.dec15)
FROM compteur2015 c1
    INNER JOIN compteur c2
        ON c1.compteur = c2.compteur
GROUP BY
    c2.compteur


问:
ORACLE Apex validation
I have one table, i have three columns, start_hour, end_hour and date,
in ORACLE Apex i have a form page with two items, P00_START_HOUR and P00_END_HOUR, i need to create a validation, to prevent an insert in the same date between start_hour and end_hour from the table.
For example, if in the table i already have

| start_hour || end_hour |

| 12:00PM    || 08:00PM  |

I can't insert a value, who is between these two hours
like this

P00_START_HOUR = 08:00AM

P00_END_HOUR   = 01:00PM

I have no idea how to do it.

答:
I created a user table for this example

```<code>create table users (
    id                             number generated by default on null as identity
                                   constraint users_id_pk primary key,
    name                           varchar2(50),
    the_user                       varchar2(20),
    email                          varchar2(30),
    created                        date not null,
    created_by                     varchar2(255) not null,
    updated                        date not null,
    updated_by                     varchar2(255) not null
);

-- triggers
create or replace trigger users_biu
    before insert or update
    on users
    for each row
begin
    if inserting then
        :new.created := sysdate;
        :new.created_by := nvl(sys_context('APEX$SESSION','APP_USER'),user);
    end if;
    :new.updated := sysdate;
    :new.updated_by := nvl(sys_context('APEX$SESSION','APP_USER'),user);
end users_biu;
/
</code>```

When the page has been loaded I'm calculating last user created

```<code>declare
l_user varchar2(30);
begin

    select the_user into l_user
    from users
    order by id desc
    FETCH FIRST 1 ROWS ONLY;

    return l_user;
end;
</code>```

Create a validation, I compared with 1 hour but you can use your own rules

```<code>declare
    l_created_hour varchar2(50);
    l_next_hour varchar2(50);

begin

    select to_char(CREATED,'DD-MM-YYYY hh:mi:ss'),
           to_char(CREATED + 1/24,'DD-MM-YYYY hh:mi:ss')
           into l_created_hour, l_next_hour
  from USERS
  where the_user = :P3_LAST_USER;

  if l_next_hour >= l_created_hour then
        return false;
  else
        return true;
  end if;

end;
</code>```

The result is

Download the app

Title: ORACLE Apex validation

Body:
I created a user table for this example

create table users (
    id                             number generated by default on null as identity
                                   constraint users_id_pk primary key,
    name                           varchar2(50),
    the_user                       varchar2(20),
    email                          varchar2(30),
    created                        date not null,
    created_by                     varchar2(255) not null,
    updated                        date not null,
    updated_by                     varchar2(255) not null
);

-- triggers
create or replace trigger users_biu
    before insert or update
    on users
    for each row
begin
    if inserting then
        :new.created := sysdate;
        :new.created_by := nvl(sys_context('APEX$SESSION','APP_USER'),user);
    end if;
    :new.updated := sysdate;
    :new.updated_by := nvl(sys_context('APEX$SESSION','APP_USER'),user);
end users_biu;
/

When the page has been loaded I'm calculating last user created

declare
l_user varchar2(30);
begin

    select the_user into l_user
    from users
    order by id desc
    FETCH FIRST 1 ROWS ONLY;

    return l_user;
end;

Create a validation, I compared with 1 hour but you can use your own rules

declare
    l_created_hour varchar2(50);
    l_next_hour varchar2(50);

begin

    select to_char(CREATED,'DD-MM-YYYY hh:mi:ss'),
           to_char(CREATED + 1/24,'DD-MM-YYYY hh:mi:ss')
           into l_created_hour, l_next_hour
  from USERS
  where the_user = :P3_LAST_USER;

  if l_next_hour >= l_created_hour then
        return false;
  else
        return true;
  end if;

end;

The result is

Download the app


问:
How to change the whole values of DataFrame?
At first attempt, I want to create a DataFrame but forgot to put some values:

```<code>a=[0,1/4,2/4,3/4,4]
b=[0,1/4,2/4,3/4,4]
z=DataFrame(index=a,columns=b)
</code>```

Then I got this.

```<code>>      0.00 0.25 0.50 0.75 4.00
> 0.00  NaN  NaN  NaN  NaN  NaN
> 0.25  NaN  NaN  NaN  NaN  NaN
> 0.50  NaN  NaN  NaN  NaN  NaN
> 0.75  NaN  NaN  NaN  NaN  NaN
> 4.00  NaN  NaN  NaN  NaN  NaN
</code>```

I want to replace all of values by np.arange(25).reshape(5,5)

Then I tried this:

```<code>z.values=np.arange(25).reshape(5,5)
</code>```

Result:

object.setattr(self, name, value)

AttributeError: can't set attribute

I mean I could re-create the DataFrame with values in it but it seems to be very .... ( dont know how to say).

Question:

1/ Why I can not do it ?

2/ How to solve it ?

3/ On the condition that I want every single values of z.values would be the result of multiplication of columns and rows(rows * columns). How can I do it ?

Expected result of 3/

```<code>     0.00    0.25   0.50    0.75 4.00
0.00    0       0      0       0    0
0.25    0  0.0625  0.125  0.1875    1
0.50    0   0.125   0.25   0.375    2
0.75    0  0.1875  0.375  0.5625    3
4.00    0       1      2       3   16
</code>```

Body:
At first attempt, I want to create a DataFrame but forgot to put some values:

a=[0,1/4,2/4,3/4,4]
b=[0,1/4,2/4,3/4,4]
z=DataFrame(index=a,columns=b)

Then I got this.

>      0.00 0.25 0.50 0.75 4.00
> 0.00  NaN  NaN  NaN  NaN  NaN
> 0.25  NaN  NaN  NaN  NaN  NaN
> 0.50  NaN  NaN  NaN  NaN  NaN
> 0.75  NaN  NaN  NaN  NaN  NaN
> 4.00  NaN  NaN  NaN  NaN  NaN

I want to replace all of values by np.arange(25).reshape(5,5)

Then I tried this:

z.values=np.arange(25).reshape(5,5)

Result:

object.setattr(self, name, value)

AttributeError: can't set attribute

I mean I could re-create the DataFrame with values in it but it seems to be very .... ( dont know how to say).

Question:

1/ Why I can not do it ?

2/ How to solve it ?

3/ On the condition that I want every single values of z.values would be the result of multiplication of columns and rows(rows * columns). How can I do it ?

Expected result of 3/

     0.00    0.25   0.50    0.75 4.00
0.00    0       0      0       0    0
0.25    0  0.0625  0.125  0.1875    1
0.50    0   0.125   0.25   0.375    2
0.75    0  0.1875  0.375  0.5625    3
4.00    0       1      2       3   16

Body:
Use pd.DataFrame.where is one way to go:

import numpy as np
import pandas as pd

a=[0,1/4,2/4,3/4,4]
b=[0,1/4,2/4,3/4,4]
z=pd.DataFrame(index=a,columns=b)

z.where(pd.notna,np.arange(25).reshape(5,5))

Output:

     0.00 0.25 0.50 0.75 4.00
0.00    0    1    2    3    4
0.25    5    6    7    8    9
0.50   10   11   12   13   14
0.75   15   16   17   18   19
4.00   20   21   22   23   24

For the last one, use np.matmul:

mat = np.matmul(np.reshape(z.index, (-1,1)), np.reshape(z.columns, (1,-1)))
z.where(pd.notna, mat)

Output:

     0.00    0.25   0.50    0.75 4.00
0.00    0       0      0       0    0
0.25    0  0.0625  0.125  0.1875    1
0.50    0   0.125   0.25   0.375    2
0.75    0  0.1875  0.375  0.5625    3
4.00    0       1      2       3   16


问:
JQuery Ui .effect with CSS effect not working
This table's row with 2 elements.One type is text and the other type is hidden.
If these element's values were different.jQuery-Ui framework will do the highlight background-color (red).

$(function() {

  $('table tr').each(function(i, val) {
    var nprice = $(this).children('.unit-price').find("input[type='text']").val();
    var oprice = $(this).children('.unit-price').find("input[type='hidden']").val();

    console.log("nprice: " + nprice);
    console.log("oprice: " + oprice);
    if (nprice != oprice) {
      console.log(i);
      console.log("nprice: " + nprice + "!=" + "oprice: " + oprice);
      var blink = setInterval(function() {
        $('.cart tr:eq(' + i + ') ').effect('highlight', {
          color: 'red'
        }, 1000);
      }, 1000);
      setTimeout(function() {
        clearInterval(blink);
      }, 10000);
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight {
  background: red;
  color: green;
  opacity: 0;
}

.unhighlight {
  background: transparent;
  color: black;
  -webkit-transition: background-color 1000ms linear;
  -ms-transition: background-color 1000ms linear;
  transition: background-color 1000ms linear;
}

.cart th,
.data-table th,
.forum-table th {
  border-width: 1px 1px 0;
  border-style: solid;
  border-color: #ddd;
  background-color: #f6f6f6;
  padding: 10px;
  white-space: nowrap;
  font-weight: normal;
}

.cart td {
  min-width: 50px;
  border-width: 1px;
  border-style: solid;
  border-color: transparent #ddd #ddd;
  background-color: #fff;
  padding: 20px;
  color: #444;
}

.cart a {
  font-weight: normal;
  color: #4ab2f1;
}

.cart a:hover {
  text-decoration: underline;
}

.cart .product {
  min-width: 225px;
  text-align: left;
}

.cart .product a {
  font-weight: bold;
  color: #444;
}

.cart .product a:hover {
  color: #4ab2f1;
  text-decoration: none;
}

.cart .product .edit-item {
  margin: 10px 0 0;
}

.cart .product .edit-item a {
  font-weight: normal;
  color: #4ab2f1;
}

.cart .product .edit-item a:hover {
  text-decoration: underline;
}

.cart .remove-from-cart,
.cart .add-to-cart {
  text-align: center;
}

.cart td.unit-price {
  white-space: nowrap;
}

.cart td.quantity input {
  width: 50px;
  text-align: center;
}

.cart td.subtotal {
  white-space: nowrap;
  color: #444;
}

.cart td.subtotal .discount,
.cart td.subtotal .discount-additional-info {
  font-style: italic;
  color: #4ab2f1;
}</code>```

  <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
  <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />

above with 2 values: 75 and 100
<<<highlight background-color was not working. Help. ``` <table class="cart">
  <thead>
    <tr>
      <th>Id#</th>
      <th>Session Eamil</th>
      <th>Login Url</th>
      <th>Date</th>
      <th>Status</th>
      <th>New Price</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="text-center">@counter11</td>
      <td>@item.SessionEmail11</td>
      <td>@item.LoginUrl11</td>
      <td>@item.CreatedAt11</td>
      <td>Failed11</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />
      </td>

    </tr>
    <tr>
      <td class="text-center">@counter12</td>
      <td>@item.SessionEmail12</td>
      <td>@item.LoginUrl12</td>
      <td>@item.CreatedAt12</td>
      <td>Failed12</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />
      </td>

    </tr>
    <tr>
      <td class="text-center">@counter12</td>
      <td>@item.SessionEmail12</td>
      <td>@item.LoginUrl12</td>
      <td>@item.CreatedAt12</td>
      <td>Failed12</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="120" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />
      </td>

    </tr>
    <tr>
      <td class="text-center">@counter12</td>
      <td>@item.SessionEmail12</td>
      <td>@item.LoginUrl12</td>
      <td>@item.CreatedAt12</td>
      <td>Failed12</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="100" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />
      </td>

    </tr>
  </tbody>
  </table></code>```

The function "effect" which highlight background-color effects not working. How can I modify the JavaScript code or CSS?

答:
Try call with callback like below.

let i = 2; //I set i for demo purpose. Your i comes from loop, so no need to declare .
$('.cart tr:eq(' + i + ') ').effect('highlight', {
  color: 'red'
}, 1000, callback);

function callback() {
  setTimeout(function() {
    $('.cart tr:eq(' + i + ') ').removeAttr("style").hide().fadeIn();
  }, 1000);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cart td {
  min-width: 50px;
  border-width: 1px;
  border-style: solid;
  border-color: transparent #ddd #ddd;
  padding: 20px;
}</code>```

      Id#
      Session Eamil
      Login Url
      Date
      Status
      New Price

      @counter11
      @item.SessionEmail11
      @item.LoginUrl11
      @item.CreatedAt11
      Failed11

        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />

      @counter12
      @item.SessionEmail12
      @item.LoginUrl12
      @item.CreatedAt12
      Failed12

        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />

      @counter12
      @item.SessionEmail12
      @item.LoginUrl12
      @item.CreatedAt12
      Failed12

        <input id="itemprice75" name="itemprice75" type="text" value="120" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />

      @counter12
      @item.SessionEmail12
      @item.LoginUrl12
      @item.CreatedAt12
      Failed12

        <input id="itemprice75" name="itemprice75" type="text" value="100" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />

```

Body:
This table's row with 2 elements.One type is text and the other type is hidden.
If these element's values were different.jQuery-Ui framework will do the highlight background-color (red).

$(function() {

  $('table tr').each(function(i, val) {
    var nprice = $(this).children('.unit-price').find("input[type='text']").val();
    var oprice = $(this).children('.unit-price').find("input[type='hidden']").val();

    console.log("nprice: " + nprice);
    console.log("oprice: " + oprice);
    if (nprice != oprice) {
      console.log(i);
      console.log("nprice: " + nprice + "!=" + "oprice: " + oprice);
      var blink = setInterval(function() {
        $('.cart tr:eq(' + i + ') ').effect('highlight', {
          color: 'red'
        }, 1000);
      }, 1000);
      setTimeout(function() {
        clearInterval(blink);
      }, 10000);
    }
  });

});

.highlight {
  background: red;
  color: green;
  opacity: 0;
}

.unhighlight {
  background: transparent;
  color: black;
  -webkit-transition: background-color 1000ms linear;
  -ms-transition: background-color 1000ms linear;
  transition: background-color 1000ms linear;
}

.cart th,
.data-table th,
.forum-table th {
  border-width: 1px 1px 0;
  border-style: solid;
  border-color: #ddd;
  background-color: #f6f6f6;
  padding: 10px;
  white-space: nowrap;
  font-weight: normal;
}

.cart td {
  min-width: 50px;
  border-width: 1px;
  border-style: solid;
  border-color: transparent #ddd #ddd;
  background-color: #fff;
  padding: 20px;
  color: #444;
}

.cart a {
  font-weight: normal;
  color: #4ab2f1;
}

.cart a:hover {
  text-decoration: underline;
}

.cart .product {
  min-width: 225px;
  text-align: left;
}

.cart .product a {
  font-weight: bold;
  color: #444;
}

.cart .product a:hover {
  color: #4ab2f1;
  text-decoration: none;
}

.cart .product .edit-item {
  margin: 10px 0 0;
}

.cart .product .edit-item a {
  font-weight: normal;
  color: #4ab2f1;
}

.cart .product .edit-item a:hover {
  text-decoration: underline;
}

.cart .remove-from-cart,
.cart .add-to-cart {
  text-align: center;
}

.cart td.unit-price {
  white-space: nowrap;
}

.cart td.quantity input {
  width: 50px;
  text-align: center;
}

.cart td.subtotal {
  white-space: nowrap;
  color: #444;
}

.cart td.subtotal .discount,
.cart td.subtotal .discount-additional-info {
  font-style: italic;
  color: #4ab2f1;
}

  <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
  <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />

above with 2 values: 75 and 100
<<<highlight background-color was not working. Help. ```

      Id#
      Session Eamil
      Login Url
      Date
      Status
      New Price

      @counter11
      @item.SessionEmail11
      @item.LoginUrl11
      @item.CreatedAt11
      Failed11

        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />

      @counter12
      @item.SessionEmail12
      @item.LoginUrl12
      @item.CreatedAt12
      Failed12

        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />

      @counter12
      @item.SessionEmail12
      @item.LoginUrl12
      @item.CreatedAt12
      Failed12

        <input id="itemprice75" name="itemprice75" type="text" value="120" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />

      @counter12
      @item.SessionEmail12
      @item.LoginUrl12
      @item.CreatedAt12
      Failed12

        <input id="itemprice75" name="itemprice75" type="text" value="100" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />

The function "effect" which highlight background-color effects not working. How can I modify the JavaScript code or CSS?

Body:
Try call with callback like below.

let i = 2; //I set i for demo purpose. Your i comes from loop, so no need to declare .
$('.cart tr:eq(' + i + ') ').effect('highlight', {
  color: 'red'
}, 1000, callback);

function callback() {
  setTimeout(function() {
    $('.cart tr:eq(' + i + ') ').removeAttr("style").hide().fadeIn();
  }, 1000);
};

.cart td {
  min-width: 50px;
  border-width: 1px;
  border-style: solid;
  border-color: transparent #ddd #ddd;
  padding: 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<table class="cart">
  <thead>
    <tr>
      <th>Id#</th>
      <th>Session Eamil</th>
      <th>Login Url</th>
      <th>Date</th>
      <th>Status</th>
      <th>New Price</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="text-center">@counter11</td>
      <td>@item.SessionEmail11</td>
      <td>@item.LoginUrl11</td>
      <td>@item.CreatedAt11</td>
      <td>Failed11</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />
      </td>

    </tr>
    <tr>
      <td class="text-center">@counter12</td>
      <td>@item.SessionEmail12</td>
      <td>@item.LoginUrl12</td>
      <td>@item.CreatedAt12</td>
      <td>Failed12</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="75" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="75" class="unit-prev-price" />
      </td>

    </tr>
    <tr>
      <td class="text-center">@counter12</td>
      <td>@item.SessionEmail12</td>
      <td>@item.LoginUrl12</td>
      <td>@item.CreatedAt12</td>
      <td>Failed12</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="120" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />
      </td>

    </tr>
    <tr>
      <td class="text-center">@counter12</td>
      <td>@item.SessionEmail12</td>
      <td>@item.LoginUrl12</td>
      <td>@item.CreatedAt12</td>
      <td>Failed12</td>
      <td class="unit-price">
        <input id="itemprice75" name="itemprice75" type="text" value="100" class="enter-price-input" />
        <input id="itemprevprice75" name="itemprevprice75" type="hidden" value="100" class="unit-prev-price" />
      </td>

    </tr>
  </tbody>
</table>


问:
Two square bracket overloading
I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class.
if i have an object of class matrix like M1  then i can use this way for giving value to each element:

```<code>M1[1][2]=5;
</code>```

OR

```<code>int X;

X=M1[4][5];
</code>```

答:
Just overload operator[] and make it return a pointer to the respective row or column of the matrix. Since pointers support subscripting by [], access by the 'double-square' notation [][] is possible then.

You can also overload operator() with two arguments.

Title: Two square bracket overloading

Body:
I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class.
if i have an object of class matrix like M1  then i can use this way for giving value to each element:

M1[1][2]=5;

OR

int X;

X=M1[4][5];


问:
How to list npm user-installed packages
How do I list the user-installed / environment package only in npm?

When I do npm -g list, it outputs every package and their dependencies. Instead I'd like to see the packages installed in the current working project or environment.

答:
For local modules, usenpm list --depth 0.

For global modules, use npm list -g --depth 0.

Example local npm module

Example global npm module

Title: How to list npm user-installed packages


问:
How do you produce a random 0 or 1 with random.rand
I'm trying to produce a 0 or 1 with numpy's random.rand.

np.random.rand() produces a random float between 0 and 1 but not just a 0 or a 1.

Thank you.

答:
You can use np.random.choice with a list of [0,1], or use np.random.radint with a range of 0,2

```<code>In [1]: import numpy as np

In [2]: np.random.choice([0,1])
Out[2]: 0

In [5]: np.random.choice([0,1])
Out[5]: 1

In [8]: np.random.randint(2)
Out[8]: 0

In [9]: np.random.randint(2)
Out[9]: 1

</code>```

You can also use the random module for the equivalent of these functions

Body:
You can use np.random.choice with a list of [0,1], or use np.random.radint with a range of 0,2

In [1]: import numpy as np

In [2]: np.random.choice([0,1])
Out[2]: 0

In [5]: np.random.choice([0,1])
Out[5]: 1

In [8]: np.random.randint(2)
Out[8]: 0

In [9]: np.random.randint(2)
Out[9]: 1

You can also use the random module for the equivalent of these functions


问:
How can I find the location visited by all employees in this sql table?
I have a sql table that looks like this:

```<code>CREATE TABLE `location_visits` (
  `employee1_name` varchar(255) NOT NULL,
  `employee2_name` varchar(255) NOT NULL,
  `region_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee1_name`,`employee2_name`),
  CONSTRAINT `location_visits_fk1` FOREIGN KEY (`employee1_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `location_visits_fk2` FOREIGN KEY (`employee2_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
)
</code>```

Employees go to places together in pairs, sort of like a buddy system. I want to find the region(s) that has been visited by all employees.

If it helps, I also have a table that lists all of my employees:

```<code>CREATE TABLE `employees` (
  `employee_name` varchar(255) NOT NULL,
  PRIMARY KEY ('employee_name')
)
</code>```

All these tables are loaded with data, of course. So, an example for data that would be valid for location_visits table is (John, Chris, Maine), (John, Adam, New Hampshire), (Adam, Chris, Maine). In this scenario, the location visited by all employees Adam, Chris, John is Maine.

What kind of sql command would do this for me?

答:
Try

SELECT employee1_name, employee2_name FROM location_visits WHERE region_name='Maine'
```

Body:
I have a sql table that looks like this:

CREATE TABLE `location_visits` (
  `employee1_name` varchar(255) NOT NULL,
  `employee2_name` varchar(255) NOT NULL,
  `region_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee1_name`,`employee2_name`),
  CONSTRAINT `location_visits_fk1` FOREIGN KEY (`employee1_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `location_visits_fk2` FOREIGN KEY (`employee2_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
)

Employees go to places together in pairs, sort of like a buddy system. I want to find the region(s) that has been visited by all employees.

If it helps, I also have a table that lists all of my employees:

CREATE TABLE `employees` (
  `employee_name` varchar(255) NOT NULL,
  PRIMARY KEY ('employee_name')
)

All these tables are loaded with data, of course. So, an example for data that would be valid for location_visits table is (John, Chris, Maine), (John, Adam, New Hampshire), (Adam, Chris, Maine). In this scenario, the location visited by all employees Adam, Chris, John is Maine.

What kind of sql command would do this for me?


答: There is no operator[][] in C++. You have to return a helper object and then overload operator[] for that too, to have this kind of access.

Title: Two square bracket overloading


问:
How to unnest multiple list columns of a dataframe in one go with dplyr pipe
I have the following tibble, which has two nested columns:

```<code>library(tidyverse)
df <- structure(list(a = list(c("a", "b"), "c"), b = list(c("1", "2",
"3"), "3"), c = c(11, 22)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L))
</code>```

Which produces:

```<code># A tibble: 2 x 3
  a         b             c
  <list>    <list>    <dbl>
1 <chr [2]> <chr [3]>    11
2 <chr [1]> <chr [1]>    22
</code>```

How can I unnest them at once producing one single tibble?

I tried this but fail:

```<code>> df %>% unnest(a, b)
Error: All nested columns must have the same number of elements.
</code>```

答:
There's probably a cleaner way to do it, but if you want the cartesian product for the columns you can unnest them in sequence, if nothing else:</p>

```<code>> df %>%
    unnest(a, .drop = FALSE) %>%
    unnest(b, .drop = FALSE)

# # A tibble: 7 x 3
#       c a     b
#   <dbl> <chr> <chr>
# 1    11 a     1
# 2    11 a     2
# 3    11 a     3
# 4    11 b     1
# 5    11 b     2
# 6    11 b     3
# 7    22 c     3
</code>```

Body:
I have the following tibble, which has two nested columns:

library(tidyverse)
df <- structure(list(a = list(c("a", "b"), "c"), b = list(c("1", "2",
"3"), "3"), c = c(11, 22)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L))

Which produces:

# A tibble: 2 x 3
  a         b             c
  <list>    <list>    <dbl>
1 <chr [2]> <chr [3]>    11
2 <chr [1]> <chr [1]>    22

How can I unnest them at once producing one single tibble?

I tried this but fail:

> df %>% unnest(a, b)
Error: All nested columns must have the same number of elements.

Body:
There's probably a cleaner way to do it, but if you want the cartesian product for the columns you can unnest them in sequence, if nothing else:

> df %>%
    unnest(a, .drop = FALSE) %>%
    unnest(b, .drop = FALSE)

# # A tibble: 7 x 3
#       c a     b
#   <dbl> <chr> <chr>
# 1    11 a     1
# 2    11 a     2
# 3    11 a     3
# 4    11 b     1
# 5    11 b     2
# 6    11 b     3
# 7    22 c     3


问:
Loop through Excel files in subfolders and copy and paste data to one sheet
I'm trying to loop through all Excel files in subfolders of a folder designated by a user and copy and paste data to a new workbook named "Compilation". This code works up to creating and saving a new workbook but data wouldn't copy and paste to the workbook.

Can anyone please help?

```<code>Sub LoopCopyPasteSubfolders()

Dim fso As Object
Dim wb As Object
Dim folder As Object
Dim subfolder As Object
Dim MyPath As String
Dim MyFile As String
Dim FdrPicker As FileDialog

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FdrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FdrPicker
    .Title = "Select a Target Folder"
    .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        MyPath = .SelectedItems(1) & "\"
    End With

NextCode:
'in case of cancel
If MyPath = "" Then GoTo ResetSettings Else

Dim NewWB As Workbook
Set NewWB = Workbooks.Add

ActiveWorkbook.SaveAs Filename:="C:\Batch\Compilation.xlsx", FileFormat:=xlWorkbookNormal

Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.getfolder(MyPath)
Set subfolder = folder.subfolders
For Each subfolder In folder.subfolders
Set wb = subfolder.Files

 For Each wb In subfolder.Files
    If fso.GetExtensionName(wb.Path) = "*.xls*" Then
    Workbooks.Open wb, ReadOnly:=True
    Range("A1:M1").End(xlDown).Copy
    For Each cell In Workbooks("Compilation").Worksheets("Sheet1").Columns(1).Cells
        If IsEmpty(cell) = True Then cell.PasteSpecial Paste:=xlPasteValues
        'exit when value pasted to the first empty row

        Exit For
    Next cell
End If

Next wb

Next subfolder

'reset settings to default
ResetSettings:

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True

End Sub
</code>```

答:
```<code>Sub LoopCopyPasteSubfoldersIII()

Dim fso As Object
Dim wb As Object
Dim folder As Object
Dim subfolder As Object
Dim MyPath As String
Dim MyFile As String
Dim FdrPicker As FileDialog
Dim wba As Workbook

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FdrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FdrPicker
.Title = "Select a Target Folder"
.AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    MyPath = .SelectedItems(1) & "\"
End With

NextCode:
'in case of cancel
MyPath = MyPath
If MyPath = "" Then GoTo ResetSettings Else

Dim NewWB As Workbook
Set NewWB = Workbooks.Add

NewWB.SaveAs Filename:="C:\Users\405458\Downloads\Compilation.xlsx",
FileFormat:=xlWorkbookNormal

Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.getfolder(MyPath)

For Each subfolder In folder.subfolders

For Each wb In subfolder.Files
    If fso.GetExtensionName(wb.Path) = "*.xls*" Then
        Set wba = Workbooks.Open(wb.Path & "\" & wb.FullName, , True)
            wba.Worksheets(1).Range("A1:M20").Copy
            For Each cell In
Workbooks("Compilation").Worksheets("Sheet1").Columns(1).Cells
                If IsEmpty(cell) = True Then
                   cell.PasteSpecial Paste:=xlPasteValues
                'exit when value pasted to the first empty row
                End If
            Exit For

            Next cell
        wba.Close False
        NewWB.Save
    End If
Next wb

Next subfolder

'reset settings to default
ResetSettings:

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True

End Sub
</code>```

Body:
I'm trying to loop through all Excel files in subfolders of a folder designated by a user and copy and paste data to a new workbook named "Compilation". This code works up to creating and saving a new workbook but data wouldn't copy and paste to the workbook.

Can anyone please help?

Sub LoopCopyPasteSubfolders()

Dim fso As Object
Dim wb As Object
Dim folder As Object
Dim subfolder As Object
Dim MyPath As String
Dim MyFile As String
Dim FdrPicker As FileDialog

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FdrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FdrPicker
    .Title = "Select a Target Folder"
    .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        MyPath = .SelectedItems(1) & "\"
    End With

NextCode:
'in case of cancel
If MyPath = "" Then GoTo ResetSettings Else

Dim NewWB As Workbook
Set NewWB = Workbooks.Add

ActiveWorkbook.SaveAs Filename:="C:\Batch\Compilation.xlsx", FileFormat:=xlWorkbookNormal

Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.getfolder(MyPath)
Set subfolder = folder.subfolders
For Each subfolder In folder.subfolders
Set wb = subfolder.Files

 For Each wb In subfolder.Files
    If fso.GetExtensionName(wb.Path) = "*.xls*" Then
    Workbooks.Open wb, ReadOnly:=True
    Range("A1:M1").End(xlDown).Copy
    For Each cell In Workbooks("Compilation").Worksheets("Sheet1").Columns(1).Cells
        If IsEmpty(cell) = True Then cell.PasteSpecial Paste:=xlPasteValues
        'exit when value pasted to the first empty row

        Exit For
    Next cell
End If

Next wb

Next subfolder

'reset settings to default
ResetSettings:

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True

End Sub


问:
How can I check Koin modules while using injection parameters?
I would like to check my configuration by using the checkModules() method provided by koin-test as explained here.

However, I am using injection parameters and my test fails with an exception:

```<code>org.koin.core.error.NoParameterFoundException: Can't get parameter value #0 from org.koin.core.parameter.DefinitionParameters@3804648a
</code>```

Here is a simple test to demonstrate the issue:

```<code>import org.junit.Test
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.check.checkModules

class TestCase : KoinTest {
    @Test
    fun checkModules() {
        koinApplication {
            modules(
                module { factory { (msg: String) -> Message(msg) } }
            )
        }.checkModules()
    }

    data class Message(val message: String)
}
</code>```

Is there a way to make this work? How could I provide the missing parameter?

答:
You need to pass this parameter to your test, like this:

```<code>class TestCase : KoinTest {
    @Test
    fun checkModules() {
        koinApplication {
            modules(module { factory { (msg: String) -> Message(msg) } })
        }.checkModules {
            create<Message> { parametersOf("testMessage") }
        }
    }

    data class Message(val message: String)
}
</code>```

Example from Koin repository: CheckModulesTest.kt#L156

My issue with the same question: Issue

Body:
I would like to check my configuration by using the checkModules() method provided by koin-test as explained here.

However, I am using injection parameters and my test fails with an exception:

org.koin.core.error.NoParameterFoundException: Can't get parameter value #0 from org.koin.core.parameter.DefinitionParameters@3804648a

Here is a simple test to demonstrate the issue:

import org.junit.Test
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.check.checkModules

class TestCase : KoinTest {
    @Test
    fun checkModules() {
        koinApplication {
            modules(
                module { factory { (msg: String) -> Message(msg) } }
            )
        }.checkModules()
    }

    data class Message(val message: String)
}

Is there a way to make this work? How could I provide the missing parameter?

Body:
You need to pass this parameter to your test, like this:

class TestCase : KoinTest {
    @Test
    fun checkModules() {
        koinApplication {
            modules(module { factory { (msg: String) -> Message(msg) } })
        }.checkModules {
            create<Message> { parametersOf("testMessage") }
        }
    }

    data class Message(val message: String)
}

Example from Koin repository: CheckModulesTest.kt#L156

My issue with the same question: Issue