问:
Is 'bitmaprenderer' not a valid value for off-screen canvas rendering context in Chrome?
While drawing bitmap image onto off-screen canvas, Chrome console threw an error on me:

Failed to execute 'getContext' on 'OffscreenCanvas': The provided value 'bitmaprenderer' is not a valid enum value of type OffscreenRenderingContextType.

The problem occurs in both worker and window contexts:

var img = new Image(63, 177);
img.src = "https://cdn.sstatic.net/Img/unified/sprites.svg";
img.onload = _ => {
 createImageBitmap(img).then(bitmap => {
  var canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  canvas.getContext('bitmaprenderer');
 }).catch(e => console.error(e.message));
};```
</div>
</div>
</p>

<p>I can get this canvas context type in window context while using (on-screen) canvas interface as so:</p>

```document.createElement('canvas').getContext('bitmaprenderer');
```

The canvas context is needed in worker, so I can't use (on-screen) canvas interface, there is no document access after all.

While I can just get two-dimensional rendering context of bitmap image by using '2d' identifier in getContext method, it would be OffscreenCanvasRenderingContext2D and not ImageBitmapRenderingContext. I don't know the difference in latency for both interfaces, but as far as I understand, bitmap can be transferred onto canvas immediately, while 2d context should be drawn.

My Chrome version is 74.0.3729.169, and linked article browser compatibility table stipulates, that bitmap rendering context interface is available from 66 version.

Am I doing something wrong, or is bitmaprenderer not supported as a valid value for off-screen canvas rendering context as of now? How can I access bitmap rendering context for off-screen canvas in Chrome? Thanks in advance.

答:
Yes, at the time this question was asked ImageBitmapRenderingContext was still not available from an OffscreenCanvas, it now is but Chrome has a bug which prevents it from rendering to a placeholder canvas.

Note that if you wanted to use this bitmap-renderer for something like being able to draw it to another context, then you could directly pass the ImageBitmap to either 2D drawImage or webgl texImage2d.

Also note that in your case, since you are in the main thread and not in a Worker, you absolutely don't need an OffscreenCanvas and can just do

var img = new Image();
img.crossOrigin = 'anonymous';
img.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Fiore_con_petali_arancioni_SVG.svg";
img.onload = _ => {
  createImageBitmap(img)
    .then(bitmap => {
      const canvas = Object.assign(document.createElement('canvas'), {
        width: bitmap.width,
        height: bitmap.height
      });
      const ctx = canvas.getContext('bitmaprenderer');
      ctx.transferFromImageBitmap(bitmap);
      return new Promise((res, rej) => {
        canvas.toBlob(blob => {
          if (!blob) rej('error');
          res(blob);
        });
      });
    })
    .then(blob => {
      console.log(blob);
      result.src = URL.createObjectURL(blob);
    })
    .catch(e => console.error(e.message));
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>PNG: <img id="result"></code>```

Body:
While drawing bitmap image onto off-screen canvas, Chrome console threw an error on me:

Failed to execute 'getContext' on 'OffscreenCanvas': The provided value 'bitmaprenderer' is not a valid enum value of type OffscreenRenderingContextType.

The problem occurs in both worker and window contexts:

var img = new Image(63, 177);
img.src = "https://cdn.sstatic.net/Img/unified/sprites.svg";
img.onload = _ => {
 createImageBitmap(img).then(bitmap => {
  var canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  canvas.getContext('bitmaprenderer');
 }).catch(e => console.error(e.message));
};

I can get this canvas context type in window context while using (on-screen) canvas interface as so:

document.createElement('canvas').getContext('bitmaprenderer');

The canvas context is needed in worker, so I can't use (on-screen) canvas interface, there is no document access after all.

While I can just get two-dimensional rendering context of bitmap image by using '2d' identifier in getContext method, it would be OffscreenCanvasRenderingContext2D and not ImageBitmapRenderingContext. I don't know the difference in latency for both interfaces, but as far as I understand, bitmap can be transferred onto canvas immediately, while 2d context should be drawn.

My Chrome version is 74.0.3729.169, and linked article browser compatibility table stipulates, that bitmap rendering context interface is available from 66 version.

Am I doing something wrong, or is bitmaprenderer not supported as a valid value for off-screen canvas rendering context as of now? How can I access bitmap rendering context for off-screen canvas in Chrome? Thanks in advance.

Body:
Yes, at the time this question was asked ImageBitmapRenderingContext was still not available from an OffscreenCanvas, it now is but Chrome has a bug which prevents it from rendering to a placeholder canvas.

Note that if you wanted to use this bitmap-renderer for something like being able to draw it to another context, then you could directly pass the ImageBitmap to either 2D drawImage or webgl texImage2d.

Also note that in your case, since you are in the main thread and not in a Worker, you absolutely don't need an OffscreenCanvas and can just do

var img = new Image();
img.crossOrigin = 'anonymous';
img.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Fiore_con_petali_arancioni_SVG.svg";
img.onload = _ => {
  createImageBitmap(img)
    .then(bitmap => {
      const canvas = Object.assign(document.createElement('canvas'), {
        width: bitmap.width,
        height: bitmap.height
      });
      const ctx = canvas.getContext('bitmaprenderer');
      ctx.transferFromImageBitmap(bitmap);
      return new Promise((res, rej) => {
        canvas.toBlob(blob => {
          if (!blob) rej('error');
          res(blob);
        });
      });
    })
    .then(blob => {
      console.log(blob);
      result.src = URL.createObjectURL(blob);
    })
    .catch(e => console.error(e.message));
};

PNG: <img id="result">


来源: stackexchange

问:
How to get package name from anywhere?
I am aware of the availability of Context.getApplicationContext() and View.getContext(), through which I can actually call Context.getPackageName() to retrieve the package name of an application.

They work if I call from a method to which a View or an Activity object is available, but if I want to find the package name from a totally independent class with no View or Activity, is there a way to do that (directly or indirectly)?

答:
Just import Android.app，then you can use:

Application.getProcessName()

Get the current Application Process Name without context, view, or activity.

ContentLicense: CC BY-SA 3.0

Title: How to get package name from anywhere?

Body:
Just import Android.app，then you can use:
<br/>Application.getProcessName()<br/>

Get the current Application Process Name without context, view, or activity.

ContentLicense: CC BY-SA 4.0


问:
What is the opposite of a decoupled web app?
If a decoupled app is one where you have a front end that sends requests to a backend then what is the opposite of that? What is a coupled web app? Can you store javascript on the server for frontend functionality?</p>

答:
I think they are called Muli Page Application. It's a classic web application where for each request the server does computation and returns a new Web page.

The new architecture becoming widely spread and that you are referring to is Single Page Application.

SPAs present the content in an easy, elegant and effective way as it loads all the content on just one single page rather than navigating the user to different pages. SPAs are faster than traditional web applications because they execute the logic in the web browser itself rather than on the server.

In both type of applications, client-side javascript is stored on the server and sent to the client / browser when the latter requests a web page. The amount of javascript with SPAs is obviously greater than MPAs as the logic is pushed to the client side.


问:
While trying to use the "fill_between" the following error is given" Input passed into argument "'y2'"is not 1-dimensional."
I am going through the Python Crash Course text and am receiving the error "Input passed into argument "'y2'"is not 1-dimensional" when attempting to use the fill_between portion of matplotlib. I am not sure why.

I have tried this in PyCharm and Anaconda, but receive the error in both IDE's. I'm fairly new to programming and so far have not ran into any issues when following the steps provided in the text, until now.
In both instances I am using Python 3.7 and Matplotlib 3.0.1

As a side note, I'm also not sure why all the months are not showing on the x-axis, but that is a separate issue.

```<code>    # Create a program where you import weather data from a csv file

# import the csv file, matplotlib(for visualizing), and datetime
import csv
from matplotlib import pyplot as plt
from datetime import datetime

# Create a variable that states the name of the file
filename = 'sitka_weather_2014.csv'
with open(filename) as file:
    # passes the file as an argument to create a reader object
    reader = csv.reader(file)
    # keeps reading until there are no more rows
    header_row = next(reader)

    # Get high temperatures and their dates from the file
    dates, highs, lows = [],[],[]
    for row in reader:
        current_date = datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(current_date)
        high = int(row[1])
        highs.append(high)
        low = int(row[3])
        lows.append([low])

# Plot Data
fig = plt.figure(dpi=250, figsize=(10,6))
plt.plot(dates, highs, c='red',alpha=0.5)
plt.plot(dates,lows, c='blue', alpha=0.5)
plt.fill_between(dates,highs,lows, facecolor='blue',alpha=0.1)
# Format Plot
plt.title("Monthly High Temperatures-2014", fontsize=24)
plt.xlabel('',fontsize=10)
fig.autofmt_xdate()
plt.ylabel('Temperature (F)',fontsize=16)
plt.tick_params(axis ='both', which='major',labelsize=16)
plt.show()
</code>```

I expect the shade to show between the high and the low lines. However only the high and low line graphs show in Anaconda, and the program errors will not show the graph in PyCharm.

答:
The problem seems to be the lows list which is multi dimensional because you are appending each element as a list using [low]. Try replacing

```<code>lows.append([low])
</code>```

by

```<code>lows.append(low)
</code>```

Body:
I am going through the Python Crash Course text and am receiving the error "Input passed into argument "'y2'"is not 1-dimensional" when attempting to use the fill_between portion of matplotlib. I am not sure why.

I have tried this in PyCharm and Anaconda, but receive the error in both IDE's. I'm fairly new to programming and so far have not ran into any issues when following the steps provided in the text, until now.
In both instances I am using Python 3.7 and Matplotlib 3.0.1

As a side note, I'm also not sure why all the months are not showing on the x-axis, but that is a separate issue.

    # Create a program where you import weather data from a csv file

# import the csv file, matplotlib(for visualizing), and datetime
import csv
from matplotlib import pyplot as plt
from datetime import datetime

# Create a variable that states the name of the file
filename = 'sitka_weather_2014.csv'
with open(filename) as file:
    # passes the file as an argument to create a reader object
    reader = csv.reader(file)
    # keeps reading until there are no more rows
    header_row = next(reader)

    # Get high temperatures and their dates from the file
    dates, highs, lows = [],[],[]
    for row in reader:
        current_date = datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(current_date)
        high = int(row[1])
        highs.append(high)
        low = int(row[3])
        lows.append([low])

# Plot Data
fig = plt.figure(dpi=250, figsize=(10,6))
plt.plot(dates, highs, c='red',alpha=0.5)
plt.plot(dates,lows, c='blue', alpha=0.5)
plt.fill_between(dates,highs,lows, facecolor='blue',alpha=0.1)
# Format Plot
plt.title("Monthly High Temperatures-2014", fontsize=24)
plt.xlabel('',fontsize=10)
fig.autofmt_xdate()
plt.ylabel('Temperature (F)',fontsize=16)
plt.tick_params(axis ='both', which='major',labelsize=16)
plt.show()

I expect the shade to show between the high and the low lines. However only the high and low line graphs show in Anaconda, and the program errors will not show the graph in PyCharm.

Body:
The problem seems to be the lows list which is multi dimensional because you are appending each element as a list using [low]. Try replacing

lows.append([low])

by

lows.append(low)


问:
React – the right way to pass form element state to sibling/parent elements?

Suppose I have a React class P, which renders two child classes, C1 and C2.

C1 contains an input field. I'll refer to this input field as Foo.

My goal is to let C2 react to changes in Foo.

I've come up with two solutions, but neither of them feels quite right.

First solution:

Assign P a state, state.input.

Create an onChange function in P, which takes in an event and sets state.input.

Pass this onChange to C1 as a props, and let C1 bind this.props.onChange to the onChange of Foo.

This works. Whenever the value of Foo changes, it triggers a setState in P, so P will have the input to pass to C2.

But it doesn't feel quite right for the same reason: I'm setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.

Is this how I'm supposed to do it, or is there a more React-natural solution?

Second solution:

Just put Foo in P.

But is this a design principle I should follow when I structure my app—putting all form elements in the render of the highest-level class?

Like in my example, if I have a large rendering of C1, I really don't want to put the whole render of C1 to render of P just because C1 has a form element.

How should I do it?

答:
Five years later with introduction of React Hooks there is now much more elegant way of doing it with use useContext hook.

You define context in a global scope, export variables, objects and functions in the parent component and then wrap children in the App in a context provided and import whatever you need in child components. Below is a proof of concept.

```<code>import React, { useState, useContext } from "react";
import ReactDOM from "react-dom";
import styles from "./styles.css";

// Create context container in a global scope so it can be visible by every component
const ContextContainer = React.createContext(null);

const initialAppState = {
  selected: "Nothing"
};

function App() {
  // The app has a state variable and update handler
  const [appState, updateAppState] = useState(initialAppState);

  return (
    <div>
      <h1>Passing state between components</h1>

      {/*
          This is a context provider. We wrap in it any children that might want to access
          App's variables.
          In 'value' you can pass as many objects, functions as you want.
           We wanna share appState and its handler with child components,
       */}
      <ContextContainer.Provider value={{ appState, updateAppState }}>
        {/* Here we load some child components */}
        <Book title="GoT" price="10" />
        <DebugNotice />
      </ContextContainer.Provider>
    </div>
  );
}

// Child component Book
function Book(props) {
  // Inside the child component you can import whatever the context provider allows.
  // Earlier we passed value={{ appState, updateAppState }}
  // In this child we need the appState and the update handler
  const { appState, updateAppState } = useContext(ContextContainer);

  function handleCommentChange(e) {
    //Here on button click we call updateAppState as we would normally do in the App
    // It adds/updates comment property with input value to the appState
    updateAppState({ ...appState, comment: e.target.value });
  }

  return (
    <div className="book">
      <h2>{props.title}</h2>
      <p>${props.price}</p>
      <input
        type="text"
        //Controlled Component. Value is reverse vound the value of the variable in state
        value={appState.comment}
        onChange={handleCommentChange}
      />
      <br />
      <button
        type="button"
        // Here on button click we call updateAppState as we would normally do in the app
        onClick={() => updateAppState({ ...appState, selected: props.title })}
      >
        Select This Book
      </button>
    </div>
  );
}

// Just another child component
function DebugNotice() {
  // Inside the child component you can import whatever the context provider allows.
  // Earlier we passed value={{ appState, updateAppState }}
  // but in this child we only need the appState to display its value
  const { appState } = useContext(ContextContainer);

  /* Here we pretty print the current state of the appState  */
  return (
    <div className="state">
      <h2>appState</h2>
      ```{JSON.stringify(appState, null, 2)}```
    </div>
  );
}

const rootElement = document.body;
ReactDOM.render(<App />, rootElement);
</code>```

You can run this example in the Code Sandbox editor.

Body:
Five years later with introduction of React Hooks there is now much more elegant way of doing it with use useContext hook.

You define context in a global scope, export variables, objects and functions in the parent component and then wrap children in the App in a context provided and import whatever you need in child components. Below is a proof of concept.

import React, { useState, useContext } from "react";
import ReactDOM from "react-dom";
import styles from "./styles.css";

// Create context container in a global scope so it can be visible by every component
const ContextContainer = React.createContext(null);

const initialAppState = {
  selected: "Nothing"
};

function App() {
  // The app has a state variable and update handler
  const [appState, updateAppState] = useState(initialAppState);

  return (
    <div>
      <h1>Passing state between components</h1>

      {/*
          This is a context provider. We wrap in it any children that might want to access
          App's variables.
          In 'value' you can pass as many objects, functions as you want.
           We wanna share appState and its handler with child components,
       */}
      <ContextContainer.Provider value={{ appState, updateAppState }}>
        {/* Here we load some child components */}
        <Book title="GoT" price="10" />
        <DebugNotice />
      </ContextContainer.Provider>
    </div>
  );
}

// Child component Book
function Book(props) {
  // Inside the child component you can import whatever the context provider allows.
  // Earlier we passed value={{ appState, updateAppState }}
  // In this child we need the appState and the update handler
  const { appState, updateAppState } = useContext(ContextContainer);

  function handleCommentChange(e) {
    //Here on button click we call updateAppState as we would normally do in the App
    // It adds/updates comment property with input value to the appState
    updateAppState({ ...appState, comment: e.target.value });
  }

  return (
    <div className="book">
      <h2>{props.title}</h2>
      <p>${props.price}</p>
      <input
        type="text"
        //Controlled Component. Value is reverse vound the value of the variable in state
        value={appState.comment}
        onChange={handleCommentChange}
      />
      <br />
      <button
        type="button"
        // Here on button click we call updateAppState as we would normally do in the app
        onClick={() => updateAppState({ ...appState, selected: props.title })}
      >
        Select This Book
      </button>
    </div>
  );
}

// Just another child component
function DebugNotice() {
  // Inside the child component you can import whatever the context provider allows.
  // Earlier we passed value={{ appState, updateAppState }}
  // but in this child we only need the appState to display its value
  const { appState } = useContext(ContextContainer);

  /* Here we pretty print the current state of the appState  */
  return (
    <div className="state">
      <h2>appState</h2>
      <pre>{JSON.stringify(appState, null, 2)}</pre>
    </div>
  );
}

const rootElement = document.body;
ReactDOM.render(<App />, rootElement);

You can run this example in the Code Sandbox editor.


问:
How to pass data continuously between two independent class in react js?
So i have a search field sitting in my header class and i want to pass the search value to the content which is sitting in another class so can anyone tell how to do that?</p>

答:
This is the purpose of redux and having a global state. You can check out a starter react redux project I built for more details. But basically you will need to dispatch actions which will update the global state from one class and then is accessible by all other components in your app.

https://github.com/iqbal125/modern-react-app-sample


问:
ASP.NET MVC Controller with multiple repositories?
I have a View where I am searching my db for an object(i.e. Books)..

My controller for this view depends on a BooksRepository that implements a search method.

Everything works fine. I also have the option to do an advanced search which presents a larger form in a Modal popup. This form has many fields including a Dropdown box to select an 'Author' to search by.

I would like to pass a list of authors in my viewmodel so in my conroller I instantiate an instance of my view model, I need to call a repository method to bring back the list of authors's...

My thinking is that this GetAuthors() method should be in an AuthorRepository...

Is it bad practice to inject multiple repo's into a controller?  or should I have an Author controller that gets injected with the author repo...and call a method in the Author controller from my BookSearch controller?

答:
I don't think it's a bad idea to inject the two repositories you need into the controller. Actually it sounds like a good practice.

But if you feel things are going out of hands, you might want to create an Application Service that would orchestrate a function in which you could inject several repositories. That would also be a way to move logic away from the controller.

But in this case, I think you are doing it right.

Read this book: http://www.infoq.com/minibooks/domain-driven-design-quickly


问:
Converting a Date to Datetime gives error in sql
I am storing a date in a varchar(50) column with values like thie:

```<code>1/01/2018
</code>```

I want to convert these to a Datetime value eg: 2018-01-22 00:00:00.0000000

My SQL is like;

```<code>select
  [Site],
  CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
from tableA;
</code>```

But I am getting;

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

I tried like this also but same error;

```<code>CONVERT(datetime, [InvDay]) as  Date,
</code>```

How can I make this work?

答:
I think you want to use set dateformat dmy. Here is an example:

```<code>declare @d varchar(15)
set @d='13/1/2018'
set dateformat dmy
select convert(datetime,@d)
</code>```

Body:
I am storing a date in a varchar(50) column with values like thie:

1/01/2018

I want to convert these to a Datetime value eg: 2018-01-22 00:00:00.0000000

My SQL is like;

select
  [Site],
  CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
from tableA;

But I am getting;

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

I tried like this also but same error;

CONVERT(datetime, [InvDay]) as  Date,

How can I make this work?

Body:
I think you want to use set dateformat dmy. Here is an example:

declare @d varchar(15)
set @d='13/1/2018'
set dateformat dmy
select convert(datetime,@d)


问:
Why Tkinter doesn't bind a function to an event correctly?
I'm making a simple program in Python 3 by using Tkinter. We start with a black canvas in a full-screen tkinter window and I want to show a blue circle in the middle of the canvas when I press the space bar on my keyboard.

I tried this code:

```<code>from tkinter import *

class TheBlueCircle:
    def __init__(self, master):
        self.master = master
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        self.master.geometry(str(self.ws)+'x'+str(self.ws)+'+0+0')
        self.canvas = Canvas(master, bg = 'black')
        self.canvas.pack(fill = BOTH, expand = True)
        self.canvas.bind('<KeyPress-space>', self.drawCircle)

    def drawCircle(self):
        r = min(self.ws, self.hs)/3
        coord = (self.ws/2-r, self.hs/2-r, self.ws/2+r, self.hs/2+r)
        self.canvas.create_oval(coord, fill = 'blue')

root = Tk()
TheBlueCircle(root)
root.mainloop()
</code>```

But it doesn't work. No matter how many times I press the space bar. It doesn't get to apply the drawCircle function.

What is wrong?

答:
There are some changes needed in your code. First you need to take an event as arg for your drawCircle method. Secondly, the current focus is not set to the canvas object.

To have your method correctly executed upon tabbing space, either first press tab when you launch your GUI, or force a focus change in your code:

```<code>class TheBlueCircle:
    def __init__(self, master):
        ...
        self.canvas.bind('<space>', self.drawCircle)
        self.canvas.focus_set()

    def drawCircle(self,event=None):
        ...
</code>```

Body:
I'm making a simple program in Python 3 by using Tkinter. We start with a black canvas in a full-screen tkinter window and I want to show a blue circle in the middle of the canvas when I press the space bar on my keyboard.

I tried this code:

from tkinter import *

class TheBlueCircle:
    def __init__(self, master):
        self.master = master
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        self.master.geometry(str(self.ws)+'x'+str(self.ws)+'+0+0')
        self.canvas = Canvas(master, bg = 'black')
        self.canvas.pack(fill = BOTH, expand = True)
        self.canvas.bind('<KeyPress-space>', self.drawCircle)

    def drawCircle(self):
        r = min(self.ws, self.hs)/3
        coord = (self.ws/2-r, self.hs/2-r, self.ws/2+r, self.hs/2+r)
        self.canvas.create_oval(coord, fill = 'blue')

root = Tk()
TheBlueCircle(root)
root.mainloop()

But it doesn't work. No matter how many times I press the space bar. It doesn't get to apply the drawCircle function.

What is wrong?

Body:
There are some changes needed in your code. First you need to take an event as arg for your drawCircle method. Secondly, the current focus is not set to the canvas object.

To have your method correctly executed upon tabbing space, either first press tab when you launch your GUI, or force a focus change in your code:

class TheBlueCircle:
    def __init__(self, master):
        ...
        self.canvas.bind('<space>', self.drawCircle)
        self.canvas.focus_set()

    def drawCircle(self,event=None):
        ...


问:
Can't access a Google Apps Script deployed as a web app with an access token
I'd like to understand a bit more how Apps Script web apps work when it comes to access them with a OAuth access token.

This is the Apps Script web app:

```<code>function doPost(e) {
  return ContentService.createTextOutput('ok');
}

function doGet(e) {
  return ContentService.createTextOutput('ok');
}
</code>```

It's deployed as: Me

Who has access to the app: See below

I use Postman to access the Apps Script web app. I call the web app URL (ending with /exec), and provide the header Authorization: Bearer ACCESS_TOKEN.

I generate access tokens using the Google OAuth Playground

I'm signed-in as me: It works with every 'who has access to the app' permissions, which is what I expect.

Signed-in as someone else within the domain: works only for 'anyone, even anonymous' permission, and only if the incoming request has no Authorization header. Otherwise I get a 403 Forbidden error.
I would expect it to work for the permissions below:

'anyone, even anonymous', even if the request has an Authorization header

'anyone'

'anyone within the domain'

Signed-in as someone else outside the domain: works only for 'anyone, even anonymous' permission, and only if the incoming request has no Authorization header. Otherwise I get a 403 Forbidden error.
I would expect it to work for the permissions below:

'anyone, even anonymous', even if the request has an Authorization header

'anyone'

What am I missing?

EDIT

The scope used to generate the access token is https://www.googleapis.com/auth/drive

答:
How about this workaround?

Specification:

When users access (run the script) to Web Apps which was deployed as "Who has access to the app:": Anyone, the script of Web Apps is required to be shared to the users. And also, the access token is required. This is the specification from April 11, 2018.

Goal:

You want to access to Web Apps under the condition of "Who has access to the app:": Anyone without sharing the script.

Unfortunately, this can be directly achieved by the specification. So it is required to think of a workaround.

Workaround:

Under above situation, when you want to make users access to Web Apps without sharing the script, I would like to propose the following workaround.

Deploy Web Apps as "Who has access to the app:": Anyone, even anonymous.

When users access to Web Apps, users use a password with the query parameter and/or payload.

By above settings, you can make users access to Web Apps without sharing the script. In this case, the password is used instead of the access token.

Sample script: Web Apps side

In this sample, the password is used as the query parameter. This can be used like the use of API key.

```<code>function doPost(e) {
  if (e.parameter.password === "sample") {
    return ContentService.createTextOutput("Done.");
  }
  return ContentService.createTextOutput("Error.");
}

function doGet(e) {
  if (e.parameter.password === "sample") {
    return ContentService.createTextOutput("Done.");
  }
  return ContentService.createTextOutput("Error.");
}
</code>```

Sample curl: Client side

```<code>curl -L "https://script.google.com/macros/s/###/exec?password=sample"
</code>```

Note:

When it accesses to Web Apps deployed above condition using above curl sample, Done. is returned from doGet(). If the password is wrong, Error. is returned. By this, you can make users access to Web Apps without sharing the script.

When you modified the script of Web Apps, please deploy Web Apps as new version. By this, the latest script is reflected.

References:

Web Apps

Taking advantage of Web Apps with Google Apps Script

Body:
I'd like to understand a bit more how Apps Script web apps work when it comes to access them with a OAuth access token.

This is the Apps Script web app:

function doPost(e) {
  return ContentService.createTextOutput('ok');
}

function doGet(e) {
  return ContentService.createTextOutput('ok');
}

It's deployed as: Me

Who has access to the app: See below

I use Postman to access the Apps Script web app. I call the web app URL (ending with /exec), and provide the header Authorization: Bearer ACCESS_TOKEN.

I generate access tokens using the Google OAuth Playground

I'm signed-in as me: It works with every 'who has access to the app' permissions, which is what I expect.

Signed-in as someone else within the domain: works only for 'anyone, even anonymous' permission, and only if the incoming request has no Authorization header. Otherwise I get a 403 Forbidden error.
I would expect it to work for the permissions below:

'anyone, even anonymous', even if the request has an Authorization header

'anyone'

'anyone within the domain'

Signed-in as someone else outside the domain: works only for 'anyone, even anonymous' permission, and only if the incoming request has no Authorization header. Otherwise I get a 403 Forbidden error.
I would expect it to work for the permissions below:

'anyone, even anonymous', even if the request has an Authorization header

'anyone'

What am I missing?

EDIT

The scope used to generate the access token is https://www.googleapis.com/auth/drive

Body:
How about this workaround?

Specification:

When users access (run the script) to Web Apps which was deployed as "Who has access to the app:": Anyone, the script of Web Apps is required to be shared to the users. And also, the access token is required. This is the specification from April 11, 2018.

Goal:

You want to access to Web Apps under the condition of "Who has access to the app:": Anyone without sharing the script.

Unfortunately, this can be directly achieved by the specification. So it is required to think of a workaround.

Workaround:

Under above situation, when you want to make users access to Web Apps without sharing the script, I would like to propose the following workaround.

Deploy Web Apps as "Who has access to the app:": Anyone, even anonymous.

When users access to Web Apps, users use a password with the query parameter and/or payload.

By above settings, you can make users access to Web Apps without sharing the script. In this case, the password is used instead of the access token.

Sample script: Web Apps side

In this sample, the password is used as the query parameter. This can be used like the use of API key.

function doPost(e) {
  if (e.parameter.password === "sample") {
    return ContentService.createTextOutput("Done.");
  }
  return ContentService.createTextOutput("Error.");
}

function doGet(e) {
  if (e.parameter.password === "sample") {
    return ContentService.createTextOutput("Done.");
  }
  return ContentService.createTextOutput("Error.");
}

Sample curl: Client side

curl -L "https://script.google.com/macros/s/###/exec?password=sample"

Note:

When it accesses to Web Apps deployed above condition using above curl sample, Done. is returned from doGet(). If the password is wrong, Error. is returned. By this, you can make users access to Web Apps without sharing the script.

When you modified the script of Web Apps, please deploy Web Apps as new version. By this, the latest script is reflected.

References:

Web Apps

Taking advantage of Web Apps with Google Apps Script


问:
Aesthetics must be either length 1 or the same as the data (1): colour
I am trying to plot a graph that will change based on selected inputs. Moreover, the data in the graph should be categorized by state. The dataset that I am using is midwest which is from ggplot2. For some reason, the color which should be based off of the state from the midwest dataset is not working. I get the error when I try to use color = state or color = prof_poverty$state. Aesthetics must be either length 1 or the same as the data (1): colour. There should be 5 different colors since there are 5 different states.

This is my code:

UI

```<code>library(shiny)
library(dplyr)
library(ggplot2)

prof_poverty <- midwest %>%
    select(state, county, percprof, percadultpoverty, percpovertyknown, percbelowpoverty, percadultpoverty, percelderlypoverty, percchildbelowpovert)

ui <- fluidPage(
   pageWithSidebar(
       headerPanel('Poverty compared with number of professors'),
       sidebarPanel(
           selectInput('xcol', 'X variable', names(prof_poverty)[3:8]),
           selectInput('ycol', 'Y variable', names(prof_poverty)[3:8]),
           selected = names(prof_poverty)[[2]]
       ),
       mainPanel(
           plotOutput('poverty')
       )
   )
)
</code>```

SERVER

```<code># Define server that renders a map and a table
server <- function(input, output){
    # Combine the selected variables into a new data frame
    selectedData <- reactive({
        prof_poverty[input$xcol, input$ycol]
    })

    output$poverty <- renderPlot ({
    ggplot(data = selectedData(), aes(x = input$xcol, y = input$ycol)) +
        geom_point(aes(color = prof_poverty$state)) })
}
# sRun the application
shinyApp(ui = ui, server = server)
</code>```

答:
Just changing the data used in the ggplot call to prof_poverty and using aes_string should work. (although there are more modern ways to deal with this)

The way you have subset the data in your reactive selectedData hasn't worked and the use of the full vector of states in the colour aesthetic is triggering the error.

Given the renderPlot function is reactive, you don't really need a reactive data object selectedData created before this anyway.

```<code>server <- function(input, output){

  output$poverty <- renderPlot ({
    ggplot(data = prof_poverty, aes_string(x = input$xcol, y = input$ycol)) +
      geom_point(aes(color = prof_poverty$state)) })
}
# Run the application
shinyApp(ui = ui, server = server)

</code>```

Body:
I am trying to plot a graph that will change based on selected inputs. Moreover, the data in the graph should be categorized by state. The dataset that I am using is midwest which is from ggplot2. For some reason, the color which should be based off of the state from the midwest dataset is not working. I get the error when I try to use color = state or color = prof_poverty$state. Aesthetics must be either length 1 or the same as the data (1): colour. There should be 5 different colors since there are 5 different states.

This is my code:

UI

library(shiny)
library(dplyr)
library(ggplot2)

prof_poverty <- midwest %>%
    select(state, county, percprof, percadultpoverty, percpovertyknown, percbelowpoverty, percadultpoverty, percelderlypoverty, percchildbelowpovert)

ui <- fluidPage(
   pageWithSidebar(
       headerPanel('Poverty compared with number of professors'),
       sidebarPanel(
           selectInput('xcol', 'X variable', names(prof_poverty)[3:8]),
           selectInput('ycol', 'Y variable', names(prof_poverty)[3:8]),
           selected = names(prof_poverty)[[2]]
       ),
       mainPanel(
           plotOutput('poverty')
       )
   )
)

SERVER

# Define server that renders a map and a table
server <- function(input, output){
    # Combine the selected variables into a new data frame
    selectedData <- reactive({
        prof_poverty[input$xcol, input$ycol]
    })

    output$poverty <- renderPlot ({
    ggplot(data = selectedData(), aes(x = input$xcol, y = input$ycol)) +
        geom_point(aes(color = prof_poverty$state)) })
}
# sRun the application
shinyApp(ui = ui, server = server)

Body:
Just changing the data used in the ggplot call to prof_poverty and using aes_string should work. (although there are more modern ways to deal with this)

The way you have subset the data in your reactive selectedData hasn't worked and the use of the full vector of states in the colour aesthetic is triggering the error.

Given the renderPlot function is reactive, you don't really need a reactive data object selectedData created before this anyway.

server <- function(input, output){

  output$poverty <- renderPlot ({
    ggplot(data = prof_poverty, aes_string(x = input$xcol, y = input$ycol)) +
      geom_point(aes(color = prof_poverty$state)) })
}
# Run the application
shinyApp(ui = ui, server = server)


问:
How to find the factors of a number given the prime factorization?
If I was given the prime factorization of a number in the form [2, 2, 3, 5, 5] how would I be able to find all of the factors in the form [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

I've attempted to do this through iterated loops, but as far as I was able to figure it out, it isn't clicking on a way to get the numbers as a result more than two numbers multiplying together

```<code>def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp
</code>```

I know this isn't the right way to do it because it only finds a small number of the factors

```<code>[1, 2, 3, 5, 6, 10, 15]
</code>```

答:
One way is to use itertools.product with numpy.prod and numpy.power:

```<code>import numpy as np
from itertools import product

f = [2, 2, 3, 5, 5]
uniq_f = np.unique(f)
counts = np.array(list(product(*(range(f.count(i) + 1) for i in uniq_f))))
sorted(np.prod(np.power(uniq_f, counts), 1))
</code>```

Output:

```<code>[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]
</code>```

Body:
If I was given the prime factorization of a number in the form [2, 2, 3, 5, 5] how would I be able to find all of the factors in the form [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

I've attempted to do this through iterated loops, but as far as I was able to figure it out, it isn't clicking on a way to get the numbers as a result more than two numbers multiplying together

def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp

I know this isn't the right way to do it because it only finds a small number of the factors

[1, 2, 3, 5, 6, 10, 15]

Body:
One way is to use itertools.product with numpy.prod and numpy.power:

import numpy as np
from itertools import product

f = [2, 2, 3, 5, 5]
uniq_f = np.unique(f)
counts = np.array(list(product(*(range(f.count(i) + 1) for i in uniq_f))))
sorted(np.prod(np.power(uniq_f, counts), 1))

Output:

[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]


问:
JUnit: Run same test on multiple target classes
I'm trying to automate a way to grade multiple students' files at once in my intro to Java class.

How can I run the same test(s) on all the files in a folder assuming the following conditions are true:

All files exist in the same folder (no sub-folders)

All files have a .java extension

All filenames are important identifiers

The code in every file meets the same requirements

```<code>    SayHelloWorld
    |-bsmithSayHelloWorld.java
    |-athomasSayHelloWorld.java
    |-cjenkinsSayHelloWorld.java
</code>```

I'm comfortable with JUnit but I've only used it in a single-file, clunky way in the past through IntelliJ.

Here's a simple sample file I'd be testing against:

public class Main {

    public static void main(String[] args) {
        System.out.println(sayHello());
    }
    public static String sayHello(){
        return "hello Java";
    }
}
```

<p>I would really like to be able to automate unit testing on all the .java files that exist in a given folder and output the results to something I can work with (console, file, whatever).</p>

<p>Possible output might look like:</p>

```bsmithSayHelloWorld helloWorldTest: pass
athomasSayHelloWorld helloWorldTest: fail
cjenkinsSayHelloWorld  helloWorldTest: pass
```

答:
Since Java11 you can run single java classes without compiling.

So if you are free to use Java 11, you can loop over the java files in the folder  with a given input, and then check the program output against expectations.

The same can be achieved using many other scripting solutions, like ant, make, gradle, python, ruby, ...

Body:
I'm trying to automate a way to grade multiple students' files at once in my intro to Java class.

How can I run the same test(s) on all the files in a folder assuming the following conditions are true:

All files exist in the same folder (no sub-folders)

All files have a .java extension

All filenames are important identifiers

The code in every file meets the same requirements

    SayHelloWorld
    |-bsmithSayHelloWorld.java
    |-athomasSayHelloWorld.java
    |-cjenkinsSayHelloWorld.java

I'm comfortable with JUnit but I've only used it in a single-file, clunky way in the past through IntelliJ.

Here's a simple sample file I'd be testing against:

public class Main {

    public static void main(String[] args) {
        System.out.println(sayHello());
    }
    public static String sayHello(){
        return "hello Java";
    }
}

I would really like to be able to automate unit testing on all the .java files that exist in a given folder and output the results to something I can work with (console, file, whatever).

Possible output might look like:

bsmithSayHelloWorld helloWorldTest: pass
athomasSayHelloWorld helloWorldTest: fail
cjenkinsSayHelloWorld  helloWorldTest: pass


问:
How to list the files in a sharepoint online directory via powershell
Hello I am trying to upload a file to my my Sharepoint Site (root directory) via PowerShell.
I can connect to the url but having issues with when trying to upload the file
i have installed Install-Module SharePointPnPPowerShellOnline

when i run the command i get this error

Add-PnPFile : The remote server returned an error: (403) Forbidden.
At line:1 char:1
+ Add-PnPFile -Path D:\delme\test.xlsx -Folder /
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [Add-PnPFile], WebException
    + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.Files.AddFile

Connect-PnPOnline –Url https://ABC123.sharepoint.com/sites/XXX/teamsites/os/Directory%20and%20Operating%20Systems/Forms/AllItems.aspx?viewpath=%2Fsites%2Fisd%2Fteamsites%2Fos%2FDirectory%20and%20Operating%20Systems%2FForms%2FAllItems.aspx

Add-PnPFile -Path D:\delme\test.xlsx -Folder /

I know I am close.

答:
Use the PowerShell below.</p>

```<code>$siteurl="https://ABC123.sharepoint.com/sites/XXX/teamsites/os"
Connect-PnPOnline -Url $siteurl
Add-PnPFile -Path D:\delme\test.xlsx -Folder "Directory and Operating Systems"
</code>```

Body:
Use the PowerShell below.

$siteurl="https://ABC123.sharepoint.com/sites/XXX/teamsites/os"
Connect-PnPOnline -Url $siteurl
Add-PnPFile -Path D:\delme\test.xlsx -Folder "Directory and Operating Systems"


问:
What is the correct way to pass data to a running thread
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

```<code>C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?
</code>```

So what is the correct way to pass data to a running thread in C# and Java?

答:
One way to pass data to a running thread is by implementing Message Queues. The thread that wants to tell the listening thread to do something would add an item to the queue of the listening thread. The listening thread reads from this thread in a blocking fashion. Causing it to wait when there are no actions to perform. Whenever another thread puts a message in the queue it will fetch the message, depending on the item and it's content you can then do something with it.

This is some Java / pseudo code:

```<code>class Listener
{
   private Queue queue;
   public SendMessage(Message m)
   {
     // This will be executed in the calling thread.
     // The locking will be done either in this function or in the Add below
     // depending on your Queue implementation.
     synchronize(this.queue)
     {
        this.queue.put(m);
     }
   }

   public Loop()
   {
     // This function should be called from the Listener thread.
     while(true)
     {
        Message m = this.queue.take();
        doAction(m);
     }
   }

   public doAction(Message m)
   {
      if (m is StopMessage)
      {
        ...
      }
   }
}
</code>```

And the caller:

```<code>class Caller
{
  private Listener listener;

  LetItStop()
  {
     listener.SendMessage(new StopMessage());
  }
}
</code>```

Of course, there are a lot of best practices when programming paralllel/concurrent code. For example, instead of while(true) you should at the least add a field like run :: Bool that you can set to false when you receive a StopMessage. Depending on the language in which you want to implement this you will have other primitives and behaviour to deal with.

In Java for example you might want to use the java.util.Concurrent package to keep things simple for you.

Body:
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?

So what is the correct way to pass data to a running thread in C# and Java?

Body:
One way to pass data to a running thread is by implementing Message Queues. The thread that wants to tell the listening thread to do something would add an item to the queue of the listening thread. The listening thread reads from this thread in a blocking fashion. Causing it to wait when there are no actions to perform. Whenever another thread puts a message in the queue it will fetch the message, depending on the item and it's content you can then do something with it.

This is some Java / pseudo code:

class Listener
{
   private Queue queue;
   public SendMessage(Message m)
   {
     // This will be executed in the calling thread.
     // The locking will be done either in this function or in the Add below
     // depending on your Queue implementation.
     synchronize(this.queue)
     {
        this.queue.put(m);
     }
   }

   public Loop()
   {
     // This function should be called from the Listener thread.
     while(true)
     {
        Message m = this.queue.take();
        doAction(m);
     }
   }

   public doAction(Message m)
   {
      if (m is StopMessage)
      {
        ...
      }
   }
}

And the caller:

class Caller
{
  private Listener listener;

  LetItStop()
  {
     listener.SendMessage(new StopMessage());
  }
}

Of course, there are a lot of best practices when programming paralllel/concurrent code. For example, instead of while(true) you should at the least add a field like run :: Bool that you can set to false when you receive a StopMessage. Depending on the language in which you want to implement this you will have other primitives and behaviour to deal with.

In Java for example you might want to use the java.util.Concurrent package to keep things simple for you.


问:
AngularJS Validation on <select> with a prompt option
I have the following code for a select drop down input that is styled in Bootstrap.

```<code><select class="form-control" name="businessprocess" ng-model="businessprocess" required>
    <option value="">-- Select Business Process --</option>
    <option value="C">Process C</option>
    <option value="Q">Process Q</option>
</select>
</code>```

Before the user is able to submit this form, he or she must select a business process.

So I have put the required directive on the select statement, however because the first option tag has -- Select Business Process -- that still counts as a selected option, and thus the required flag is met, and therefore the form validates even though no actual Business Process is selected.

How can I overcome this issue?

Thank You.

答:
Use the following code snippet</p>

```<code><select class="form-control" name="businessprocess" ng-model="businessprocess">
    <option value="A" disabled selected hidden>-- Select Business Process --</option>
    <option value="C">Process C</option>
    <option value="Q">Process Q</option>
</select>
</code>```

Body:
I have the following code for a select drop down input that is styled in Bootstrap.

<select class="form-control" name="businessprocess" ng-model="businessprocess" required>
    <option value="">-- Select Business Process --</option>
    <option value="C">Process C</option>
    <option value="Q">Process Q</option>
</select>

Before the user is able to submit this form, he or she must select a business process.

So I have put the required directive on the select statement, however because the first option tag has -- Select Business Process -- that still counts as a selected option, and thus the required flag is met, and therefore the form validates even though no actual Business Process is selected.

How can I overcome this issue?

Thank You.

Body:
Use the following code snippet

<select class="form-control" name="businessprocess" ng-model="businessprocess">
    <option value="A" disabled selected hidden>-- Select Business Process --</option>
    <option value="C">Process C</option>
    <option value="Q">Process Q</option>
</select>


问:
How to Flexbox into a specific way?
I want to seperate my divs into something like the image below using flexbox but i'm not sure how to do it. Do I need to use absolute positions for it or does flexbox have a way to approach it without too much issue?

答: If you use flexbox for this layout, you'll need a few extra wrapper divs: one to contain all five divs, one to contain divs 1 & 4, and one to contain divs 2 & 5. It may also be worth it to try CSS grid, which is built for this kind of thing without wrapper divs.</p>

Title: How to Flexbox into a specific way?


问:
CSV file - RStudio does not recognize values in the columns [pcr package used]
I work on the data from qPCR experiment. The dataset I want to use was produced in Excel - table of 2 columns, 90 rows, all values are numeric (decimal place - period). The file was saved as CSV and opened in RStudio as such. For my work, I use pcr package (tidyverse and dplyr also loaded in).
However, upon using one of the commands in this package, I get an error.

Checked the length of the columns, one is shown as 2 (it should not be, as there are 10 variables, each of them is repeated 9 times). The other one is not recognized

> View(MIR393a_R)
> group_var <- rep(c("Col-0 B", "Col-0 A", "Kyoto B", "Kyoto A", "Kb-0 B", "Kb-0 A", "Db-1 B", "Db-1 A", "Durh-1 B", "Durh-1 A"), each = 9)
> pcr_analyze(MIR393a_R, group_var = group_var, reference_gene ='Reference', reference_group = 'MIR393a', method = 'delta_delta_ct', plot = FALSE)
```

<p>What should be there:
Calculated values and errors of double delta (plot is optional if plot = TRUE)
What I obtained:</p>

```Error: Column `MIR393a` must be length 10 (the number of rows) or one, not 0
In addition: Warning messages:
1: In mean.default(x) : argument is not numeric or logical: returning NA
2: In mean.default(x) : argument is not numeric or logical: returning NA
3: In mean.default(x) : argument is not numeric or logical: returning NA
4: In mean.default(x) : argument is not numeric or logical: returning NA
5: In mean.default(x) : argument is not numeric or logical: returning NA
6: In mean.default(x) : argument is not numeric or logical: returning NA
7: In mean.default(x) : argument is not numeric or logical: returning NA
8: In mean.default(x) : argument is not numeric or logical: returning NA
9: In mean.default(x) : argument is not numeric or logical: returning NA
10: In mean.default(x) : argument is not numeric or logical: returning NA
```

答:
I'm not familiar with the pcr package you are using, but is it possible you should set
reference_group = 'MIR393a_R'
 not 'MIR393a' in the pcr_analyze line?</p>

Body:
I work on the data from qPCR experiment. The dataset I want to use was produced in Excel - table of 2 columns, 90 rows, all values are numeric (decimal place - period). The file was saved as CSV and opened in RStudio as such. For my work, I use pcr package (tidyverse and dplyr also loaded in).
However, upon using one of the commands in this package, I get an error.

Checked the length of the columns, one is shown as 2 (it should not be, as there are 10 variables, each of them is repeated 9 times). The other one is not recognized

> View(MIR393a_R)
> group_var <- rep(c("Col-0 B", "Col-0 A", "Kyoto B", "Kyoto A", "Kb-0 B", "Kb-0 A", "Db-1 B", "Db-1 A", "Durh-1 B", "Durh-1 A"), each = 9)
> pcr_analyze(MIR393a_R, group_var = group_var, reference_gene ='Reference', reference_group = 'MIR393a', method = 'delta_delta_ct', plot = FALSE)

What should be there:
Calculated values and errors of double delta (plot is optional if plot = TRUE)
What I obtained:

Error: Column `MIR393a` must be length 10 (the number of rows) or one, not 0
In addition: Warning messages:
1: In mean.default(x) : argument is not numeric or logical: returning NA
2: In mean.default(x) : argument is not numeric or logical: returning NA
3: In mean.default(x) : argument is not numeric or logical: returning NA
4: In mean.default(x) : argument is not numeric or logical: returning NA
5: In mean.default(x) : argument is not numeric or logical: returning NA
6: In mean.default(x) : argument is not numeric or logical: returning NA
7: In mean.default(x) : argument is not numeric or logical: returning NA
8: In mean.default(x) : argument is not numeric or logical: returning NA
9: In mean.default(x) : argument is not numeric or logical: returning NA
10: In mean.default(x) : argument is not numeric or logical: returning NA


问:
Getting a null object exception when using an interface
I have created a shopping cart via recyclerview. Each viewholder also has a + and - button to add or remove quantity. This functionality is done in the adapter and I have to notify the parent fragment of the updated total amount. This last bit is done via an interface. The problem is, I am getting the following error:

```<code>Process: com.ecomm.market, PID: 6630
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.ecomm.market.SelectionAdapter$OnUpdateCartListener.onUpdateCart(int)' on a null object reference
        at com.ecomm.market.SelectionAdapter$ViewHolder$1.onClick(SelectionAdapter.java:103)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

The selected item and corresponding quantity are stored in a hashmap that I convert to an array to populate the recycler view cart. This is what the relevant part of my main fragment MenuFragment looks like:

```<code>
                // Using the adapter interface to add items to cart and adding up total amount
                menuItemAdapter.setOnAddToCartListener(new MenuItemAdapter.OnAddToCartListener() {
                    @Override
                    public void onAddToCart(final HashMap selectionItemsHashMap) {

                        setupSelectionRecycler(menuView);
                        totalAmount = mapToArray(selectionItemsHashMap);

                            selectionAdapter = new SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

                        selectionRecycler.setAdapter(selectionAdapter);
                        cartItemsHashmap = selectionItemsHashMap;

                        selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                            @Override
                            public void onUpdateCart(int updatedTotalAmount) {

                                String stringTotalAmount = Integer.toString(updatedTotalAmount);
                                Log.d(TAG, "received total:" +stringTotalAmount);
                                tvTotalAmount.setText("$"+ stringTotalAmount);
                                totalAmount = updatedTotalAmount;
                            }
                        });
                    }
                });
            }
</code>```

And here is an excerpt from my adapter SelectionAdapter:

```<code>public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.ViewHolder> {

    private static final String TAG = SelectionAdapter.class.getSimpleName();

    private ArrayList<SelectionItem> selectionItemArrayList = new ArrayList<>();
    public HashMap<String, Integer> selectionItemsHashMap = new HashMap<String, Integer>();
    public int totalAmount;

    private OnUpdateCartListener updateCartListener;

    public interface OnUpdateCartListener {
        void onUpdateCart(int totalAmount);
    }

    public void setUpdateCartListener(OnUpdateCartListener updateCartListener) {
        this.updateCartListener = updateCartListener;
    }

    public SelectionAdapter(ArrayList<SelectionItem> selectionItemArrayList, HashMap<String, Integer> selectionItemsHashMap, int currentTotalAmount) {
        this.selectionItemArrayList = selectionItemArrayList;
        this.selectionItemsHashMap = selectionItemsHashMap;
        this.totalAmount = currentTotalAmount;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.selection_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
        String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
        viewHolder.tvDishQuantity.setText(quantity);
    }

    @Override
    public int getItemCount() {
        return selectionItemArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvSelectItem, tvDishQuantity;
        ImageView addQuantity, subtractQuantity, deleteItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvSelectItem = itemView.findViewById(R.id.dish_selection);
            tvDishQuantity = itemView.findViewById(R.id.dish_quantity);

            addQuantity = itemView.findViewById(R.id.button_add);
            subtractQuantity = itemView.findViewById(R.id.button_subtract);
            deleteItem = itemView.findViewById(R.id.delete_item);

            addQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Find the name of the menu item
                    int position = getAdapterPosition();
                    String itemName = selectionItemArrayList.get(position).getSelectionName();

                    // Increase quantity
                    int currentQuantity = selectionItemsHashMap.get(itemName);

                    currentQuantity += 1;
                    // Update the hashmap with the new quantity
                    selectionItemsHashMap.put(itemName,currentQuantity);

                    //Update total amount
                    for (Object name: selectionItemsHashMap.keySet()) {
                        String key = (String) name;
                        if (key.equals(selectionItemArrayList.get(position).getSelectionName())) {
                            int eachPrice = Integer.parseInt(selectionItemArrayList.get(position).getSelectionPrice());
                            totalAmount += eachPrice;
                        }
                    }
                    // Display the new quantity
                    String stringCurrentQuantity = Integer.toString(currentQuantity);
                    tvDishQuantity.setText(stringCurrentQuantity);
                    //updateCartListener.onUpdateCart(totalAmount);
                }
            });
}
</code>```

EDIT
A couple of points:
- When the cart is initially filled, I use this same code and it works fine.
- The problem occurs once the user returns to the cart and I have to repopulate it from a bundle. Everything works fine, except when the user goes straight to the cart and attempts to alter the quantity from there.

答:
I guess you forget assignment the updateCartListener in your adapter.</p>

```<code>    SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

    cartItemsHashmap = selectionItemsHashMap;

    selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                        @Override
                        public void onUpdateCart(int updatedTotalAmount) {

                            String stringTotalAmount = Integer.toString(updatedTotalAmount);
                            Log.d(TAG, "received total:" +stringTotalAmount);
                            tvTotalAmount.setText("$"+ stringTotalAmount);
                            totalAmount = updatedTotalAmount;
                        }
                    });
     selectionRecycler.setAdapter(selectionAdapter);
</code>```

Body:
I have created a shopping cart via recyclerview. Each viewholder also has a + and - button to add or remove quantity. This functionality is done in the adapter and I have to notify the parent fragment of the updated total amount. This last bit is done via an interface. The problem is, I am getting the following error:

Process: com.ecomm.market, PID: 6630
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.ecomm.market.SelectionAdapter$OnUpdateCartListener.onUpdateCart(int)' on a null object reference
        at com.ecomm.market.SelectionAdapter$ViewHolder$1.onClick(SelectionAdapter.java:103)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

The selected item and corresponding quantity are stored in a hashmap that I convert to an array to populate the recycler view cart. This is what the relevant part of my main fragment MenuFragment looks like:

                // Using the adapter interface to add items to cart and adding up total amount
                menuItemAdapter.setOnAddToCartListener(new MenuItemAdapter.OnAddToCartListener() {
                    @Override
                    public void onAddToCart(final HashMap selectionItemsHashMap) {

                        setupSelectionRecycler(menuView);
                        totalAmount = mapToArray(selectionItemsHashMap);

                            selectionAdapter = new SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

                        selectionRecycler.setAdapter(selectionAdapter);
                        cartItemsHashmap = selectionItemsHashMap;

                        selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                            @Override
                            public void onUpdateCart(int updatedTotalAmount) {

                                String stringTotalAmount = Integer.toString(updatedTotalAmount);
                                Log.d(TAG, "received total:" +stringTotalAmount);
                                tvTotalAmount.setText("$"+ stringTotalAmount);
                                totalAmount = updatedTotalAmount;
                            }
                        });
                    }
                });
            }

And here is an excerpt from my adapter SelectionAdapter:

public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.ViewHolder> {

    private static final String TAG = SelectionAdapter.class.getSimpleName();

    private ArrayList<SelectionItem> selectionItemArrayList = new ArrayList<>();
    public HashMap<String, Integer> selectionItemsHashMap = new HashMap<String, Integer>();
    public int totalAmount;

    private OnUpdateCartListener updateCartListener;

    public interface OnUpdateCartListener {
        void onUpdateCart(int totalAmount);
    }

    public void setUpdateCartListener(OnUpdateCartListener updateCartListener) {
        this.updateCartListener = updateCartListener;
    }

    public SelectionAdapter(ArrayList<SelectionItem> selectionItemArrayList, HashMap<String, Integer> selectionItemsHashMap, int currentTotalAmount) {
        this.selectionItemArrayList = selectionItemArrayList;
        this.selectionItemsHashMap = selectionItemsHashMap;
        this.totalAmount = currentTotalAmount;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.selection_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
        String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
        viewHolder.tvDishQuantity.setText(quantity);
    }

    @Override
    public int getItemCount() {
        return selectionItemArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvSelectItem, tvDishQuantity;
        ImageView addQuantity, subtractQuantity, deleteItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvSelectItem = itemView.findViewById(R.id.dish_selection);
            tvDishQuantity = itemView.findViewById(R.id.dish_quantity);

            addQuantity = itemView.findViewById(R.id.button_add);
            subtractQuantity = itemView.findViewById(R.id.button_subtract);
            deleteItem = itemView.findViewById(R.id.delete_item);

            addQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Find the name of the menu item
                    int position = getAdapterPosition();
                    String itemName = selectionItemArrayList.get(position).getSelectionName();

                    // Increase quantity
                    int currentQuantity = selectionItemsHashMap.get(itemName);

                    currentQuantity += 1;
                    // Update the hashmap with the new quantity
                    selectionItemsHashMap.put(itemName,currentQuantity);

                    //Update total amount
                    for (Object name: selectionItemsHashMap.keySet()) {
                        String key = (String) name;
                        if (key.equals(selectionItemArrayList.get(position).getSelectionName())) {
                            int eachPrice = Integer.parseInt(selectionItemArrayList.get(position).getSelectionPrice());
                            totalAmount += eachPrice;
                        }
                    }
                    // Display the new quantity
                    String stringCurrentQuantity = Integer.toString(currentQuantity);
                    tvDishQuantity.setText(stringCurrentQuantity);
                    //updateCartListener.onUpdateCart(totalAmount);
                }
            });
}

EDIT
A couple of points:
- When the cart is initially filled, I use this same code and it works fine.
- The problem occurs once the user returns to the cart and I have to repopulate it from a bundle. Everything works fine, except when the user goes straight to the cart and attempts to alter the quantity from there.

Body:
I guess you forget assignment the updateCartListener in your adapter.

    SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

    cartItemsHashmap = selectionItemsHashMap;

    selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                        @Override
                        public void onUpdateCart(int updatedTotalAmount) {

                            String stringTotalAmount = Integer.toString(updatedTotalAmount);
                            Log.d(TAG, "received total:" +stringTotalAmount);
                            tvTotalAmount.setText("$"+ stringTotalAmount);
                            totalAmount = updatedTotalAmount;
                        }
                    });
     selectionRecycler.setAdapter(selectionAdapter);


答:
You could use itertools.combinations (which will give duplicates) and set to filter the duplicates out:

```<code>from itertools import combinations
from functools import reduce
from operator import mul

factors = [2, 2, 3, 5, 5]

set(reduce(mul, combination) for i in range (1, len(factors) + 1) for combination in combinations(factors, i))
</code>```

Output:

```<code>{2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300}
</code>```

Title: How to find the factors of a number given the prime factorization?

Body:
You could use itertools.combinations (which will give duplicates) and set to filter the duplicates out:

from itertools import combinations
from functools import reduce
from operator import mul

factors = [2, 2, 3, 5, 5]

set(reduce(mul, combination) for i in range (1, len(factors) + 1) for combination in combinations(factors, i))

Output:

{2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300}


问:
iPad/iPhone HTML5 video loading
I'm trying to load  on the fly on the iPad/iPhone and notice that I cannot place a div above this.  I put the overlay in the html so that it's generated on page load and not added via javascript and the video when its created is absolutely positioned below this element.  This works on a PC, I'm wondering if since it was created via js that the iPhone OS is overriding the z-index and forcing to the top?

Also is there a way to override the default "cannot play icon", the one with the slash, and show a loading animation instead?  This would solve my issue via another route.

My last option would be to loaded all the video tags via js on page load and have them layered on top of each other for the iPad/iPhone?  Since the iPhone OS won't load any video until requested would this work?

I also am having an issue with the iPhone and showing the "poster" attribute that is set on the video tag.

答:
I found a pretty nice work-around.  I'm using jquery, so that's one thing to keep in mind.

My issue was, I was building a Ipad web-app, with a navigation button at the bottom left (I can't give a link as it's a client project).  When the user would click (tap) the button in the lower left, a drop-up menu would animate in, and then you could click the buttons in those menu's to get to deeper sub-menu's.

The problem:

any li tags (or anything for that matter) that was over the video, wouldn't be clickable, so on the pages with video, part of my tap-navigation (the part over the video wouldn't work).  Reading posts here actually lead me to my solution, simple, and it may or may not work for your case, but I hope it does.

My workaround:

```<code>var myNav = $("TAG_SELECTOR_HERE");

myNav.toggle(function(){
   var videos = $("video");
   videos.removeAttr("controls");
},
function(){
   var videos = $("video");
   videos.attr("controls","true");
})
</code>```

Now I know I may be missing some semi-colons, or my coding may be off, but I'm just posting for reference.  Basically, when my menu is clicked, or is active, I'm removing the controls attribute from all videos, and then when the menu is deactivated, I'm bringing the controls back.

You could use this method anywhere you like...you could remove the controls after a video ends, after someone hovers over something (assuming that something isn't already over the video), when the mouse is within certain coordinates (may be your only solution in extreme cases) but this should work.

Thanks!!

-Nick

ContentLicense: CC BY-SA 2.5

Title: iPad/iPhone HTML5 video loading

Body:
I found a pretty nice work-around.  I'm using jquery, so that's one thing to keep in mind.

My issue was, I was building a Ipad web-app, with a navigation button at the bottom left (I can't give a link as it's a client project).  When the user would click (tap) the button in the lower left, a drop-up menu would animate in, and then you could click the buttons in those menu's to get to deeper sub-menu's.

The problem:

any li tags (or anything for that matter) that was over the video, wouldn't be clickable, so on the pages with video, part of my tap-navigation (the part over the video wouldn't work).  Reading posts here actually lead me to my solution, simple, and it may or may not work for your case, but I hope it does.

My workaround:

var myNav = $("TAG_SELECTOR_HERE");

myNav.toggle(function(){
   var videos = $("video");
   videos.removeAttr("controls");
},
function(){
   var videos = $("video");
   videos.attr("controls","true");
})

Now I know I may be missing some semi-colons, or my coding may be off, but I'm just posting for reference.  Basically, when my menu is clicked, or is active, I'm removing the controls attribute from all videos, and then when the menu is deactivated, I'm bringing the controls back.

You could use this method anywhere you like...you could remove the controls after a video ends, after someone hovers over something (assuming that something isn't already over the video), when the mouse is within certain coordinates (may be your only solution in extreme cases) but this should work.

Thanks!!

-Nick


问:
Getting java to display the correct amount of decrements
I am making an app which is a guessing game between 1 and 100. The current version I am writing gives the player 7 tries to to find the correct guess. I have created a variable to display how many guesses the player has left, however once the player has guessed, the number of guesses decrements by more than one (usually two).

So basically the numberOfGuesses var. will decrement every time the checkGuess() method is run. I have tried placing the decrement in the event listener for when the player presses the button, but it's still decrementing by more than one. There is a setOnClick listener if the player clicks the mouse button too, and another for the enter button. When I use the button in the game, it decrements properly. When I use the ENTER button, it decrements by two. Is it running the button listener when I press ENTER?

I tried changing decrement from numberOfGuesses--; to --numberOfGuesses;

I tried assigning it as numberOfGuesses = numberOfGuesses - 1;

Here is the variables wiring to thew GUI, and the checkGuess() method

```<code>public class MainActivity extends AppCompatActivity {
    private EditText txtGuess;
    private Button btnGuess;
    private TextView lblOutput;
    private int theNumber;
    private int numberOfTries = 7;

    public void checkGuess() {
        String guessText = txtGuess.getText().toString();//
        String message = "";
        try {
            --numberOfTries;
            int guess = Integer.parseInt(guessText);
            if (guess > theNumber)
                message = guess + " is too high. You have " +numberOfTries + " " + " tries left! ";

            else if (guess < theNumber)
                message = guess + " is too low. You have " +numberOfTries + " " + " tries left! ";

            else{
                message = guess +
                        " is correct! You finished with " +numberOfTries + " tries left. Let's play again!";
                Toast.makeText(MainActivity.this, message,
                          Toast.LENGTH_LONG).show();
                newGame();

            }
        } catch (Exception e) {
            message = "Enter a whole number between 1 and 100.";
        } finally {
            lblOutput.setText(message);
            txtGuess.requestFocus();
            txtGuess.selectAll();
</code>```

The newGame() method which generates a new random number

```<code> public void newGame(){

        theNumber = (int)(Math.random() * 100 + 1);
        numberOfTries = 7;

    }
</code>```

Here is the method which runs on execution of app

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtGuess = (EditText) findViewById(R.id.txtGuess);
        btnGuess = (Button) findViewById(R.id.btnGuess);
        lblOutput = (TextView) findViewById(R.id.lblOutput);
        newGame();
        btnGuess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkGuess();
            }
        });
        txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
               checkGuess();
               return true;
            }
        });
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
</code>```

I am expecting the numberOfGuesses to decrement from 7 to 6, but the actual output is decrementing from 7 to 5, when I use enter, it works as I want for the button click (or at least displaying as 7 to 5),

答: Pressing enter while the text field is selected would trigger the OnEditorActionListener (and so would any other change, as far as I can tell).  Have you tried filtering that Listener by actionId to make sure it only goes off specifically for the enter key?</p>

Body:
I am making an app which is a guessing game between 1 and 100. The current version I am writing gives the player 7 tries to to find the correct guess. I have created a variable to display how many guesses the player has left, however once the player has guessed, the number of guesses decrements by more than one (usually two).

So basically the numberOfGuesses var. will decrement every time the checkGuess() method is run. I have tried placing the decrement in the event listener for when the player presses the button, but it's still decrementing by more than one. There is a setOnClick listener if the player clicks the mouse button too, and another for the enter button. When I use the button in the game, it decrements properly. When I use the ENTER button, it decrements by two. Is it running the button listener when I press ENTER?

I tried changing decrement from numberOfGuesses--; to --numberOfGuesses;

I tried assigning it as numberOfGuesses = numberOfGuesses - 1;

Here is the variables wiring to thew GUI, and the checkGuess() method

public class MainActivity extends AppCompatActivity {
    private EditText txtGuess;
    private Button btnGuess;
    private TextView lblOutput;
    private int theNumber;
    private int numberOfTries = 7;

    public void checkGuess() {
        String guessText = txtGuess.getText().toString();//
        String message = "";
        try {
            --numberOfTries;
            int guess = Integer.parseInt(guessText);
            if (guess > theNumber)
                message = guess + " is too high. You have " +numberOfTries + " " + " tries left! ";

            else if (guess < theNumber)
                message = guess + " is too low. You have " +numberOfTries + " " + " tries left! ";

            else{
                message = guess +
                        " is correct! You finished with " +numberOfTries + " tries left. Let's play again!";
                Toast.makeText(MainActivity.this, message,
                          Toast.LENGTH_LONG).show();
                newGame();

            }
        } catch (Exception e) {
            message = "Enter a whole number between 1 and 100.";
        } finally {
            lblOutput.setText(message);
            txtGuess.requestFocus();
            txtGuess.selectAll();

The newGame() method which generates a new random number

 public void newGame(){

        theNumber = (int)(Math.random() * 100 + 1);
        numberOfTries = 7;

    }

Here is the method which runs on execution of app

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtGuess = (EditText) findViewById(R.id.txtGuess);
        btnGuess = (Button) findViewById(R.id.btnGuess);
        lblOutput = (TextView) findViewById(R.id.lblOutput);
        newGame();
        btnGuess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkGuess();
            }
        });
        txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
               checkGuess();
               return true;
            }
        });
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

I am expecting the numberOfGuesses to decrement from 7 to 6, but the actual output is decrementing from 7 to 5, when I use enter, it works as I want for the button click (or at least displaying as 7 to 5),


问:
Accessing JTextField Text
I have a simple program, I am trying to access the data from the textfield but I am always getting null or empty field.

For an example.

```<code>public class income {
JButton save = new JButton("save");

  public JTextField setIncomeValue() {
  ..
  ..
    JTextField incomeValue = new JTextField(10);
    return incomeValue;
  }

  public void launch_Ui{
   frame.add(setIncomeValue());
   frame.add(save);
   save.addactionlistener(new saveListener());
  }
}

class saveListener  implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        String test = new income().setIncomeValue().getText();
        System.out.println("savings...  " + test + " value ?");
    }

}
</code>```

Anybody have any idea or have stumble upon this challenge before?

答:
Updates

After looking through my logic carefully, i have finally come out with a solution.
What i did was to create a scope inside my savelistener .

```<code>class saveListener implements ActionListener{

JTextField incomeData;

public saveListener(JTextField incomeData) {
    this.incomeData = incomeData;
 }

 @Override
 public void actionPerformed(ActionEvent e) {
 String test = incomeData.getText();
    System.out.println("Input data " + test);
  }
}
</code>```

Hope this will help those who are in need :)

Title: Accessing JTextField Text

Body:
I have a simple program, I am trying to access the data from the textfield but I am always getting null or empty field.

For an example.

public class income {
JButton save = new JButton("save");

  public JTextField setIncomeValue() {
  ..
  ..
    JTextField incomeValue = new JTextField(10);
    return incomeValue;
  }

  public void launch_Ui{
   frame.add(setIncomeValue());
   frame.add(save);
   save.addactionlistener(new saveListener());
  }
}

class saveListener  implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        String test = new income().setIncomeValue().getText();
        System.out.println("savings...  " + test + " value ?");
    }

}

Anybody have any idea or have stumble upon this challenge before?

Body:
Updates

After looking through my logic carefully, i have finally come out with a solution.
What i did was to create a scope inside my savelistener .

class saveListener implements ActionListener{

JTextField incomeData;

public saveListener(JTextField incomeData) {
    this.incomeData = incomeData;
 }

 @Override
 public void actionPerformed(ActionEvent e) {
 String test = incomeData.getText();
    System.out.println("Input data " + test);
  }
}

Hope this will help those who are in need :)