问:
List file using ls command in Linux with full path
Many will found that this is repeating questions but i have gone through all the questions before asked about this topic but none worked for me.

I want to print full path name of the certain file format using ls command so far i found chunk of code that will print all the files in the directory but not full path.

```<code>for i in io.popen("ls /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7"):lines() do
  if string.find(i,"%.*$") then
     print(i)
  end
end
</code>```

this will print out all the file in root diractory and subdiratory.

Output:

```<code>  0020111118223425.lvf
  2012
  2012 (2009).mp4
  3 Idiots
  Aashiqui 2
  Agneepath.mkv
  Avatar (2009)
  Captain Phillips (2013)
  Cocktail
</code>```

I want output like:

```<code>  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/0020111118223425.lvf           [File in Root Directory]
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/2012/2012.mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/2012 (2009).mp4                [File in Root Directory]
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/3 Idiots/3 Idiots.mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Aashiqui 2/Aashiqui 2.mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Avatar (2009)/Avatar (2009).mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Captain Phillips (2013).mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Cocktail/Cocktail.mkv
</code>```

EDIT:
I have used this all but its not working with my code in LUA.

when I used with my code it displays wrong directory

```<code>for i in io.popen("ls -d $PWD/* /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7"):lines() do
    if string.find(i,"%.*$") then
      print("/mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/"..i)
    end
  end
</code>```

is not finding files in "/mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7" insted its prints the machines root directory files.

答:
This worked for me:</p>

```<code>ls -rt -d -1 $PWD/{*,.*}
</code>```

Body:
Many will found that this is repeating questions but i have gone through all the questions before asked about this topic but none worked for me.

I want to print full path name of the certain file format using ls command so far i found chunk of code that will print all the files in the directory but not full path.

for i in io.popen("ls /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7"):lines() do
  if string.find(i,"%.*$") then
     print(i)
  end
end

this will print out all the file in root diractory and subdiratory.

Output:

  0020111118223425.lvf
  2012
  2012 (2009).mp4
  3 Idiots
  Aashiqui 2
  Agneepath.mkv
  Avatar (2009)
  Captain Phillips (2013)
  Cocktail

I want output like:

  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/0020111118223425.lvf           [File in Root Directory]
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/2012/2012.mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/2012 (2009).mp4                [File in Root Directory]
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/3 Idiots/3 Idiots.mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Aashiqui 2/Aashiqui 2.mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Avatar (2009)/Avatar (2009).mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Captain Phillips (2013).mkv
  /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/Cocktail/Cocktail.mkv

EDIT:
I have used this all but its not working with my code in LUA.

when I used with my code it displays wrong directory

for i in io.popen("ls -d $PWD/* /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7"):lines() do
    if string.find(i,"%.*$") then
      print("/mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/"..i)
    end
  end

is not finding files in "/mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7" insted its prints the machines root directory files.

Body:
This worked for me:

ls -rt -d -1 $PWD/{*,.*}


来源: stackexchange

问:
JSON file proper Case and word spacing
I am wondering what will be the best approach for word case and word delimiter in JSON

considering that later on the JSON file will be converted to a Java Pojo and i would like this Java Pojo to be in ProperCase

I am debating between:

```<code>"sectionSuspensionTiresSteering": [{
"SectionSuspensionTiresSteering": [{
"section_suspension_tires_steering": [{
"section Suspension Tires Steering": [{
</code>```

答:
I understand that JSON properties are written in camel case (sectionSuspensionTiresSteering) style.

But it has nothing to do with how the property will be written or coded in java.

For example if you use Gson() to do the conversions between java an JSON you can name the java property whatever you want and annotate the property with @SerializedName("jsonName") passing in the JSON property name.

What I mean is that the two names are not coupled.

ContentLicense: CC BY-SA 3.0

Title: JSON file proper Case and word spacing

Body:
I am wondering what will be the best approach for word case and word delimiter in JSON

considering that later on the JSON file will be converted to a Java Pojo and i would like this Java Pojo to be in ProperCase

I am debating between:

"sectionSuspensionTiresSteering": [{
"SectionSuspensionTiresSteering": [{
"section_suspension_tires_steering": [{
"section Suspension Tires Steering": [{


问:
User in student role automatically
In asp.net(C #) I want to automatically add the new users when they sign up in a particular role (student role) i have managed the role but how i can automatically add them or like in more simple words

i want new users to get in Student Role by default

what are the codes and processure please help !!

答:
Without seeing your code, it is difficult to tell how best to achieve this.

I would simply set the role to Student in the user class constructor.

ContentLicense: CC BY-SA 2.5

Title: User in student role automatically


问:
Appveyor docker mounts fail

Appveyor Visual Studio 2017 image

Simple command in the install: section of the .appveyor.yaml:

docker run --rm -v c:/Users:/data alpine ls /data

I always get

```<code>docker: Error response from daemon: invalid bind mount spec "c:/Users:/data":
invalid volume specification: 'c:\Users:\data'.
</code>```

I've tried lots of ways of specifying the volume (//c/Users, /c/Users, LOTS)

It's possible that appveyor image doesn't have the C drive shared and that's the problem? How would we cause it to be shared?

答:
For Windows correct mounting syntax is c:/Users:c:/data (to mount host directory C:\Users as container directory C:\data):

```<code>docker run --rm -v c:/Users:c:/data alpine dir c:\data
</code>```

Title: Appveyor docker mounts fail

Body:
Appveyor Visual Studio 2017 image

Simple command in the install: section of the .appveyor.yaml:

docker run --rm -v c:/Users:/data alpine ls /data

I always get

docker: Error response from daemon: invalid bind mount spec "c:/Users:/data":
invalid volume specification: 'c:\Users:\data'.

I've tried lots of ways of specifying the volume (//c/Users, /c/Users, LOTS)

It's possible that appveyor image doesn't have the C drive shared and that's the problem? How would we cause it to be shared?

Body:
For Windows correct mounting syntax is c:/Users:c:/data (to mount host directory C:\Users as container directory C:\data):

docker run --rm -v c:/Users:c:/data alpine dir c:\data


问:
My background Image won't show up on the div
I am trying to create a div and add a background image to it in jQuery. For some reason, I cannot do it. If I instead make my background color white, I get a white background. Here is my code:

```<code>function appendToDom(poster) {
        var aPoster = $('<div>');
        aPoster.css({
                display: 'inline block',
                float: 'left',
                margin: '10px',
                marginLeft: '37px',
                marginTop: '20px',
                width: '200px',
                height: '300px',
                fontSize: '36px',
                color: 'black',
                //backgroundColor: 'white',
                backgroundSize: '200px 300px',
                backgroundImage: './../images/question.png'
            })
            /*
                    $(aPoster).attr("css","background-image: url(~/desktop/MyMovies/public/js/images/question.jpeg)");
                    $(aPoster).attr("css","background-size: 200px 300px");*/
        $(main).append(aPoster);
    }
</code>```

Thanks for all the advice! So I took the suggestions given to me, but it still doesn't work for me.Here is a screenshot of what I have:

my improved code

NVM I got it! Thanks!

答: If the style is inline like in your case, the path has to be relative to the html document. Please check it.</p>

Body:
I am trying to create a div and add a background image to it in jQuery. For some reason, I cannot do it. If I instead make my background color white, I get a white background. Here is my code:

function appendToDom(poster) {
        var aPoster = $('
');
        aPoster.css({
                display: 'inline block',
                float: 'left',
                margin: '10px',
                marginLeft: '37px',
                marginTop: '20px',
                width: '200px',
                height: '300px',
                fontSize: '36px',
                color: 'black',
                //backgroundColor: 'white',
                backgroundSize: '200px 300px',
                backgroundImage: './../images/question.png'
            })
            /*
                    $(aPoster).attr("css","background-image: url(~/desktop/MyMovies/public/js/images/question.jpeg)");
                    $(aPoster).attr("css","background-size: 200px 300px");*/
        $(main).append(aPoster);
    }

Thanks for all the advice! So I took the suggestions given to me, but it still doesn't work for me.Here is a screenshot of what I have:

my improved code

NVM I got it! Thanks!


问:
Render a component when another component is clicked
I want to render BlackSpark when RedSpark is clicked, but I'm not sure how to change the state of  a component in another component. I know how to set state in the component itself, but how do I affect another component when I click a different component?

```<code>class BlackSpark extends React.Component {
    render() {
        return (
            <div className="black"></div>
        );
    }
}

class RedSpark extends React.Component {
    render() {
        return (
            <div className="red"></div>
        );
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
             <BlackSpark />
             <RedSpark />
            </div>
        );
    }
}
</code>```

答:
In React, there's a concept of component composition as you've already embraced -- it allows you to accomplish what you want by rendering children based on the parent's state, another key concept known as lifting state up. What this means, is if you have mutually dependent components, create a single parent which composes them, and have state in the parent control the presentation and logic of the children. With the parent App, you can keep your state inside App, and based on App's state, conditionally render whatever you want -- either BlackSpark or both. For example, using the logical && operator:

```<code>{condition && <Component />}
</code>```

This will only render <Component> when condition is truthy, or else it will not render anything at all (except for when condition is 0). Applying it to this situation, try adding state to your App component to utilize conditional rendering.

There's another key concept you need to understand: component props. They are essentially inputs to a component, certain properties passed to the component to tell how it should behave -- like attributes on regular HTML elements such as input placeholders, URLs, and event handlers. For example:

```<code><Component foo="bar" bar={3} />
</code>```

This will pass the props foo and bar down to Component with the values "bar" and 3 respectively and are accessible through this.props. If you were to access this.props.foo inside the Component component it would give you "bar". If you pair this up with composition, you can accomplish what you want:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      showHello: true
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange() {
    this.setState(prevState => ({
      showHello: !prevState.showHello
    }));
  }

  render() {
    return (

        {this.state.showHello && <Child2 />}
        This is a test.
        <Child1 onClick={this.handleChange} />

    );
  }
}

class Child1 extends React.Component {
  render() {
    return
Click me!

  }
}

class Child2 extends React.Component {
  render() {
    return
Hello!

  }
}

ReactDOM.render(<Example />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

The above example lifts state up by having a parent compose the children and maintain the state. It then uses props to pass down an onClick handler to Child1, so that whenever Child1 is clicked, the state of the parent changes. Once the state of the parent changes, it will use conditional rendering to render <Child2> if the condition is truthy. Further reading at the React documentation and on the logical && operator.

Body:
I want to render BlackSpark when RedSpark is clicked, but I'm not sure how to change the state of  a component in another component. I know how to set state in the component itself, but how do I affect another component when I click a different component?

class BlackSpark extends React.Component {
    render() {
        return (

        );
    }
}

class RedSpark extends React.Component {
    render() {
        return (

        );
    }
}

class App extends React.Component {
    render() {
        return (

             <BlackSpark />
             <RedSpark />

        );
    }
}

Body:
In React, there's a concept of component composition as you've already embraced -- it allows you to accomplish what you want by rendering children based on the parent's state, another key concept known as lifting state up. What this means, is if you have mutually dependent components, create a single parent which composes them, and have state in the parent control the presentation and logic of the children. With the parent App, you can keep your state inside App, and based on App's state, conditionally render whatever you want -- either BlackSpark or both. For example, using the logical && operator:

{condition && <Component />}

This will only render <Component> when condition is truthy, or else it will not render anything at all (except for when condition is 0). Applying it to this situation, try adding state to your App component to utilize conditional rendering.

There's another key concept you need to understand: component props. They are essentially inputs to a component, certain properties passed to the component to tell how it should behave -- like attributes on regular HTML elements such as input placeholders, URLs, and event handlers. For example:

<Component foo="bar" bar={3} />

This will pass the props foo and bar down to Component with the values "bar" and 3 respectively and are accessible through this.props. If you were to access this.props.foo inside the Component component it would give you "bar". If you pair this up with composition, you can accomplish what you want:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      showHello: true
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange() {
    this.setState(prevState => ({
      showHello: !prevState.showHello
    }));
  }

  render() {
    return (
      <div>
        {this.state.showHello && <Child2 />}
        This is a test.
        <Child1 onClick={this.handleChange} />
      </div>
    );
  }
}

class Child1 extends React.Component {
  render() {
    return <div onClick={this.props.onClick}>Click me!</div>
  }
}

class Child2 extends React.Component {
  render() {
    return <div>Hello!</div>
  }
}

ReactDOM.render(<Example />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

The above example lifts state up by having a parent compose the children and maintain the state. It then uses props to pass down an onClick handler to Child1, so that whenever Child1 is clicked, the state of the parent changes. Once the state of the parent changes, it will use conditional rendering to render <Child2> if the condition is truthy. Further reading at the React documentation and on the logical && operator.


问:
Handle 3 different responses from one single POST request
I'm trying to change the following code so it only makes one query instead of two. The problem is, you can see there are 3 possible responses I need returned. The default is 404 at the bottom if no conditionals are met, and the second 404 response is returned if the login credentials are correct BUT the account has expired. The only valid response (200) is returned if the account is correct and active.

How do I combine the SELECT statements into one while preserving the ability to respond in 3 different ways depending on the user's status?

```<code>    @POST
    @Path("accounts/initial/{user}")
    @Produces("application/json")
    @Consumes("application/json")
    public Response validate(@PathParam("user") final String username) {

        PreparedStatement statement = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            conn = LicenseDBSource.getInstance().getConnection();
            statement = conn.prepareStatement("SELECT * FROM members WHERE username = ?");
            statement.setString(1, username);
            rs = statement.executeQuery();

            if (rs.next()) {
                statement = conn.prepareStatement("SELECT * FROM members WHERE
                username = ? AND LOCALTIMESTAMP < expiration");
                statement.setString(1, username);

                rs = statement.executeQuery();
                if (rs.next()) {
                    return Response.status(200).build();
                    }
                } else {
                    return Response.status(404).entity("Expired").build();
                }
            }
        } catch (...) {
           ...handle exceptions...
        } finally {
            closeResources(...);
        }
        return Response.status(404).entity("Incorrect").build();
    }
</code>```

My database contains columns including "username" and "expiration".

答:
If you want to perform two queries with just one statement, you can just use two subqueries. Your try block would look like:

```<code>try {
    conn = LicenseDBSource.getInstance().getConnection();
    statement = conn.prepareStatement(
        "SELECT " +
        "   EXISTS (SELECT * FROM members WHERE username = ?) AS user_exists, " +
        "   EXISTS (SELECT * FROM members WHERE username = ? " +
                       " AND LOCALTIMESTAMP < expiration) AS user_is_current" ;
    statement.setString(1, username);
    statement.setString(2, username);
    rs = statement.executeQuery();
    rs.next(); // There will *always* be one row
    if (rs.getBoolean("user_exists")) {
        if (rs.getBoolean("user_is_current") {
            return Response.status(200).build();
        } else {
            return Response.status(404).entity("Expired").build();
        }
    }
</code>```

Alternative, use a single query, but this time you have two options: it either returns no rows (meaning user doesn't exist), or returns just one row (assuming usrname is PK) with a computed column telling you whether the user is current. That's actually cleaner and take less time than the previous approach:

```<code>try {
    conn = LicenseDBSource.getInstance().getConnection();
    statement = conn.prepareStatement(
        "SELECT " +
        "    (LOCALTIMESTAMP < expiration) AS user_is_current " +
        "FROM " +
        "    members WHERE username = ?";

    statement.setString(1, username);
    rs = statement.executeQuery();

    if (rs.next()) {
        if (rs.getBoolean("user_is_current") {
            return Response.status(200).build();
        } else {
            return Response.status(404).entity("Expired").build();
        }
    }
}
</code>```

Body:
I'm trying to change the following code so it only makes one query instead of two. The problem is, you can see there are 3 possible responses I need returned. The default is 404 at the bottom if no conditionals are met, and the second 404 response is returned if the login credentials are correct BUT the account has expired. The only valid response (200) is returned if the account is correct and active.

How do I combine the SELECT statements into one while preserving the ability to respond in 3 different ways depending on the user's status?

    @POST
    @Path("accounts/initial/{user}")
    @Produces("application/json")
    @Consumes("application/json")
    public Response validate(@PathParam("user") final String username) {

        PreparedStatement statement = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            conn = LicenseDBSource.getInstance().getConnection();
            statement = conn.prepareStatement("SELECT * FROM members WHERE username = ?");
            statement.setString(1, username);
            rs = statement.executeQuery();

            if (rs.next()) {
                statement = conn.prepareStatement("SELECT * FROM members WHERE
                username = ? AND LOCALTIMESTAMP < expiration");
                statement.setString(1, username);

                rs = statement.executeQuery();
                if (rs.next()) {
                    return Response.status(200).build();
                    }
                } else {
                    return Response.status(404).entity("Expired").build();
                }
            }
        } catch (...) {
           ...handle exceptions...
        } finally {
            closeResources(...);
        }
        return Response.status(404).entity("Incorrect").build();
    }

My database contains columns including "username" and "expiration".

Body:
If you want to perform two queries with just one statement, you can just use two subqueries. Your try block would look like:

try {
    conn = LicenseDBSource.getInstance().getConnection();
    statement = conn.prepareStatement(
        "SELECT " +
        "   EXISTS (SELECT * FROM members WHERE username = ?) AS user_exists, " +
        "   EXISTS (SELECT * FROM members WHERE username = ? " +
                       " AND LOCALTIMESTAMP < expiration) AS user_is_current" ;
    statement.setString(1, username);
    statement.setString(2, username);
    rs = statement.executeQuery();
    rs.next(); // There will *always* be one row
    if (rs.getBoolean("user_exists")) {
        if (rs.getBoolean("user_is_current") {
            return Response.status(200).build();
        } else {
            return Response.status(404).entity("Expired").build();
        }
    }

Alternative, use a single query, but this time you have two options: it either returns no rows (meaning user doesn't exist), or returns just one row (assuming usrname is PK) with a computed column telling you whether the user is current. That's actually cleaner and take less time than the previous approach:

try {
    conn = LicenseDBSource.getInstance().getConnection();
    statement = conn.prepareStatement(
        "SELECT " +
        "    (LOCALTIMESTAMP < expiration) AS user_is_current " +
        "FROM " +
        "    members WHERE username = ?";

    statement.setString(1, username);
    rs = statement.executeQuery();

    if (rs.next()) {
        if (rs.getBoolean("user_is_current") {
            return Response.status(200).build();
        } else {
            return Response.status(404).entity("Expired").build();
        }
    }
}


问:
Selenium WebDriver and Selenium server
I need your help to wire things related to selenium.
Now over the past few weeks I have been reading about Selenium documents.
There is selenium IDE (a firefox extension for record and replay tests)
Selenium RC - (selenium 1.0). This seems to be deprecated now and uses a proxy HTTP server to run test on multiple browsers.
Selenium Web Driver - (selenium 2.0). This is the latest one and one which should be used now for automated tests.
(Each browser implements Web Driver API)
I also read that web driver interacts with native browser support for automation and does not require HTTP server.

Then there is this Selenium server. (selenium stand alone server written in java)
The interaction with selenium server is via JSON wire protocol. (where each language binding call selenium server passing JSON data over HTTP)

Now I have the following question :

Does the Selenium server same as the proxy server used in selenium
RC?

Does the selenium RC uses JSON wire protocol.

Where is selenium server fits in Selenium 2.0, if web driver
interacts with native browser support for automation.

Lets say I am running my tests using selenium 2.0, java client
library, in chrome browser. When I call a WebDriver API, how does it
interacts with chrome driver? Does it uses JSON wire protocol?

...
I have more questions, but needs the answer of the above ones to clear Selenium cloud in my head.

答:
1- Selenium Server 2.0 is compatible with Selenium RC. The version bump from 1.0 to 2.0 was mainly because they add WebDriver API to the server. So, Selenium Server 2.0 kind of include Selenium RC.

A few months ago they removed the Selenium RC API from Selenium Server, being that the main factor to again bump the version number, this time to 3.0.

Note: You still you can use the RC API with Selenium 3 (using a legacy module that not comes out the box with the Selenium Server .jar), but since the RC API is implemented using WebDriver instead of Selenium Core, some tests could behave differently.

2- No, JSON Wire Protocol is the WebDriver protocol, kind of tie to the WebDriver Interface or API. W3C doc here. The JSON Wire Protocol could be seen as the way to represent in the context of a client/server communication, the commands defined in the WebDriver API binding (e.g. go to an specific URL, click on a element, ...).

3- Selenium Server is a "WebDriver server". Your tests scripts can communicate with it using the JSON Wire Protocol and sends "WebDriver commands". Depending on the capability needed by your tests scripts (e.g. what browser your tests scripts want to use) then the Selenium Server "forward/execute" the commands in one way or another.

If you specified that you want the HtmlUnit headless browser, then Selenium Server will not forward the commands to any other process but execute them using the HtmlUnitDriver that come bundled with the Selenium Server.

If you specified that you want the Chrome browser, then Selenium Server will "forward" the commands to the ChromeDriver(in case of Chrome, the WebDriver driver is a completely separate "WebDriver Server" process).

I this way, Selenium Server is useful to concentrate at one point, outside your tests scripts, all the neccesary burden to deal with several browsers. You can configure it to deal with several browsers.

Besides you can make Selenium Server behave like a grid, and just talk with one endpoint, the hub, that will be in charge to distribute the tests to all the registered nodes.

4- Yes, partially already explained. Just add that you can connect directly from your test scripts to the ChromeDriver if you want.

Title: Selenium WebDriver and Selenium server


问:
Node-Red Program to display results on Labview
I am running Node-Red on a Raspberry Pi 3. The node-red program allows me to run the Input/Output modules.

I was wondering if I can use LabVIEW to show my results from node red on the front panel of LabVIEW or do I have to create a separate program in LabVIEW to run my I/O modules.

答:
You could try one of the following:

Run your Node-Red program and communicate with the Node-Red program via LabVIEW using the Node-Red API.  You would need to rebuild the GUI in LabVIEW

Insert the Node-Red Webpage into LabVIEW

If you're using windows, place an ActiveX container from the
  containers palette on the FP, right click and select Insert ActiveX
  object. Find the Internet Explorer object (it may be called Microsoft
  Web Browser) and use property and invoke nodes to load the URL you
  want.

To me either option doesn't really make sense.  If you already have LabVIEW, you could just use LabVIEW to talk with your sensors.


问:
IOS/Objective-C/CoreData: Adding new managed objects to an MOC
I want to add some new managed objects to an entity in core data. These managed objects are also represented by a class

Is it necessary to do the following each time?

```<code> NSEntityDescription *entity = [NSEntityDescription entityForName:@"Steps" inManagedObjectContext:self.managedObjectContext];
        // Initialize Record
        NSManagedObject *blankStep = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
</code>```

Alternatively, if I have an array of these objects, can I merely add a new object to the array and then save the context?

```<code>NSMutableArray <Steps *> *theNewSteps = [NSMutableArray arrayWithCapacity:20];
Steps *blankStep = [[Steps* alloc] init];
[theNewSteps addObject: blankStep];
</code>```

Am confused about what is going on here.

答:
Is it necessary to do the following each time?

Yes, either that or this:

```<code>NSManagedObject *blankStep = [NSEntityDescription insertNewObjectForEntityForName:@"Steps" inManagedObjectContext: self.managedObjectContext];
</code>```

Either way instantiates a new object and inserts it into the managed object context.

Alternatively, if I have an array of these objects, can I merely add a new object to the array and then save the context?

No. Core Data doesn't know about your array, so it doesn't know if you change that array. Also, this line:

```<code>Steps *blankStep = [[Steps alloc] init];
</code>```

Will fail because it tries to create a new Steps instance but doesn't call the designated initializer for the class. You can't use init for managed objects, you need to use either your first code snippet or the version I mentioned above.

Body:
I want to add some new managed objects to an entity in core data. These managed objects are also represented by a class

Is it necessary to do the following each time?

 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Steps" inManagedObjectContext:self.managedObjectContext];
        // Initialize Record
        NSManagedObject *blankStep = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];

Alternatively, if I have an array of these objects, can I merely add a new object to the array and then save the context?

NSMutableArray <Steps *> *theNewSteps = [NSMutableArray arrayWithCapacity:20];
Steps *blankStep = [[Steps* alloc] init];
[theNewSteps addObject: blankStep];

Am confused about what is going on here.

Body:
Is it necessary to do the following each time?

Yes, either that or this:

NSManagedObject *blankStep = [NSEntityDescription insertNewObjectForEntityForName:@"Steps" inManagedObjectContext: self.managedObjectContext];

Either way instantiates a new object and inserts it into the managed object context.

Alternatively, if I have an array of these objects, can I merely add a new object to the array and then save the context?

No. Core Data doesn't know about your array, so it doesn't know if you change that array. Also, this line:

Steps *blankStep = [[Steps alloc] init];

Will fail because it tries to create a new Steps instance but doesn't call the designated initializer for the class. You can't use init for managed objects, you need to use either your first code snippet or the version I mentioned above.


问:
How to Custom Tab bar item text
I am using five tab bar items in the tab bar,i want to custom the text which is displayed on that.Is it possible.Please help me in this.Thanks in advance

Thanks
ask

答: you can use IB to do this.click ones on tab bar item and go to its property by command+1 and then again click ones on same tab bar item and you will get property window in which you can change the text of tab bar item...</p>

Title: How to Custom Tab bar item text


问:
How do I delete an item in rails?
I am doing a Ruby on Rails course and I am on a part where I am trying to delete a portfolio item but it is giving me an error. Here's the error.

ActiveRecord::InvalidForeignKey in PortfoliosController#destroy

PG::ForeignKeyViolation: ERROR: update or delete on table "portfolios" violates foreign key constraint "fk_rails_cc5ab4a1c3" on table "technologies" DETAIL: Key (id)=(12) is still referenced from table "technologies". : DELETE FROM "portfolios" WHERE "portfolios"."id" = $1

Extracted source (around line #52):

```<code>50
51 # Destroy/delete the record
52 @portfolio_item.destroy
53
54 # Redirect
55 respond_to do |format|`
</code>```

Rails.root: /home/ubuntu/workspace/DevcampPortfolio/ClonedRepo/Devcamp-Portfolio

Application Trace | Framework Trace | Full Trace
app/controllers/portfolios_controller.rb:52:in 'destroy'

Request

Parameters:

{"_method"=>"delete", "authenticity_token"=>"3fGuZqFrTblpS7aQGpfszjN24lSxu6SAr5/JRlLc0RDupDZ7BJKJr6kPnEYHa0/BR7rmTPnN+/i5Ptjb3wCLtw==", "id"=>"12"}

Response

Headers:

None

the code for the place I am in the course

my code

What do I change to fix it?

答:
You need to add dependent: :destroy to your has_many relation on the portfolio model.

has_many :technologies, dependent: :destroy
This will make it so that when you destroy a portfolio it destroys the technologies that "belong" to the portfolio.

If you want to keep the technologies you need to change the relationship between them, or allow them to be parentless and hook a before_destroy action to the portfolio model.

Title: How do I delete an item in rails?

Body:
I am doing a Ruby on Rails course and I am on a part where I am trying to delete a portfolio item but it is giving me an error. Here's the error.

ActiveRecord::InvalidForeignKey in PortfoliosController#destroy

PG::ForeignKeyViolation: ERROR: update or delete on table "portfolios" violates foreign key constraint "fk_rails_cc5ab4a1c3" on table "technologies" DETAIL: Key (id)=(12) is still referenced from table "technologies". : DELETE FROM "portfolios" WHERE "portfolios"."id" = $1

Extracted source (around line #52):

50
51 # Destroy/delete the record
52 @portfolio_item.destroy
53
54 # Redirect
55 respond_to do |format|`

Rails.root: /home/ubuntu/workspace/DevcampPortfolio/ClonedRepo/Devcamp-Portfolio

Application Trace | Framework Trace | Full Trace
app/controllers/portfolios_controller.rb:52:in 'destroy'

Request

Parameters:

{"_method"=>"delete", "authenticity_token"=>"3fGuZqFrTblpS7aQGpfszjN24lSxu6SAr5/JRlLc0RDupDZ7BJKJr6kPnEYHa0/BR7rmTPnN+/i5Ptjb3wCLtw==", "id"=>"12"}

Response

Headers:

None

the code for the place I am in the course

my code

What do I change to fix it?


答:
I don't really think that JSON has a naming convention, so you can "choose" sort of speak. As I have a Java background, I prefer using camelCase (your first option). I would avoid using blank spaces in the JSON keys, it is allowed but causes problems because most of the existing framework aren't able to deal with it.

So you are free to use the style you want. Regarding the conversion back to Java Pojo, this is just a matter of annotations. When you use for example Jackson, it allows you to annotate your fields in order to convert the JSON file back to a Java Pojo.

Title: JSON file proper Case and word spacing


问:
Prestashop cash on delivery fee
I am a bit new in prestashop and I have following question.

I am using prestashop 1.6 and I would like to add fee when costumer wants to pay with Cash on delivery. I tried to use some of free modules, but they didn't add fee to final price, so prices listed in back office were without fee.

Thanks for help in advance.

答:
You can use Handling charges on Shipping > Preferences
Then just enable Handling charges into Cash on delivery settings

Title: Prestashop cash on delivery fee


问:
Microsoft webchat in french
I have embed the Microsoft web chat channel into my site using the iFrame methode :
    https://webchat.botframework.com/embed/mybot?s=YOUR_SECRET_HERE'>

The web chat interface is in english, what parameters do I need to get the french version ? (the microsoft framework says french is supported).

答:
To localize the content of your bot you need to configure the default locale in your bot code, and provide resource files that define the default messaging in your language.  All of this happens in your bot code and not in WebChat. The WebChat control is just the delivery mechanism for your bot's messages.

For more information on localization in Bot Framework:

.NET SDK: https://learn.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-formflow-localize

Node SDK: https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-localization

Code Examples:

.NET SDK: https://github.com/Microsoft/BotBuilder/tree/master/CSharp/Samples/AnnotatedSandwichBot

Node SDK: https://github.com/Microsoft/BotBuilder/tree/master/Node/examples/basics-localization

Title: Microsoft webchat in french


问:
Find keyCode in other language
I am building an application designed for Hebrew speakers.

The code keyEvent.KEYCODE_ENTER gives me the KeyCode for Enter on the english keyboard. How do I find out what is the KeyCode for Enter on the hebrew keybord?

答:
Please find it out here by loading this page, focusing the text box and pressing the key you want to investigate (Enter in your case):

https://www.w3.org/2002/09/tests/keys.html

Title: Find keyCode in other language


问:
Only default controller is working and the rest is 404 not found
I'm using codeigniter on my wamp and everything is fine but when I upload it on live server the default_controller is working but the other controller are 404 not found or "The requested URL /Sample_controller was not found on this server".

Here is my sample controller:

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Sample_controller extends CI_Controller {
        function __construct(){
            parent::__construct();
    }

    public function index(){
        print_r('Hello World');
    }
}
</code>```

and here's my config.php:

```<code>$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
$config['allow_get_array'] = TRUE;
</code>```

and this is my router.php:

```<code>$route['default_controller']    = 'login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

and my .htaccess:

```<code><IfModule mod_rewrite.c>
    Options +FollowSymLinks
    Options +Indexes
    RewriteEngine On

    RewriteBase /folder
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{HTTP_HOST} !www.sampleurl.com$ [NC]
    RewriteCond %{REQUEST_URI} ^/$

    RewriteCond $1 !^(index\.php|assets|user_assets|tmp|robots\.txt)
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
</code>```

if I tried this sampleurl.com it's working fine and will direct me to my default controller which is the login but if i tried this sampleurl.com/sample_controller or sampleurl.com/login it will lead me to 404 not found The requested URL /sample_controller was not found on this server. Apache/2.4.7 (Ubuntu) Server at sampleurl.com Port 80

I hope someone can help me on this
I tried changing them to:

```<code>$config['uri_protocol'] = AUTO
$config['enable_query_strings'] = TRUE;
</code>```

and it's still not working.

答:
According to your code, you may have these 2 issues:

1- As per documentation you are required to make your controller filename first character Uppercase.

2- Try adding a question mark "?" in your .htaccess file's last rule. Also remove the "/" before "index.php" check the code below.

Current code:

```<code>RewriteRule ^(.*)$ /index.php/$1 [L]
</code>```

New code:

```<code>RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Body:
I'm using codeigniter on my wamp and everything is fine but when I upload it on live server the default_controller is working but the other controller are 404 not found or "The requested URL /Sample_controller was not found on this server".

Here is my sample controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Sample_controller extends CI_Controller {
        function __construct(){
            parent::__construct();
    }

    public function index(){
        print_r('Hello World');
    }
}

and here's my config.php:

$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
$config['allow_get_array'] = TRUE;

and this is my router.php:

$route['default_controller']    = 'login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

and my .htaccess:

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    Options +Indexes
    RewriteEngine On

    RewriteBase /folder
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{HTTP_HOST} !www.sampleurl.com$ [NC]
    RewriteCond %{REQUEST_URI} ^/$

    RewriteCond $1 !^(index\.php|assets|user_assets|tmp|robots\.txt)
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

if I tried this sampleurl.com it's working fine and will direct me to my default controller which is the login but if i tried this sampleurl.com/sample_controller or sampleurl.com/login it will lead me to 404 not found The requested URL /sample_controller was not found on this server. Apache/2.4.7 (Ubuntu) Server at sampleurl.com Port 80

I hope someone can help me on this
I tried changing them to:

$config['uri_protocol'] = AUTO
$config['enable_query_strings'] = TRUE;

and it's still not working.

Body:
According to your code, you may have these 2 issues:

1- As per documentation you are required to make your controller filename first character Uppercase.

2- Try adding a question mark "?" in your .htaccess file's last rule. Also remove the "/" before "index.php" check the code below.

Current code:

RewriteRule ^(.*)$ /index.php/$1 [L]

New code:

RewriteRule ^(.*)$ index.php?/$1 [L]


问:
How to reset Google Cloud Shell user persistent disk?
Ok, folks.  Pushing the limits (of my understanding), I've broken my Google Cloud Shell on Google Cloud Platform.  I can no longer open a shell session.

When I click the shell icon >_ on the tool bar, the shell opens on the lower half of the screen for a moment, stating it is provisioning the instance (if it has been over an hour), established a connection, and then poof, it closes.

I was able to time a screen capture just right to see the following:

```<code>Welcome to Cloud Shell! For help, visit https://cloud.google.com/cloud-shell/help.
-bash: /usr/bin/zsh: No such file or directory
</code>```

I am pretty sure this relates to a naive attempt to install zsh ON A DIFFERENT PROJECT.  My theory is that the 5Gb of persistent disk storage provided by Cloud Shell is per user, not per user per project.  Therefore, my home directory is borked and will no longer load because the OS modifications are not persisted, only user home directories, and my .bashrc now references non-existent files.

So my question is this:  How do I start over, or wipe out the existing persistent disk and settings to obtain a working Shell again?

答:
Just do sudo su - which will make you the root user.

Then just remove/uninstall anything you added/installed.  Ex: rm /home/your_user/.bashrc

If you are unable to login because you messed up your .bashrc or something, it will prompt you to signin as root and then you can remove things with the command above.

Body:
Ok, folks.  Pushing the limits (of my understanding), I've broken my Google Cloud Shell on Google Cloud Platform.  I can no longer open a shell session.

When I click the shell icon >_ on the tool bar, the shell opens on the lower half of the screen for a moment, stating it is provisioning the instance (if it has been over an hour), established a connection, and then poof, it closes.

I was able to time a screen capture just right to see the following:

Welcome to Cloud Shell! For help, visit https://cloud.google.com/cloud-shell/help.
-bash: /usr/bin/zsh: No such file or directory

I am pretty sure this relates to a naive attempt to install zsh ON A DIFFERENT PROJECT.  My theory is that the 5Gb of persistent disk storage provided by Cloud Shell is per user, not per user per project.  Therefore, my home directory is borked and will no longer load because the OS modifications are not persisted, only user home directories, and my .bashrc now references non-existent files.

So my question is this:  How do I start over, or wipe out the existing persistent disk and settings to obtain a working Shell again?


问:
Django import-export new values in foriegn key model
I'm using the django import-export library to data. It works well except I cannot get it to import objects which don't already exist in the foreign key.

If the objects (values in the csv) exist in the foreign key model- then it imports fine.

But if the objects/values don't exist in the foreign key model- it says "matching query does not exist" and will not import the data.

How can I tell it to add new object to the foreign key model if they don't exist in the foreign key?

Models.py snippet

```<code>class Store(models.Model):

    store_name = models.CharField(max_length=30)
    def __unicode__(self):
        return self.store_name
    #etc

class Product(models.Model):

    Store = models.ForeignKey(Store)
    Category = models.ForeignKey(Category)
    first_name = models.CharField(max_length=30)
    second_name = models.CharField(max_length=30)
...
</code>```

Admin.py snippet

```<code>admin.site.register(Category)
admin.site.register(Store)

class ProductResource(resources.ModelResource):

     store_name = fields.Field(column_name='store_name', attribute='Store',
                       widget=ForeignKeyWidget(Store, 'store_name'))

    def __unicode__(self):
        return self.store_name.name

    class Meta:
        model = Product
        fields = ('id', 'first_name', 'second_name','store_name')
        export_order = ('id', 'second_name', 'first_name')
        skip_unchanged = False
        report_skipped = False
        widgets = {
                'published': {'format': '%d.%m.%Y'},
                }

class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    list_display = ('first_name', 'second_name')

admin.site.register(Product, ProductAdmin)
</code>```

答:
Provided the ForeignKey of your model can be null :

```<code>MyForeignKeyName = Models.ForeignKey(<modelclass>,blank=True, null=True)
</code>```

You can add a before_import_row() method in your Resource class :

```<code>def before_import_row(self,row) :
    fieldname = 'MyForeignKeyName'
    if not( <modelclass>.objects.filter(pk=row[fieldname]).exists() ) :
        # print(row['id'],row[fieldname],'unknown key !') # console log
        row[fieldname ] = None # or something else.. *
</code>```

*.. compliant with your foreignkey configuration [ python None = SQL null ]

I'm a bit new to Django so maybe it's not the better way, but this solves my problem.

There's also something about db_constraint=False that can be added to ForeignKey's arguments (some info @stackoverflow and @django) but well, I did not find my way with it.

Body:
I'm using the django import-export library to data. It works well except I cannot get it to import objects which don't already exist in the foreign key.

If the objects (values in the csv) exist in the foreign key model- then it imports fine.

But if the objects/values don't exist in the foreign key model- it says "matching query does not exist" and will not import the data.

How can I tell it to add new object to the foreign key model if they don't exist in the foreign key?

Models.py snippet

class Store(models.Model):

    store_name = models.CharField(max_length=30)
    def __unicode__(self):
        return self.store_name
    #etc

class Product(models.Model):

    Store = models.ForeignKey(Store)
    Category = models.ForeignKey(Category)
    first_name = models.CharField(max_length=30)
    second_name = models.CharField(max_length=30)
...

Admin.py snippet

admin.site.register(Category)
admin.site.register(Store)

class ProductResource(resources.ModelResource):

     store_name = fields.Field(column_name='store_name', attribute='Store',
                       widget=ForeignKeyWidget(Store, 'store_name'))

    def __unicode__(self):
        return self.store_name.name

    class Meta:
        model = Product
        fields = ('id', 'first_name', 'second_name','store_name')
        export_order = ('id', 'second_name', 'first_name')
        skip_unchanged = False
        report_skipped = False
        widgets = {
                'published': {'format': '%d.%m.%Y'},
                }

class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    list_display = ('first_name', 'second_name')

admin.site.register(Product, ProductAdmin)

Body:
Provided the ForeignKey of your model can be null :

MyForeignKeyName = Models.ForeignKey(<modelclass>,blank=True, null=True)

You can add a before_import_row() method in your Resource class :

def before_import_row(self,row) :
    fieldname = 'MyForeignKeyName'
    if not( <modelclass>.objects.filter(pk=row[fieldname]).exists() ) :
        # print(row['id'],row[fieldname],'unknown key !') # console log
        row[fieldname ] = None # or something else.. *

*.. compliant with your foreignkey configuration [ python None = SQL null ]

I'm a bit new to Django so maybe it's not the better way, but this solves my problem.

There's also something about db_constraint=False that can be added to ForeignKey's arguments (some info @stackoverflow and @django) but well, I did not find my way with it.


问:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
I am getting this kind of error, how to fix it.</p>

```<code>Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'.
Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
</code>```

答:
I had this problem i just deleted every thing related to android in
c://user/your pc name /
and it worked </p>

Body:
I am getting this kind of error, how to fix it.

Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'.
Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.


问:
Transforming two functions into one R
Ok I would like to make my functions kri3 and Kmap into one function. Both functions work by them selves. The issue I am having is that when I combine the two kri3 will not save the values it creates in my global environment and pass them to Kmap. Because of this Kmap will not use the values unless I split the function into two. Why can I not make this into one function? I want to have just one function for all of this not two.

The function I want to make is one that will take a variable, latitude, longitude and how sharp the map is in the x and y directions. Then it will krige the given data and output two heat maps for prediction and variance onto a ggmap all in one go.

```<code>kri3 <- function(var, lat, lon, defx, defy){

  #making a data frame out of the given vectors
  spdf <- data.frame(var,lat,lon)

  #makeing spatial point data frame coords
  sp::coordinates(spdf) <- ~ lon + lat
  bbox <- sp::bbox(spdf)

  #variogram stuff
  lzn.vgm <- gstat::variogram(var ~ 1, spdf)

  lzn.fit1 <- gstat::fit.variogram(lzn.vgm, model = gstat::vgm(1, "Sph", 900, 1))

  lzn.fit = automap::autofitVariogram(var ~ 1,
                                      spdf,
                                      model = c("Sph"),
                                      kappa = c(0.05, seq(0.2, 2, 0.1), 5, 10),
                                      fix.values = c(NA, NA, NA),
                                      start_vals = c(NA,NA,NA),
                                      verbose = T)

  #making our grid
  cs <- c(defx, defy)
  bb <- sp::bbox(spdf)
  cc <- bb[,1] + (cs/2)
  cd <- ceiling(diff(t(bb))/cs)
  gold_grd <- sp::GridTopology(cellcentre.offset = cc, cellsize = cs, cells.dim = cd)
  gold_grd
  p4s <- sp::CRS(sp::proj4string(spdf))
  gold_sg <- sp::SpatialGrid(gold_grd, proj4string = p4s)
  summary(gold_sg)

  #kringing and auto kriging
  lzn.kriged <- as.data.frame(gstat::krige(var ~ 1, spdf, gold_sg , model=lzn.fit1))
  lzn.Akriged <- automap::autoKrige(var ~ 1, spdf, gold_sg)

  lzn.Akriged.pred <- lzn.Akriged$krige_output$var1.pred
  lzn.Akriged.var <- lzn.Akriged$krige_output$var1.var

  return(lzn.kriged)
  return(lzn.Akriged.var)
  return(lzn.Akriged.pred)

}

kriw <- kri3(new_river$E_coli, new_river$lat2, new_river$lon2, 0.005, 0.005)

Kmap <-  function(lat, lon, kriw){

  #making a dataframe for ggplot
  kriw <- as.data.frame(kriw)

  #making a maps
  bbox1 <- ggmap::make_bbox(lon, lat, f = 1.4)
  map <- ggmap::get_map(bbox1)

  #making a heat map
  M1 <- ggmap::ggmap(map) +
    ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                    y = lat, alpha = var1.pred), fill = "red")

  M2 <- ggmap::ggmap(map) +
    ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                    y = lat, alpha = var1.var), fill = "red")
  #Placing both heat maps together
  heat <- gridExtra::grid.arrange(M1,M2, ncol=2)

  return(heat)

}

Kmap(new_river$lat2, new_river$lon2, kriw)
</code>```

答:
r2evans was right.

instead of using return 3 times I needed to use it once.

old code:

```<code>  return(lzn.kriged)
  return(lzn.Akriged.var)
  return(lzn.Akriged.pred)
</code>```

new code:

```<code>kriw <- data.frame(lzn.kriged, lzn.Akriged.var, lzn.Akriged.pred)
 return(kriw)
</code>```

This easily let me move my variables and create one function.

Title: Transforming two functions into one R

Body:
Ok I would like to make my functions kri3 and Kmap into one function. Both functions work by them selves. The issue I am having is that when I combine the two kri3 will not save the values it creates in my global environment and pass them to Kmap. Because of this Kmap will not use the values unless I split the function into two. Why can I not make this into one function? I want to have just one function for all of this not two.

The function I want to make is one that will take a variable, latitude, longitude and how sharp the map is in the x and y directions. Then it will krige the given data and output two heat maps for prediction and variance onto a ggmap all in one go.

kri3 <- function(var, lat, lon, defx, defy){

  #making a data frame out of the given vectors
  spdf <- data.frame(var,lat,lon)

  #makeing spatial point data frame coords
  sp::coordinates(spdf) <- ~ lon + lat
  bbox <- sp::bbox(spdf)

  #variogram stuff
  lzn.vgm <- gstat::variogram(var ~ 1, spdf)

  lzn.fit1 <- gstat::fit.variogram(lzn.vgm, model = gstat::vgm(1, "Sph", 900, 1))

  lzn.fit = automap::autofitVariogram(var ~ 1,
                                      spdf,
                                      model = c("Sph"),
                                      kappa = c(0.05, seq(0.2, 2, 0.1), 5, 10),
                                      fix.values = c(NA, NA, NA),
                                      start_vals = c(NA,NA,NA),
                                      verbose = T)

  #making our grid
  cs <- c(defx, defy)
  bb <- sp::bbox(spdf)
  cc <- bb[,1] + (cs/2)
  cd <- ceiling(diff(t(bb))/cs)
  gold_grd <- sp::GridTopology(cellcentre.offset = cc, cellsize = cs, cells.dim = cd)
  gold_grd
  p4s <- sp::CRS(sp::proj4string(spdf))
  gold_sg <- sp::SpatialGrid(gold_grd, proj4string = p4s)
  summary(gold_sg)

  #kringing and auto kriging
  lzn.kriged <- as.data.frame(gstat::krige(var ~ 1, spdf, gold_sg , model=lzn.fit1))
  lzn.Akriged <- automap::autoKrige(var ~ 1, spdf, gold_sg)

  lzn.Akriged.pred <- lzn.Akriged$krige_output$var1.pred
  lzn.Akriged.var <- lzn.Akriged$krige_output$var1.var

  return(lzn.kriged)
  return(lzn.Akriged.var)
  return(lzn.Akriged.pred)

}

kriw <- kri3(new_river$E_coli, new_river$lat2, new_river$lon2, 0.005, 0.005)

Kmap <-  function(lat, lon, kriw){

  #making a dataframe for ggplot
  kriw <- as.data.frame(kriw)

  #making a maps
  bbox1 <- ggmap::make_bbox(lon, lat, f = 1.4)
  map <- ggmap::get_map(bbox1)

  #making a heat map
  M1 <- ggmap::ggmap(map) +
    ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                    y = lat, alpha = var1.pred), fill = "red")

  M2 <- ggmap::ggmap(map) +
    ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                    y = lat, alpha = var1.var), fill = "red")
  #Placing both heat maps together
  heat <- gridExtra::grid.arrange(M1,M2, ncol=2)

  return(heat)

}

Kmap(new_river$lat2, new_river$lon2, kriw)

Body:
r2evans was right.

instead of using return 3 times I needed to use it once.

old code:

  return(lzn.kriged)
  return(lzn.Akriged.var)
  return(lzn.Akriged.pred)

new code:

kriw <- data.frame(lzn.kriged, lzn.Akriged.var, lzn.Akriged.pred)
 return(kriw)

This easily let me move my variables and create one function.


问:
Error: Failed to lookup view "error" in views directory Node JS and Jquery Error
I can't figure out the solution to this problem, even after looking over previous posts.

I am getting the error below:

GET /public/stylesheets/nice-select.css 404 2.429 ms - 1594
      Error: Failed to lookup view "error" in views directory "/home/nmysore/PhpstormProjects/Makerspace/express_example/views"
          at EventEmitter.render (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/application.js:580:17)
          at ServerResponse.render (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/response.js:971:7)
          at /home/nmysore/PhpstormProjects/Makerspace/express_example/app.js:49:7
          at Layer.handle_error (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/layer.js:71:5)
          at trim_prefix (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:315:13)
          at /home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:284:7
          at Function.process_params (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:335:12)
          at next (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:275:10)
          at /home/nmysore/PhpstormProjects/Makerspace/express_example/app.js:38:3
          at Layer.handle [as handle_request] (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/layer.js:95:5)

I am trying to use some jQuery package to have nice animations when selecting elements, and using a node.js server.

http://hernansartorio.com/jQuery-nice-select/

My structure is currently:

app.js

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stylus = require('stylus');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

// unce(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

app.engine('html', require('ejs').renderFile);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
 });

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
</code>```

And inside my index.html:

```<code><!DOCTYPE html>
<html>
<script src="public/javascripts/jquery.js"></script>
<script src="public/javascripts/jquery.nice-select.js"></script>
<link rel = "stylesheet" href="public/stylesheets/nice-select.css">
<script>
$(document).ready(function() {
      $('select').niceSelect();
});
</script>
<body>
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    <select name='Major'>
        <option disabled selected>Select Major</option>
        <option value="1">All Majors</option>
        <option value="2">Computer Science</option>
        <option value="3">Structural Engineering</option>
        <option value="4">Cognitive Science</option>
        <option value="5">Bioengineering</option>
        <option value="6">Electrical Engineering</option>
        <option value="7">Etc</option>
        <option value="8">Etc</option>
    </select>
</body>
</html>
</code>```

I've tried a bunch of suggestions on previous threads, but the error is not going away.

答:
You're asking for the error.html view with this line:

res.render('error');

Yet it doesn't exist in the views folder. Add an error.html and it should render.

Body:
I can't figure out the solution to this problem, even after looking over previous posts.

I am getting the error below:

GET /public/stylesheets/nice-select.css 404 2.429 ms - 1594
      Error: Failed to lookup view "error" in views directory "/home/nmysore/PhpstormProjects/Makerspace/express_example/views"
          at EventEmitter.render (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/application.js:580:17)
          at ServerResponse.render (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/response.js:971:7)
          at /home/nmysore/PhpstormProjects/Makerspace/express_example/app.js:49:7
          at Layer.handle_error (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/layer.js:71:5)
          at trim_prefix (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:315:13)
          at /home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:284:7
          at Function.process_params (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:335:12)
          at next (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/index.js:275:10)
          at /home/nmysore/PhpstormProjects/Makerspace/express_example/app.js:38:3
          at Layer.handle [as handle_request] (/home/nmysore/PhpstormProjects/Makerspace/express_example/node_modules/express/lib/router/layer.js:95:5)

I am trying to use some jQuery package to have nice animations when selecting elements, and using a node.js server.

http://hernansartorio.com/jQuery-nice-select/

My structure is currently:

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stylus = require('stylus');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

// unce(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

app.engine('html', require('ejs').renderFile);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
 });

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

And inside my index.html:

<!DOCTYPE html>

<link rel = "stylesheet" href="public/stylesheets/nice-select.css">

My First Heading

My first paragraph.

    <select name='Major'>
        <option disabled selected>Select Major</option>
        <option value="1">All Majors</option>
        <option value="2">Computer Science</option>
        <option value="3">Structural Engineering</option>
        <option value="4">Cognitive Science</option>
        <option value="5">Bioengineering</option>
        <option value="6">Electrical Engineering</option>
        <option value="7">Etc</option>
        <option value="8">Etc</option>
    </select>

I've tried a bunch of suggestions on previous threads, but the error is not going away.


问:
Rolling file from Serilog not working in macOs
I'm trying to implement Serilog in a .Net Core library to have a good abstraction for this Third party and be able to use it on different project that are in my Solution.

So I configure Serilog like the example in their GitHub

```<code>    if(Log.Logger == null){
        Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .WriteTo.LiterateConsole()
        .WriteTo.RollingFile("logs/myUsefullLogs.txt")
        .CreateLogger();
    }
</code>```

And I log an information like this :

```<code>    Log.Information(message,ex,source);
    Log.CloseAndFlush();
</code>```

If I put a breakpoint all seems to work perfectly but when I search the file I'm not able to find it.

Somebody already face to this in macOS?

答:
Log.Logger will never have the value null, so your configuration code above will never run.

When logging is not configured, Log.Logger is assigned an instance of the (internal) SilentLogger class: https://github.com/serilog/serilog/blob/dev/src/Serilog/Log.cs#L43.

Body:
I'm trying to implement Serilog in a .Net Core library to have a good abstraction for this Third party and be able to use it on different project that are in my Solution.

So I configure Serilog like the example in their GitHub

    if(Log.Logger == null){
        Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .WriteTo.LiterateConsole()
        .WriteTo.RollingFile("logs/myUsefullLogs.txt")
        .CreateLogger();
    }

And I log an information like this :

    Log.Information(message,ex,source);
    Log.CloseAndFlush();

If I put a breakpoint all seems to work perfectly but when I search the file I'm not able to find it.

Somebody already face to this in macOS?


问:
CRM plugin not firing for emails sent from console application
I have a plugin written that is registered for the DeliverIncoming message on the email entity in CRM. The plugin fires normally when emails arrive into a queue.

I also have a console application that connects to the CRM service, checks the followupby attribute of cases and depending on the date sends out a reminder/overdue notification.

The problem is that these emails aren't causing the plugin to fire. The email activities are created in CRM and the emails are sent and delivered without any issue but the plugin doesn't fire. I also tried registering the plugin against the Create message of the email entity and that doesn't fire either.

The emails are sent using the SendEmailFromTemplateRequest as the request object being passed into the CrmService.Execute() method

The plugin fires for all other instances of emails being delivered. The emails sent from the console application are the only ones experiencing this issue. Does anybody know why this would occur?

Thanks,
Neil

答: Turns out the plugin was firing, but when run from the console application it was throwing an exception when trying to log to a file it didn't have permission to. I had a break point on the second line, the first line was the logging line. </p>


问:
Wikipedia links API returns links that aren't on the page
I'm experimenting with the python module wikipedia which is a wrapper for the wikipedia API.  In particular I'm looking at the links API, which as I understand should return a 'List of titles of Wikipedia page links on a page', i.e. all the references to other wikipedia pages within the text of the page I'm querying about.  When I look at the result for the article on Google, I get a list of links as expected (wikipedia titles in JSON format). The problem is that there seem to be links listed there that do not appear on the Google page.  I thought maybe it's including links to Google, but that doesn't work either, in particular, the third link returned in the JSON structure is to ADATA.  I don't see a link to ADATA anywhere on the Google page, nor a link to Google anywhere on the ADATA page.  Is this a bug or am I missing something obvious?

I believe this link is enough to reproduce the issue:

```<code>https://en.wikipedia.org/w/api.php?action=query&titles=Google&prop=links
</code>```

The result I see looks like this:

```<code>{
    "continue": {
        "plcontinue": "1092923|0|Aardvark_(search_engine)",
        "continue": "||"
    },
    "query": {
        "pages": {
            "1092923": {
                "pageid": 1092923,
                "ns": 0,
                "title": "Google",
                "links": [
                    {
                        "ns": 0,
                        "title": "111 Eighth Avenue"
                    },
                    {
                        "ns": 0,
                        "title": "2600: The Hacker Quarterly"
                    },
                    {
                        "ns": 0,
                        "title": "ADATA"
                    },
. . .
</code>```

In python you can reproduce like this:

```<code>import wikipedia
wikipedia.page('Google').links
</code>```

which produces output like this:

```<code>['111 Eighth Avenue',
 '2600: The Hacker Quarterly',
 'ADATA',
 'AI Challenge',
 'AKM Semiconductor, Inc.',
 'AOL',
 'API.AI',
</code>```

答:
There seem to be some bits of the page that are not visible by default when visiting the page.  In this example, the link appears when you click on the 'show' button for "Major information technology companies" at the bottom of the page.  I believe this should account for what I'm seeing.

Thanks to zwer in the comments for pointing out where to find the link.

Body:
I'm experimenting with the python module wikipedia which is a wrapper for the wikipedia API.  In particular I'm looking at the links API, which as I understand should return a 'List of titles of Wikipedia page links on a page', i.e. all the references to other wikipedia pages within the text of the page I'm querying about.  When I look at the result for the article on Google, I get a list of links as expected (wikipedia titles in JSON format). The problem is that there seem to be links listed there that do not appear on the Google page.  I thought maybe it's including links to Google, but that doesn't work either, in particular, the third link returned in the JSON structure is to ADATA.  I don't see a link to ADATA anywhere on the Google page, nor a link to Google anywhere on the ADATA page.  Is this a bug or am I missing something obvious?

I believe this link is enough to reproduce the issue:

https://en.wikipedia.org/w/api.php?action=query&titles=Google&prop=links

The result I see looks like this:

{
    "continue": {
        "plcontinue": "1092923|0|Aardvark_(search_engine)",
        "continue": "||"
    },
    "query": {
        "pages": {
            "1092923": {
                "pageid": 1092923,
                "ns": 0,
                "title": "Google",
                "links": [
                    {
                        "ns": 0,
                        "title": "111 Eighth Avenue"
                    },
                    {
                        "ns": 0,
                        "title": "2600: The Hacker Quarterly"
                    },
                    {
                        "ns": 0,
                        "title": "ADATA"
                    },
. . .

In python you can reproduce like this:

import wikipedia
wikipedia.page('Google').links

which produces output like this:

['111 Eighth Avenue',
 '2600: The Hacker Quarterly',
 'ADATA',
 'AI Challenge',
 'AKM Semiconductor, Inc.',
 'AOL',
 'API.AI',


问:
How to update a dependency with quicklisp?
I have updated quicklisp to the lates version

CL-USER> (ql:update-all-dists)

1 dist to check.

You already have the latest version of "quicklisp": 2017-06-30.

NIL

But this did not update the dependencies to the latest version, ex. Hunchentoot webserver is version 1.2.35, but I need 1.2.37 because of a bugfix.

/home/pio/quicklisp/dists/quicklisp/software/hunchentoot-1.2.35/hunchentoot.asd

How can I update the Hunchentoot to the latest release (https://github.com/edicl/hunchentoot/releases/tag/v1.2.37) with quicklisp?

答:
Ql:quickload will first ask ASDF for locally available systems, which happens in a defined order.

I usually put all Lisp libraries that I want to be found under ~/common-lisp/ which is a standard place ASDF looks into, so it just works.

If you have some other directories, you can make these directories known to ASDF.  You can for example use the file ~/.config/common-lisp/source-registry.conf:

```<code>(:source-registry
  (:tree (:home "repos"))
  :inherit-configuration)
</code>```

This will make ASDF aware of any .asd files under the ~/repos/ directory.

You can then use asdf:load-system or ql:quickload to load such systems (the latter will also resolve and download missing dependencies).

If quicklisp has already installed a system in a different version and ASDF happens to find that version first, you might need to ql:uninstall it beforehand.

Body:
Ql:quickload will first ask ASDF for locally available systems, which happens in a defined order.

I usually put all Lisp libraries that I want to be found under ~/common-lisp/ which is a standard place ASDF looks into, so it just works.

If you have some other directories, you can make these directories known to ASDF.  You can for example use the file ~/.config/common-lisp/source-registry.conf:

(:source-registry
  (:tree (:home "repos"))
  :inherit-configuration)

This will make ASDF aware of any .asd files under the ~/repos/ directory.

You can then use asdf:load-system or ql:quickload to load such systems (the latter will also resolve and download missing dependencies).

If quicklisp has already installed a system in a different version and ASDF happens to find that version first, you might need to ql:uninstall it beforehand.

ContentLicense: CC BY-SA 4.0


问:
How do I insert text to the 1st line of a file using sed?
Hi I'm trying to add text to the 1st line of a file using sed
so far iv'e tried

```<code>#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
</code>```

And this dosn't work
also tried

```<code>#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test
</code>```

this dosn't seem to work either
oddly when I try

```<code>#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test
</code>```

I get the 1st line of text to appear when i use cat test
but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

Can text be inserted into the 1st line of a newly created file using sed?

If yes whats the best way of inserting text after the 1st line of text?

答:
Suppose you have a file like this:

```<code>one
two
</code>```

Then to append to the first line:

```<code>$ sed '1 s_$_/etc/example/live/example.com/fullchain.pem;_' file
one/etc/example/live/example.com/fullchain.pem;
two
</code>```

To insert before the first line:

```<code>$ sed '1 i /etc/example/live/example.com/fullchain.pem;' file
/etc/example/live/example.com/fullchain.pem;
one
two
</code>```

Or, to append after the first line:

```<code>$ sed '1 a /etc/example/live/example.com/fullchain.pem;' file
one
/etc/example/live/example.com/fullchain.pem;
two
</code>```

Note the number 1 in those sed expressions - that's called the address in sed terminology. It tells you on which line the command that follows is to operate.

If your file doesn't contain the line you're addressing, the sed command won't get executed. That's why you can't insert/append on line 1, if your file is empty.

Instead of using stream editor, to append (to empty files), just use a shell redirection >>:

```<code>echo "content" >> file
</code>```

Body:
Hi I'm trying to add text to the 1st line of a file using sed
so far iv'e tried

#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test

And this dosn't work
also tried

#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test

this dosn't seem to work either
oddly when I try

#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test

I get the 1st line of text to appear when i use cat test
but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

Can text be inserted into the 1st line of a newly created file using sed?

If yes whats the best way of inserting text after the 1st line of text?

Body:
Suppose you have a file like this:

one
two

Then to append to the first line:

$ sed '1 s_$_/etc/example/live/example.com/fullchain.pem;_' file
one/etc/example/live/example.com/fullchain.pem;
two

To insert before the first line:

$ sed '1 i /etc/example/live/example.com/fullchain.pem;' file
/etc/example/live/example.com/fullchain.pem;
one
two

Or, to append after the first line:

$ sed '1 a /etc/example/live/example.com/fullchain.pem;' file
one
/etc/example/live/example.com/fullchain.pem;
two

Note the number 1 in those sed expressions - that's called the address in sed terminology. It tells you on which line the command that follows is to operate.

If your file doesn't contain the line you're addressing, the sed command won't get executed. That's why you can't insert/append on line 1, if your file is empty.

Instead of using stream editor, to append (to empty files), just use a shell redirection >>:

echo "content" >> file


问:
My background Image won't show up on the div
I am trying to create a div and add a background image to it in jQuery. For some reason, I cannot do it. If I instead make my background color white, I get a white background. Here is my code:

```<code>function appendToDom(poster) {
        var aPoster = $('<div>');
        aPoster.css({
                display: 'inline block',
                float: 'left',
                margin: '10px',
                marginLeft: '37px',
                marginTop: '20px',
                width: '200px',
                height: '300px',
                fontSize: '36px',
                color: 'black',
                //backgroundColor: 'white',
                backgroundSize: '200px 300px',
                backgroundImage: './../images/question.png'
            })
            /*
                    $(aPoster).attr("css","background-image: url(~/desktop/MyMovies/public/js/images/question.jpeg)");
                    $(aPoster).attr("css","background-size: 200px 300px");*/
        $(main).append(aPoster);
    }
</code>```

Thanks for all the advice! So I took the suggestions given to me, but it still doesn't work for me.Here is a screenshot of what I have:

my improved code

NVM I got it! Thanks!

答:
Try making your method look like this...

```<code> aPoster.css({
            'display': 'inline block',
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-color': 'white',
            'background-size': '200px 300px',
            'background-image': 'url("./../images/question.png")'
</code>```

Try something like this and see what you get. You also notice that I got rid of the values with pixel. Because JavaScript's default values for CSS properties like that have their units in pixels. Just try it and see if it works. Hope this helped. Oh and one last thing, if you used an external script, don't forget to use the URL and make it relative to the script itself and not your main page...but in your case, the styles would be added inline to the div element so you should probably make it relative to your main page, the page where the div would be created...

Body:
I am trying to create a div and add a background image to it in jQuery. For some reason, I cannot do it. If I instead make my background color white, I get a white background. Here is my code:

function appendToDom(poster) {
        var aPoster = $('
');
        aPoster.css({
                display: 'inline block',
                float: 'left',
                margin: '10px',
                marginLeft: '37px',
                marginTop: '20px',
                width: '200px',
                height: '300px',
                fontSize: '36px',
                color: 'black',
                //backgroundColor: 'white',
                backgroundSize: '200px 300px',
                backgroundImage: './../images/question.png'
            })
            /*
                    $(aPoster).attr("css","background-image: url(~/desktop/MyMovies/public/js/images/question.jpeg)");
                    $(aPoster).attr("css","background-size: 200px 300px");*/
        $(main).append(aPoster);
    }

Thanks for all the advice! So I took the suggestions given to me, but it still doesn't work for me.Here is a screenshot of what I have:

my improved code

NVM I got it! Thanks!

Body:
Try making your method look like this...

 aPoster.css({
            'display': 'inline block',
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-color': 'white',
            'background-size': '200px 300px',
            'background-image': 'url("./../images/question.png")'

Try something like this and see what you get. You also notice that I got rid of the values with pixel. Because JavaScript's default values for CSS properties like that have their units in pixels. Just try it and see if it works. Hope this helped. Oh and one last thing, if you used an external script, don't forget to use the URL and make it relative to the script itself and not your main page...but in your case, the styles would be added inline to the div element so you should probably make it relative to your main page, the page where the div would be created...


问:
I am not able to create two notifications with different time even using two classes using broadcast receivers
This is the main class where I am trying to call both methods for creating notifications

shownotificationAtNight(hour,min),
shownotificationAtMorning(hour,min)

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shownotificationAtNight(22,21);
        shownotificationAtMorning(10,22);

    }

    private void shownotificationAtNight(int hour,int min) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,min);

        if(calendar.getTime().compareTo(new Date()) < 0) {calendar.add(Calendar.DATE, 1);}

        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    private void shownotificationAtMorning(int hour,int min) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,min);

        if(calendar.getTime().compareTo(new Date()) < 0) {calendar.add(Calendar.DATE, 1);}

        Intent intent = new Intent(MainActivity.this, MorningAlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}
</code>```

Then the receiver class are as follow with MID creating random number for different notifications

```<code>public class MorningAlarmReceiver extends BroadcastReceiver
{
        int MID  = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
        @Override
        public void onReceive(Context context, Intent intent)
            {
             long when = System.currentTimeMillis();
             NotificationManager notificationManager = (NotificationManager) context
                                                       .getSystemService(Context.NOTIFICATION_SERVICE);

             Intent notificationIntent = new Intent(context, ToTask.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

             PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

             Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

              NotificationCompat.Builder mNotifyBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(
                context).setSmallIcon(meg)
                .setContentTitle("Todays Alarm")
                .setContentText("Get done and add new tasks").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
              notificationManager.notify(MID, mNotifyBuilder.build());
              MID++;
        }
}
</code>```

The other class receiver

```<code>class AlarmReceiver extends BroadcastReceiver {
    int MID  = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
    @Override
    public void onReceive(Context context, Intent intent) {
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, ToTask.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(
                context).setSmallIcon(meg)
                .setContentTitle("Tommorow Plan")
                .setContentText("Events To be Performed").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
        notificationManager.notify(MID, mNotifyBuilder.build());
        MID++;
    }
}
</code>```

答:
Did you edit your Manifest accordingly? </p>

```<code><receiver android:name=".MyBroadcastReceiver"></receiver>
</code>```

Body:
This is the main class where I am trying to call both methods for creating notifications

shownotificationAtNight(hour,min),
shownotificationAtMorning(hour,min)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shownotificationAtNight(22,21);
        shownotificationAtMorning(10,22);

    }

    private void shownotificationAtNight(int hour,int min) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,min);

        if(calendar.getTime().compareTo(new Date()) < 0) {calendar.add(Calendar.DATE, 1);}

        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    private void shownotificationAtMorning(int hour,int min) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,min);

        if(calendar.getTime().compareTo(new Date()) < 0) {calendar.add(Calendar.DATE, 1);}

        Intent intent = new Intent(MainActivity.this, MorningAlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}

Then the receiver class are as follow with MID creating random number for different notifications

public class MorningAlarmReceiver extends BroadcastReceiver
{
        int MID  = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
        @Override
        public void onReceive(Context context, Intent intent)
            {
             long when = System.currentTimeMillis();
             NotificationManager notificationManager = (NotificationManager) context
                                                       .getSystemService(Context.NOTIFICATION_SERVICE);

             Intent notificationIntent = new Intent(context, ToTask.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

             PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

             Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

              NotificationCompat.Builder mNotifyBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(
                context).setSmallIcon(meg)
                .setContentTitle("Todays Alarm")
                .setContentText("Get done and add new tasks").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
              notificationManager.notify(MID, mNotifyBuilder.build());
              MID++;
        }
}

The other class receiver

class AlarmReceiver extends BroadcastReceiver {
    int MID  = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
    @Override
    public void onReceive(Context context, Intent intent) {
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, ToTask.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(
                context).setSmallIcon(meg)
                .setContentTitle("Tommorow Plan")
                .setContentText("Events To be Performed").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
        notificationManager.notify(MID, mNotifyBuilder.build());
        MID++;
    }
}

Body:
Did you edit your Manifest accordingly?

<receiver android:name=".MyBroadcastReceiver"></receiver>


问:
I can not send consecutive data from the serial port
I want to send consecutive data from the serial port. But serial port is not taking the second data after the first data is sent. If I stop and restart it, it works fine. This is my code:

String inputString="";
boolean stringComplete=false;

void serialEvent() {
  while(Serial.available()) {
    char inChar=(char) Serial.read();
    inputString+=inChar;
    if(inChar=='\n') {
      stringComplete=true;
    }
  }
}

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  serialEvent();
  if(stringComplete) {
    Serial.println(inputString);
    inputString="";
    stringComplete=false;
  }
  if(inputString=="HELLO") {
    digitalWrite(12, HIGH);
    serialEvent();
  } else if(inputString=="WORD") {
    digitalWrite(13, HIGH);
    serialEvent();
  }
}
```

For circuits and simulation:
https://tinkercad.com/things/6fTYYBc3w0e

答:
You're comparing strings while the inputString is set to an empty string before it can be used.
Put the string compares inside the if(stringInput) block. Also, you'll need to include the newline character in the comparison. </p>

```<code>void loop()
{
   serialEvent();

   if(stringComplete)
   {
        Serial.println(inputString);
        if(inputString=="HELLO\n")
        {
           digitalWrite(12,HIGH);
           serialEvent();
        }
        else if(inputString=="WORD\n")
        {
           digitalWrite(13,HIGH);
           serialEvent();
        }

        inputString="";
        stringComplete=false;
   }
}
</code>```

Body:
I want to send consecutive data from the serial port. But serial port is not taking the second data after the first data is sent. If I stop and restart it, it works fine. This is my code:

String inputString="";
boolean stringComplete=false;

void serialEvent() {
  while(Serial.available()) {
    char inChar=(char) Serial.read();
    inputString+=inChar;
    if(inChar=='\n') {
      stringComplete=true;
    }
  }
}

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  serialEvent();
  if(stringComplete) {
    Serial.println(inputString);
    inputString="";
    stringComplete=false;
  }
  if(inputString=="HELLO") {
    digitalWrite(12, HIGH);
    serialEvent();
  } else if(inputString=="WORD") {
    digitalWrite(13, HIGH);
    serialEvent();
  }
}

For circuits and simulation:
https://tinkercad.com/things/6fTYYBc3w0e

Body:
You're comparing strings while the inputString is set to an empty string before it can be used.
Put the string compares inside the if(stringInput) block. Also, you'll need to include the newline character in the comparison.

void loop()
{
   serialEvent();

   if(stringComplete)
   {
        Serial.println(inputString);
        if(inputString=="HELLO\n")
        {
           digitalWrite(12,HIGH);
           serialEvent();
        }
        else if(inputString=="WORD\n")
        {
           digitalWrite(13,HIGH);
           serialEvent();
        }

        inputString="";
        stringComplete=false;
   }
}