问:
sending a list value in a Post request's body to validate Pydantic model
I'm using FastAPI, Pydantic, SQLAlchemy, and Postgres to build a service that receives post requests and stores the data on the database. There is a List in the Pydantic model like the following:

```<code>from typing import List
from pydantic import BaseModel, Field

class Note(base model):
    id: int
    title: str
    authors: List[str]
</code>```

And the table:

```<code>notes = Table(
    "notes",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("title", String),
    Column("authors", ARRAY(String(50), dimensions=3)),
)
</code>```

Here is the way I do the post request, when there is not a List value:

```<code>def post(payload: Note):
    query = questions.insert().values(title=payload.title)
    return database.execute(query=query)
</code>```

Post request's body:

```<code>{
    "title": "some value"
}
</code>```

And it works fine. But adding the List value breaks it with Pydantic's validation error:

```<code>def post(payload: Note):
    query = questions.insert().values(title=payload.title, authors=payload.authors)
    return database.execute(query=query)
</code>```
```<code>{
    "title": "some value",
    "authors": ["name1", "name2", "name3"]
}
</code>```

value is not a valid list

type_error.list

How can I change the post function and request body, to make this work?

Edit: The traceback:

```<code>ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/applications.py", line 149, in __call__
    await super().__call__(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/applications.py", line 102, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 550, in __call__
    await route.handle(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 204, in app
    response_data = await serialize_response(
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 126, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Note
response
  value is not a valid list (type=type_error.list)
</code>```

答:
I was using Django-Ninja (based on FastAPI) and had the same error. Originally, my decorator was like this:

@router.get('/apartment-sale-hanoi/', response=List[ApartmentSaleHanoiSchema])
```
<p>I fixed <code>value is not a valid list (type=type_error.list)</code> just by removing <code>List</code> from the response model as following:</p>
<pre class="lang-py prettyprint-override"><code>@router.get('/apartment-sale-hanoi/', response=ApartmentSaleHanoiSchema)
</code>```

my returning response (displayed as JSON) was a list of objects

response = ApartmentSaleHanoi.objects.all()
```

Body:
I'm using FastAPI, Pydantic, SQLAlchemy, and Postgres to build a service that receives post requests and stores the data on the database. There is a List in the Pydantic model like the following:

from typing import List
from pydantic import BaseModel, Field

class Note(base model):
    id: int
    title: str
    authors: List[str]

And the table:

notes = Table(
    "notes",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("title", String),
    Column("authors", ARRAY(String(50), dimensions=3)),
)

Here is the way I do the post request, when there is not a List value:

def post(payload: Note):
    query = questions.insert().values(title=payload.title)
    return database.execute(query=query)

Post request's body:

{
    "title": "some value"
}

And it works fine. But adding the List value breaks it with Pydantic's validation error:

def post(payload: Note):
    query = questions.insert().values(title=payload.title, authors=payload.authors)
    return database.execute(query=query)

{
    "title": "some value",
    "authors": ["name1", "name2", "name3"]
}

value is not a valid list

type_error.list

How can I change the post function and request body, to make this work?

Edit: The traceback:

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/applications.py", line 149, in __call__
    await super().__call__(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/applications.py", line 102, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 550, in __call__
    await route.handle(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 204, in app
    response_data = await serialize_response(
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 126, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Note
response
  value is not a valid list (type=type_error.list)

Body:
I was using Django-Ninja (based on FastAPI) and had the same error. Originally, my decorator was like this:

@router.get('/apartment-sale-hanoi/', response=List[ApartmentSaleHanoiSchema])

I fixed value is not a valid list (type=type_error.list) just by removing List from the response model as following:

@router.get('/apartment-sale-hanoi/', response=ApartmentSaleHanoiSchema)

my returning response (displayed as JSON) was a list of objects

response = ApartmentSaleHanoi.objects.all()


来源: stackexchange

问:
How to bypass CORS policy when sending get/post request from React JS?
From my React JS app , I need to fetch data from servers in other domains.
However, I am prevented by CORS policy and not able to fetch the data.

Let us assume that my React app is running on localhost:3000 during the development.
I want to make get/post call to another server running on  http://myserver.com
The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz

I have installed http-proxy-middleware thru npm and using it in my react app.
Created a setupProxy.js file under src folder with below content :

```<code>const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
   app.use(
      createProxyMiddleware('/data/records' , {
        target:'http://ext-server.com',
        changeOrigin: true
     })
 )
}
</code>```

On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com

```<code>getTheData() {

let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);

axios.get(url,
  {
    headers: {
     "Content-Type":"application/json;charset=UTL-8",
     "Access-Control-Allow-Origin": "*",
     Accept: "application/json",
      },
      baseURL: 'http://ext-server.com'
   }
 ).then((response) => {
     console.log(response["access_token"]);
  }).catch(error) => {
       console.log("Error: ", error)
  }).then(function () {
       console.log("always call it")
});

}
</code>```

In the package.json , I have added :

```<code>"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",
</code>```

But I am still getting below error:
Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.

Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware?
Any help will be very useful!
Thanks

答:
The CORS policy is one and only administered by the web server and its settings. To allow CORS requests it has to be implemented on server side. No chance to do it from your client application.

Basically its just a header setting (below example for NodeJS):

```<code>res.header("Access-Control-Allow-Origin", "*")
</code>```

Sending that header will allow requests from every domain.

ContentLicense: CC BY-SA 4.0

Body:
From my React JS app , I need to fetch data from servers in other domains.
However, I am prevented by CORS policy and not able to fetch the data.

Let us assume that my React app is running on localhost:3000 during the development.
I want to make get/post call to another server running on  http://myserver.com
The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz

I have installed http-proxy-middleware thru npm and using it in my react app.
Created a setupProxy.js file under src folder with below content :

const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
   app.use(
      createProxyMiddleware('/data/records' , {
        target:'http://ext-server.com',
        changeOrigin: true
     })
 )
}

On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com

getTheData() {

let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);

axios.get(url,
  {
    headers: {
     "Content-Type":"application/json;charset=UTL-8",
     "Access-Control-Allow-Origin": "*",
     Accept: "application/json",
      },
      baseURL: 'http://ext-server.com'
   }
 ).then((response) => {
     console.log(response["access_token"]);
  }).catch(error) => {
       console.log("Error: ", error)
  }).then(function () {
       console.log("always call it")
});

}

In the package.json , I have added :

"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",

But I am still getting below error:
Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.

Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware?
Any help will be very useful!
Thanks

Body:
The CORS policy is one and only administered by the web server and its settings. To allow CORS requests it has to be implemented on server side. No chance to do it from your client application.

Basically its just a header setting (below example for NodeJS):

res.header("Access-Control-Allow-Origin", "*")

Sending that header will allow requests from every domain.


问:
Replace all non NaN values with the initial value per row
I have the following dataframe:

```<code>Periods            0      1      2      3      4      5      6      7     8     9     10    11    12   13   14   15   16   17   18   19
Item 1           89.0   89.0   88.0   86.0   73.0   73.0   67.0    NaN   NaN   NaN   NaN   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 2          197.0  197.0  157.0  157.0  156.0  156.0  153.0  153.0   3.0   3.0   2.0   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 3          105.0  105.0   98.0   47.0   40.0   21.0   20.0   15.0  13.0  11.0  11.0  11.0  10.0  7.0  7.0  5.0  5.0  3.0  2.0  1.0
</code>```

It has several NaNs, and columns from a range between 0 - 20. What i wanted, is to replicate the first column to the next columns, until this value is not NaN. Let me show you an example of what it should look like:

```<code>Periods                0      1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16     17     18     19
Item 1               89.0   89.0   89.0   89.0   89.0   89.0   89.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 2               197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 3               105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0
</code>```

But I can't figure out a way to do this. I wish i could post some code, but all I tried was to search for those methods: backfill, ffill. None of them looked like what I needed.

Any ideas? Thanks in advance.

答:
Here's another idea, just for the record: using map:

```<code>df.iloc[0] = df.iloc[0].notna().map({True: df.iloc[0, 0]})
</code>```

Body:
I have the following dataframe:

Periods            0      1      2      3      4      5      6      7     8     9     10    11    12   13   14   15   16   17   18   19
Item 1           89.0   89.0   88.0   86.0   73.0   73.0   67.0    NaN   NaN   NaN   NaN   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 2          197.0  197.0  157.0  157.0  156.0  156.0  153.0  153.0   3.0   3.0   2.0   NaN   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Item 3          105.0  105.0   98.0   47.0   40.0   21.0   20.0   15.0  13.0  11.0  11.0  11.0  10.0  7.0  7.0  5.0  5.0  3.0  2.0  1.0

It has several NaNs, and columns from a range between 0 - 20. What i wanted, is to replicate the first column to the next columns, until this value is not NaN. Let me show you an example of what it should look like:

Periods                0      1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16     17     18     19
Item 1               89.0   89.0   89.0   89.0   89.0   89.0   89.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 2               197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0  197.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
Item 3               105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0  105.0

But I can't figure out a way to do this. I wish i could post some code, but all I tried was to search for those methods: backfill, ffill. None of them looked like what I needed.

Any ideas? Thanks in advance.

Body:
Here's another idea, just for the record: using map:

df.iloc[0] = df.iloc[0].notna().map({True: df.iloc[0, 0]})


答:
I will do mul

```<code>df.notna().mul(df.iloc[:,0],axis=0).mask(df.isna())
</code>```

Title: Replace all non NaN values with the initial value per row

Body:
I will do mul

df.notna().mul(df.iloc[:,0],axis=0).mask(df.isna())


问:
Extract number of the institutional holding that a stock has
I'm trying to extract the number of the institutional holding that a stock has.

For instance, here from Apple at the following link

https://finance.yahoo.com/quote/AAPL/holders?p=AAPL)

Extract a number

I would like to get the number 5,102 from:

```<code> "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}
</code>```

I think this is a tulip right?

Code

This is the code so far:

```<code>import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla/5.0'}

url = 'https://finance.yahoo.com/quote/AAPL/holders?p=AAPL'

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
</code>```

What I tried

I tried to use yfinance but I don't know how to make a loop to extract all the holders for each ticker. So I though would be more easy to do a web scraping for one and then looping for each stock.

答:
Using yfinance

Try the module yfinance (an API facade, client library to Yahoo! Finance). Some research here on SO shows how:

Retrieve company name with ticker symbol input, yahoo or google API

Then adjust to your case and play around:

```<code>import yfinance as yf

stock = yf.Ticker('APPL')
print(stock.info)
</code>```

Prints the retrieved JSON data stock.info as a dict:

```<code>{'symbol': 'APPL', 'quoteType': 'MUTUALFUND', 'exchange': 'YHD', 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EST', 'gmtOffSetMilliseconds': '-18000000', 'market': 'us_market', 'isEsgPopulated': False, 'quoteSourceName': 'Delayed Quote', 'regularMarketOpen': None, 'averageDailyVolume3Month': None, 'regularMarketTime': 1561759658, 'volume24Hr': None, 'regularMarketDayHigh': None, 'shortName': None, 'averageDailyVolume10Day': None, 'longName': None, 'regularMarketChange': None, 'regularMarketPreviousClose': None, 'preMarketPrice': None, 'exchangeDataDelayedBy': 0, 'toCurrency': None, 'postMarketChange': None, 'postMarketPrice': None, 'exchangeName': 'YHD', 'preMarketChange': None, 'circulatingSupply': None, 'regularMarketDayLow': None, 'priceHint': 2, 'regularMarketPrice': None, 'regularMarketVolume': None, 'lastMarket': None, 'regularMarketSource': 'DELAYED', 'openInterest': None, 'marketState': 'POST', 'underlyingSymbol': None, 'marketCap': None, 'volumeAllCurrencies': None, 'strikePrice': None, 'maxAge': 1, 'fromCurrency': None, 'logo_url': ''}
</code>```

However, there is no institution or any other count resembling your information-demand (given number 5,102) like on the screenshot from Yahoo! Finance page of AAPL:

Research on the desired figure

I searched the web for Number of Institutions Holding Shares and  yfinance and found an article explaining it:

Medium: All you need to know about yfinance : Yahoo! Finance Library | by Abhijith Chandradas | Nerd For Tech

Ticker.major_holders and Ticker.institutional_holders can be used to get details of shareholding of the company.

major_holders: shows how much of the shares and float are held by the insiders and institutions

Ticker.institutional_holders provides the details of major institutioal shareholding.

Retrieve information about holders using yfinance

```<code>import yfinance as yf

appl = yf.Ticker('APPL')

full_name = appl.info['longName']
major_holders = appl.major_holders
institutional_holders = appl.institutional_holders

print(f"Name:\n{full_name}")
print(f"Major holders:\n{major_holders}")
print(f"Institutional holders:\n{institutional_holders}")
</code>```

Prints what is expected to hold the desired number:

```<code>Name:
None
Major holders:
                         0   1
0           Previous Close NaN
1               YTD Return NaN
2      Expense Ratio (net) NaN
3                 Category NaN
4            Last Cap Gain NaN
5       Morningstar Rating NaN
6  Morningstar Risk Rating NaN
7    Sustainability Rating NaN
Institutional holders:
                      0   1
0            Net Assets NaN
1     Beta (5Y Monthly) NaN
2                 Yield NaN
3     5y Average Return NaN
4     Holdings Turnover NaN
5         Last Dividend NaN
6  Average for Category NaN
7        Inception Date NaN
</code>```

Now it is left to you to figure out, why there is no data available for APPL.

Test also the ticker symbol AMZN and see if the example outputs from Medium article can be reproduced with figures available

Parsing JSON an extracting a value

Given you have this JSON:

 "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}
```
<p>Then you can parse it using Pythons standard module <code>json</code>:</p>
```import json

json_text = """
 "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}
"""
obj = json.loads('{'+json_text+'}')  # surrounding braces needed to make it a valid JSON (object)
print(obj['institutionsCount']['longFmt'])
# 5,102
```

Body:
I'm trying to extract the number of the institutional holding that a stock has.

For instance, here from Apple at the following link

https://finance.yahoo.com/quote/AAPL/holders?p=AAPL)

Extract a number

I would like to get the number 5,102 from:

 "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}

I think this is a tulip right?

Code

This is the code so far:

import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla/5.0'}

url = 'https://finance.yahoo.com/quote/AAPL/holders?p=AAPL'

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')

What I tried

I tried to use yfinance but I don't know how to make a loop to extract all the holders for each ticker. So I though would be more easy to do a web scraping for one and then looping for each stock.

Body:
Using yfinance

Try the module yfinance (an API facade, client library to Yahoo! Finance). Some research here on SO shows how:

Retrieve company name with ticker symbol input, yahoo or google API

Then adjust to your case and play around:

import yfinance as yf

stock = yf.Ticker('APPL')
print(stock.info)

Prints the retrieved JSON data stock.info as a dict:

{'symbol': 'APPL', 'quoteType': 'MUTUALFUND', 'exchange': 'YHD', 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EST', 'gmtOffSetMilliseconds': '-18000000', 'market': 'us_market', 'isEsgPopulated': False, 'quoteSourceName': 'Delayed Quote', 'regularMarketOpen': None, 'averageDailyVolume3Month': None, 'regularMarketTime': 1561759658, 'volume24Hr': None, 'regularMarketDayHigh': None, 'shortName': None, 'averageDailyVolume10Day': None, 'longName': None, 'regularMarketChange': None, 'regularMarketPreviousClose': None, 'preMarketPrice': None, 'exchangeDataDelayedBy': 0, 'toCurrency': None, 'postMarketChange': None, 'postMarketPrice': None, 'exchangeName': 'YHD', 'preMarketChange': None, 'circulatingSupply': None, 'regularMarketDayLow': None, 'priceHint': 2, 'regularMarketPrice': None, 'regularMarketVolume': None, 'lastMarket': None, 'regularMarketSource': 'DELAYED', 'openInterest': None, 'marketState': 'POST', 'underlyingSymbol': None, 'marketCap': None, 'volumeAllCurrencies': None, 'strikePrice': None, 'maxAge': 1, 'fromCurrency': None, 'logo_url': ''}

However, there is no institution or any other count resembling your information-demand (given number 5,102) like on the screenshot from Yahoo! Finance page of AAPL:

Research on the desired figure

I searched the web for Number of Institutions Holding Shares and  yfinance and found an article explaining it:

Medium: All you need to know about yfinance : Yahoo! Finance Library | by Abhijith Chandradas | Nerd For Tech

Ticker.major_holders and Ticker.institutional_holders can be used to get details of shareholding of the company.

major_holders: shows how much of the shares and float are held by the insiders and institutions

Ticker.institutional_holders provides the details of major institutioal shareholding.

Retrieve information about holders using yfinance

import yfinance as yf

appl = yf.Ticker('APPL')

full_name = appl.info['longName']
major_holders = appl.major_holders
institutional_holders = appl.institutional_holders

print(f"Name:\n{full_name}")
print(f"Major holders:\n{major_holders}")
print(f"Institutional holders:\n{institutional_holders}")

Prints what is expected to hold the desired number:

Name:
None
Major holders:
                         0   1
0           Previous Close NaN
1               YTD Return NaN
2      Expense Ratio (net) NaN
3                 Category NaN
4            Last Cap Gain NaN
5       Morningstar Rating NaN
6  Morningstar Risk Rating NaN
7    Sustainability Rating NaN
Institutional holders:
                      0   1
0            Net Assets NaN
1     Beta (5Y Monthly) NaN
2                 Yield NaN
3     5y Average Return NaN
4     Holdings Turnover NaN
5         Last Dividend NaN
6  Average for Category NaN
7        Inception Date NaN

Now it is left to you to figure out, why there is no data available for APPL.

Test also the ticker symbol AMZN and see if the example outputs from Medium article can be reproduced with figures available

Parsing JSON an extracting a value

Given you have this JSON:

 "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}

Then you can parse it using Pythons standard module json:

import json

json_text = """
 "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}
"""
obj = json.loads('{'+json_text+'}')  # surrounding braces needed to make it a valid JSON (object)
print(obj['institutionsCount']['longFmt'])
# 5,102


问:
Spring-MVC bean class cannot be found
In my build.xml, I set the attribute scr.dir:

```<code><property name="src.dir" value="${backend.dir}/java-src/catw/src"/>
</code>```

My dispatcher-servlet.xml:

```<code><bean name="/welcome.htm" class="com.bamboo.catW3.business.impl.WelcomeController"/>
</code>```

My view WEB-INF/jsp:

```<code>welcome.jsp
</code>```

My controller:

```<code>com.bamboo.catW3.business.impl.WelcomeController.java
</code>```

I run the project and show me this message:

```<code>org.springframework.beans.factory.CannotLoadBeanClassException:
Cannot find class [com.bamboo.catW3.business.impl.WelcomeController] for bean
with name '/welcome.htm' defined in ServletContext resource
[/WEB-INF/branch_try_htmlModulo-servlet.xml]; nested exception is
java.lang.ClassNotFoundException: com.bamboo.catW3.business.impl.WelcomeController
    org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1076)
</code>```

I don't know how to fix this error, can anyone help me please?

答:
May be many of u r getting problem with springhelloworld project.I have recently faced that problem as from eclipse when i am running it,it's working fine..but from browser it is showing error like class not found exception.So,I have found solution for that...it is a problem of class file....

Solution:

Just put your classes folder from build/classes to your WEB-INF directory...and your problem will be solved...

I hope this will help you...

ContentLicense: CC BY-SA 2.5

Title: Spring-MVC bean class cannot be found

Body:
In my build.xml, I set the attribute scr.dir:

<property name="src.dir" value="${backend.dir}/java-src/catw/src"/>

My dispatcher-servlet.xml:

<bean name="/welcome.htm" class="com.bamboo.catW3.business.impl.WelcomeController"/>

My view WEB-INF/jsp:

welcome.jsp

My controller:

com.bamboo.catW3.business.impl.WelcomeController.java

I run the project and show me this message:

org.springframework.beans.factory.CannotLoadBeanClassException:
Cannot find class [com.bamboo.catW3.business.impl.WelcomeController] for bean
with name '/welcome.htm' defined in ServletContext resource
[/WEB-INF/branch_try_htmlModulo-servlet.xml]; nested exception is
java.lang.ClassNotFoundException: com.bamboo.catW3.business.impl.WelcomeController
    org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1076)

I don't know how to fix this error, can anyone help me please?

ContentLicense: CC BY-SA 3.0


问:
How can I create columns with type Date and type DateTime in nestjs with typeORM?
I am new with nestjs. How can I set columns that accepts Date format and dateTime format?

Not in both cases, the columns are two differents column, one accept Date and other dateTime.

答:
To add more to this ticket as DateTime was not even mentioned:

  /**
   * Start DateTime
   */
  @Column({
    type: 'datetime',
    default: () => 'NOW()',
  })
  @Index()
  start: string;

  /**
   * End DateTime
   */
  @Column({
    type: 'datetime',
    nullable: true,
  })
  @Index()
  end: string;
```

This is for those not wanting or needing to use

@CreateDateColumn()

@UpdateDateColumn()

Body:
To add more to this ticket as DateTime was not even mentioned:

  /**
   * Start DateTime
   */
  @Column({
    type: 'datetime',
    default: () => 'NOW()',
  })
  @Index()
  start: string;

  /**
   * End DateTime
   */
  @Column({
    type: 'datetime',
    nullable: true,
  })
  @Index()
  end: string;

This is for those not wanting or needing to use

@CreateDateColumn()

@UpdateDateColumn()


问:
"No encode delegate" error with GraphicsMagick
I'm encountering an error during conversion of a PDF file to a PNG image.

The error is:

Command failed: gm convert: No encode delegate for this image format (PNG) [No such file or directory].:

The code which opens the PDF and makes the image looks like:

```<code>gm((file_path + file_name))

    .size(async (err, size) => {

        if (!err) {

            if (size.width > options.width) {

                gm((file_path + file_name))

                    .resize(options.width)

                    .setFormat('png')

                    .autoOrient()

                    .noProfile()

                    .write((file_path + file_name_thumb), async (err) => {

                        if (!err) {

                            return resolve({
                                file_path,
                                file_name: file_name_thumb
                            });

                        } else {

                            await std.log('Error caught in image_advanced.thumb().', file_path, file_name, options, err);

                            return reject(err);

                        }

                    });

            } else {

                await fs.copyFileSync((file_path + file_name), (file_path + file_name_thumb));

                return resolve({
                    file_path,
                    file_name: file_name_thumb
                });

            }

        } else {

            await std.log('ERROR: No thumb returned in image_advanced.thumb().', file_path, file_name, options, err);

            return reject(err);

        }

    });
</code>```

I believe I do have the delegates loaded and configured correctly.

When I run a configure on the instance, I see this output table:

This appears to indicate that PDF and PNG are supported/enabled.

This is an Amazon EC2 Linux 2 instance.

In reality, getting GraphicsMagick installed and configured was not easy so, like many others, I may have installed enabled more than one version and perhaps that's my issue?

答:
So, now it's all working without any code changes above.

If I had to hazard a very uneducated guess, it's b/c I ran another configure. It was the same as the last one b/c I used the up arrow in the shell:

./configure --with-png=yes --with-jpg=yes

Anyway, the code above CAN AND DOES convert all of the files I need (GIF, PNG, JPG, PDF) to PNG. For those of you pulling your hair out for a conversion solution, please try this code.

Oh and big props to the wizard behind the GM curtain who probably doesn't get near enough love: Bob Friesenhahn!

Body:
I'm encountering an error during conversion of a PDF file to a PNG image.

The error is:

Command failed: gm convert: No encode delegate for this image format (PNG) [No such file or directory].:

The code which opens the PDF and makes the image looks like:

gm((file_path + file_name))

    .size(async (err, size) => {

        if (!err) {

            if (size.width > options.width) {

                gm((file_path + file_name))

                    .resize(options.width)

                    .setFormat('png')

                    .autoOrient()

                    .noProfile()

                    .write((file_path + file_name_thumb), async (err) => {

                        if (!err) {

                            return resolve({
                                file_path,
                                file_name: file_name_thumb
                            });

                        } else {

                            await std.log('Error caught in image_advanced.thumb().', file_path, file_name, options, err);

                            return reject(err);

                        }

                    });

            } else {

                await fs.copyFileSync((file_path + file_name), (file_path + file_name_thumb));

                return resolve({
                    file_path,
                    file_name: file_name_thumb
                });

            }

        } else {

            await std.log('ERROR: No thumb returned in image_advanced.thumb().', file_path, file_name, options, err);

            return reject(err);

        }

    });

I believe I do have the delegates loaded and configured correctly.

When I run a configure on the instance, I see this output table:

This appears to indicate that PDF and PNG are supported/enabled.

This is an Amazon EC2 Linux 2 instance.

In reality, getting GraphicsMagick installed and configured was not easy so, like many others, I may have installed enabled more than one version and perhaps that's my issue?


问:
Typescript: Model driven and Type safe Specification with autocomplete?
I found this $SPEC tagged template literal prototype

function $SPEC<Keys extends string[]>([result, ...parts]: TemplateStringsArray, ...keys: Keys) {

  return (params: { [K in Keys[number]]: string }) =>

    keys.reduce((acc, key: keyof typeof params, i) => acc + params[key] + parts[i], result)

}
```
<p>It has possibility to "interpolate" a Specification in markdown - with ${<code>Data</code>}</p>
<pre class="lang-js prettyprint-override"><code>const TestScenario = $SPEC `

# Feature XY
>> As ${`role`} I want XY because of benefit ...

Scenario:
  - given ${`Entity 1`} ...
  - when ...
  - then ...

`
</code>```

And so far this "interpolation driven" Specification is "somehow" Type safe and with autocomplete - but for Data only.

const TestCase  = TestScenario({ // Test `Data`

        'role': `Editor`,
        'Entity 1': `example 1`

})
```
<p>current type safety and autocomplete</p>
<p>Typescript Playground</p>
<p>HOW can I go further with Type safe and autocomplete - for $SPEC - to be even MORE "MODEL DRIVEN" ?</p>
<p>GOALS:</p>
<ul>
<li>for a collective of Analysts and Testers (with minimal coding skills)</li>
<li>I am looking for MINIMAListics TYPESCRIPT SYNTAX and implementation (see prototype above)</li>
<li>wanted syntax for intersectional $SPECification should be: (Domain) MODEL DRIVEN & TYPE SAFE (against model/s) & WITH intellisense / AUTOCOMPLETE (productivity)</li>
</ul>
<p>TERMINOLOGY:</p>
<ul>
<li>it appears that an Analyst and Tester Specifications have intersections at least in:
<ul>
<li>Domain terms - elements from the Model/s</li>
<li>and Scenarios - TestCase is usually based on a scenario from UseCase / UserStory + adds TestData via domain EXAMPLES (according to Model)</li>
</ul>
</li>
</ul>
<p>CONCEPT + WORKFLOW SAMPLE:</p>
<pre class="lang-js prettyprint-override"><code>
// sorry - this is only pseudocode (I'm just starting with Typescript and I don't know the relevant syntax, so I'm introducing "alternative syntax" where possible :)

// 1. DomainModels.ts - via Typescript Interfaces - from @Analyst

type Attribute = {}; type Action = {}; // structure is not important for now :)

interface role {}
interface Repository1 {}
interface Entity2 {
  'Simple att3': Attribute
  'Complex att4': {
    'Att5': Attribute
    // ...
  }
  'Action N': Action
}

// 2. Specifications.md.ts - via markdown, wrapped in MINIMAList Typescript - from @Anlayst and @Tester also

// declare function $SPEC (...) ...
const UseCase =  $SPEC
const TestScenario = $SPEC

// ... probably irrelevant syntax
const UC1 = UseCase<{role, Repository1, Entity2}>
`
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvv
>> vvvvvvvv ${`role`} vvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvv
- vv ${`Repository1`} vvvvvvvvvv ${`Entity2.Simple att3`} vvv
- vvvvvvv ${`Entity2.Action N`} vvvvvvvvvvvvv vvvvvvvvvvvvvvvv
`

// ... other syntax alternatives ?
// const TS2 = TestScenario<[role, Repository1, Entity2]> `...`
// const Scenario3 = $SPEC<role | Repository1 | Entity2> `...`

// ALL "syntaxes / alternatives" only TRY to "DELIVER" MODELS TO $SPEC

// ... or this alternative would be nice - has "shortcuts" for "models" :)
const Scenario4 = $SPEC( (r: role, rep: Repository1, e: Partial<Entity2>) => `
>> vvvvvvvv ${r} vvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvv
- vv ${rep} vvvvvvvvvv ${e['Simple att3']} vvv
- vvvvvvv ${e['Action N']} vvvvvvvvvvvvv vvvvvvvvvvvvvvvv
` )

// 3. Examples.ts - via Typescript call of $SPEC() "aliases" - from @Tester

const TC4_1 = Scenario4( // again, exact structure of some parameters is not important for now :)
  {}, // r:   role
  {}, // rep: repository
  {   // e:   Partial<Entity2>
    'Simple att3': 'example 1',
    'Action N': () => {}
  }
)
</code>```

So please, can you advise YOUR MINIMAList Typescript SYNTAX (and implementation if possible) FOR the GIVEN CONCEPT ???

Or do you know some framework / library / tool like this or close to concept of "Model Driven Type safe Specification" ???
(I know about Cucumber and Gauge, they are close, but not exactly what I'm looking for)

I will be grateful for any suggestions or opinions - they are very welcome.

THANK YOU (if you read to this point - I couldn't cut it :)

答:
thanks to @jcalz there is this solution:

type _K2O<K extends string, V = unknown> =
K extends `${infer F}.${infer R}` ? { [P in F]: _K2O<R, V> } : { [P in K]: V }

type DeepMerge<T> = { [K in keyof T]: DeepMerge<T[K]> } extends infer O ? { [K in keyof O]: O[K] } : never;

type KeyToObject<K extends string, V = unknown> = (K extends unknown ? (x: _K2O<K, V>) => void : never) extends
  (x: infer O) => void ? DeepMerge<O> : never;

type DotPrefix<T extends string> = T extends "" ? "" : `.${T}`

type DotNestedKeys<T> = (T extends object ?
  { [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<DotNestedKeys<T[K]>>}` }[Exclude<keyof T, symbol>]
  : "") extends infer D ? Extract<D, string> : ''; // here I intuitively changed : never to : '', because of problem with next split()

function $SPEC<M>() {
  return <Keys extends DotNestedKeys<M>[]>([result, ...parts]: TemplateStringsArray, ...keys: Keys) => {
    return (params: KeyToObject<Keys[number], string>): string =>
      keys.reduce((acc, key, i) => acc + (key.split(".").reduce<any>((o, k) => o[k], params)) + parts[i], result)
  }
}
```
<pre class="lang-js prettyprint-override"><code>
// 1. DomainModels.ts

interface Entity2 {
  'Simple att3': string
  'Complex att4': {
    'Att5': string
    // ...
  }
  'Action N': string
}

// 2. Specifications.md.ts

const TestScenario = $SPEC;

const TS1 = TestScenario<{role: string, entity2: Entity2}>()
`
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvv
>> vvvvvvvv ${`role`} vvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvv
- vvvvvvvvvvvv ${`entity2.Simple att3`} vvvvvvvvvvvvvv
- vvvvvvv ${`entity2.Action N`} vvvvvvvvvvvvv vvvvvvvvvvvvvvvv
`

// 3. Examples.ts

TS1({ // TestCase aka Example = [TestScenario, TestData]
  role: `Editor`,
  entity2: {
    'Simple att3': `example 1`,
    'Action N': `exmple 2`
  }
})
</code>```

$SPEC resp. TestScenario resp. TS1 now also has autocomplete and is interface aka model driven

Body:
I found this $SPEC tagged template literal prototype

function $SPEC<Keys extends string[]>([result, ...parts]: TemplateStringsArray, ...keys: Keys) {

  return (params: { [K in Keys[number]]: string }) =>

    keys.reduce((acc, key: keyof typeof params, i) => acc + params[key] + parts[i], result)

}

It has possibility to "interpolate" a Specification in markdown - with ${Data}

const TestScenario = $SPEC `

# Feature XY
>> As ${`role`} I want XY because of benefit ...

Scenario:
  - given ${`Entity 1`} ...
  - when ...
  - then ...

`

And so far this "interpolation driven" Specification is "somehow" Type safe and with autocomplete - but for Data only.

const TestCase  = TestScenario({ // Test `Data`

        'role': `Editor`,
        'Entity 1': `example 1`

})

current type safety and autocomplete

Typescript Playground

HOW can I go further with Type safe and autocomplete - for $SPEC - to be even MORE "MODEL DRIVEN" ?

GOALS:

for a collective of Analysts and Testers (with minimal coding skills)

I am looking for MINIMAListics TYPESCRIPT SYNTAX and implementation (see prototype above)

wanted syntax for intersectional $SPECification should be: (Domain) MODEL DRIVEN & TYPE SAFE (against model/s) & WITH intellisense / AUTOCOMPLETE (productivity)

TERMINOLOGY:

it appears that an Analyst and Tester Specifications have intersections at least in:

Domain terms - elements from the Model/s

and Scenarios - TestCase is usually based on a scenario from UseCase / UserStory + adds TestData via domain EXAMPLES (according to Model)

CONCEPT + WORKFLOW SAMPLE:

// sorry - this is only pseudocode (I'm just starting with Typescript and I don't know the relevant syntax, so I'm introducing "alternative syntax" where possible :)

// 1. DomainModels.ts - via Typescript Interfaces - from @Analyst

type Attribute = {}; type Action = {}; // structure is not important for now :)

interface role {}
interface Repository1 {}
interface Entity2 {
  'Simple att3': Attribute
  'Complex att4': {
    'Att5': Attribute
    // ...
  }
  'Action N': Action
}

// 2. Specifications.md.ts - via markdown, wrapped in MINIMAList Typescript - from @Anlayst and @Tester also

// declare function $SPEC (...) ...
const UseCase =  $SPEC
const TestScenario = $SPEC

// ... probably irrelevant syntax
const UC1 = UseCase<{role, Repository1, Entity2}>
`
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvv
>> vvvvvvvv ${`role`} vvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvv
- vv ${`Repository1`} vvvvvvvvvv ${`Entity2.Simple att3`} vvv
- vvvvvvv ${`Entity2.Action N`} vvvvvvvvvvvvv vvvvvvvvvvvvvvvv
`

// ... other syntax alternatives ?
// const TS2 = TestScenario<[role, Repository1, Entity2]> `...`
// const Scenario3 = $SPEC<role | Repository1 | Entity2> `...`

// ALL "syntaxes / alternatives" only TRY to "DELIVER" MODELS TO $SPEC

// ... or this alternative would be nice - has "shortcuts" for "models" :)
const Scenario4 = $SPEC( (r: role, rep: Repository1, e: Partial<Entity2>) => `
>> vvvvvvvv ${r} vvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvv
- vv ${rep} vvvvvvvvvv ${e['Simple att3']} vvv
- vvvvvvv ${e['Action N']} vvvvvvvvvvvvv vvvvvvvvvvvvvvvv
` )

// 3. Examples.ts - via Typescript call of $SPEC() "aliases" - from @Tester

const TC4_1 = Scenario4( // again, exact structure of some parameters is not important for now :)
  {}, // r:   role
  {}, // rep: repository
  {   // e:   Partial<Entity2>
    'Simple att3': 'example 1',
    'Action N': () => {}
  }
)

So please, can you advise YOUR MINIMAList Typescript SYNTAX (and implementation if possible) FOR the GIVEN CONCEPT ???

Or do you know some framework / library / tool like this or close to concept of "Model Driven Type safe Specification" ???
(I know about Cucumber and Gauge, they are close, but not exactly what I'm looking for)

I will be grateful for any suggestions or opinions - they are very welcome.

THANK YOU (if you read to this point - I couldn't cut it :)

Body:
thanks to @jcalz there is this solution:

type _K2O<K extends string, V = unknown> =
K extends `${infer F}.${infer R}` ? { [P in F]: _K2O<R, V> } : { [P in K]: V }

type DeepMerge<T> = { [K in keyof T]: DeepMerge<T[K]> } extends infer O ? { [K in keyof O]: O[K] } : never;

type KeyToObject<K extends string, V = unknown> = (K extends unknown ? (x: _K2O<K, V>) => void : never) extends
  (x: infer O) => void ? DeepMerge<O> : never;

type DotPrefix<T extends string> = T extends "" ? "" : `.${T}`

type DotNestedKeys<T> = (T extends object ?
  { [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<DotNestedKeys<T[K]>>}` }[Exclude<keyof T, symbol>]
  : "") extends infer D ? Extract<D, string> : ''; // here I intuitively changed : never to : '', because of problem with next split()

function $SPEC<M>() {
  return <Keys extends DotNestedKeys<M>[]>([result, ...parts]: TemplateStringsArray, ...keys: Keys) => {
    return (params: KeyToObject<Keys[number], string>): string =>
      keys.reduce((acc, key, i) => acc + (key.split(".").reduce<any>((o, k) => o[k], params)) + parts[i], result)
  }
}

// 1. DomainModels.ts

interface Entity2 {
  'Simple att3': string
  'Complex att4': {
    'Att5': string
    // ...
  }
  'Action N': string
}

// 2. Specifications.md.ts

const TestScenario = $SPEC;

const TS1 = TestScenario<{role: string, entity2: Entity2}>()
`
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvv
>> vvvvvvvv ${`role`} vvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvv
- vvvvvvvvvvvv ${`entity2.Simple att3`} vvvvvvvvvvvvvv
- vvvvvvv ${`entity2.Action N`} vvvvvvvvvvvvv vvvvvvvvvvvvvvvv
`

// 3. Examples.ts

TS1({ // TestCase aka Example = [TestScenario, TestData]
  role: `Editor`,
  entity2: {
    'Simple att3': `example 1`,
    'Action N': `exmple 2`
  }
})

$SPEC resp. TestScenario resp. TS1 now also has autocomplete and is interface aka model driven


问:
How to get Max Value with in PySpark window function
My data Model is something like Below, trying to get MAX Value within WindowFrame, I am able to model the data but am not sure how to get max Value within Window Frame.

Expected output:

I am able to partition and rank, how to get max value(result column) with In Window Frame.

tried like this.

```<code>windowSpec  = Window.partitionBy("number").orderBy("version")
wdf=df.withColumn("rank", row_number().over(windowSpec))
wdf.show()
</code>```

Body:
My data Model is something like Below, trying to get MAX Value within WindowFrame, I am able to model the data but am not sure how to get max Value within Window Frame.

Expected output:

I am able to partition and rank, how to get max value(result column) with In Window Frame.

tried like this.

windowSpec  = Window.partitionBy("number").orderBy("version")
wdf=df.withColumn("rank", row_number().over(windowSpec))
wdf.show()

Body:
Use when function.

from pyspark.sql import functions as F
rowId = F.row_number().over(
    Window.partitionBy("number").orderBy(col("version").desc())
)

df
.withColumn("max_value",F.when( rowId == 1,F.lit("Y")).otherwise(F.lit("N")))
.show()

+---+------+-------+------+---------+
|id |number|version|status|max_value|
+---+------+-------+------+---------+
|102|335762|3      |N     |Y        |
|100|335762|2      |Y     |N        |
|105|47495 |1      |Y     |Y        |
|103|210752|12     |Y     |Y        |
|101|210752|2      |Y     |N        |
|106|210752|1      |Y     |N        |
|104|324916|2      |N     |Y        |
|107|324916|1      |Y     |N        |
+---+------+-------+------+---------+


问:
@MockK or mockk()
When using the Mockk for Android Unit tests, there is any difference of using the notation when declaring dependencies?

```<code>class Test {
    private val x: X = mockk()

    private val test = TestClass(x)
...
}
</code>```

or

```<code>class Test {
    @MockK
    private lateinit var x: X

    @InjectMockKs
    private lateinit var test: TestClass

    @Before
    fun setup() {
        MockKAnnotations.init(this)
    }
...
}
</code>```

答:
I'd recommend using mockk() and "naive" constructor dependencies injection in tests rather than annotations because of these two reasons:

The mockk() builder allows you to define immutable variables with val which is more safe, efficient & better* (in terms of software development at all), whereas with @Mockk you should use var keyword;

@InjectMockKs is not that cool as it seems. I worked on a project where I caught the same issue that Mockito has. My teammate removed one of the class dependencies somewhere in a middle of the constuctor arguments, built & ran the code, but forgot to fix & run tests locally. He pushed those changes, but then we got an error in our "Run Tests" pipeline stage which was pointed to nowhere, just NPE about missing class. We spent some extra time to finally find the issue, the thing is

Mockito will try to inject mocks only either by constructor injection, property injection or setter injection in order and as described below. If any of the following strategy fail, then Mockito won't report failure; i.e. you will have to provide dependencies yourself.

https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/InjectMocks.html

Title: @MockK or mockk()

Body:
When using the Mockk for Android Unit tests, there is any difference of using the notation when declaring dependencies?

class Test {
    private val x: X = mockk()

    private val test = TestClass(x)
...
}

or

class Test {
    @MockK
    private lateinit var x: X

    @InjectMockKs
    private lateinit var test: TestClass

    @Before
    fun setup() {
        MockKAnnotations.init(this)
    }
...
}


问:
switching between tabs menu by time
I'm new to HTML and I am trying to build a site. I have everything I want to display, but I need help clicking between tabs automatically.

Is it possible to switch between tabs every 5 mins?
Can anyone point me into the right direction or help me create the JS to do this?
Thank you in advance!!!

Picture of the Page:

```<code><!DOCTYPE html>
    <html>

    <head>

        <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1">
        <!-- <meta http-equiv="refresh" content="90"> -->
        <title>Plasma MFG Dashboard</title>

        <link href="css/style.css" rel="stylesheet" type="text/css" />
        <script src="js/jquery-1.7.2.min.js"></script>
        <style type="text/css">

        </style>
    </head>

    <body>
        <header>
            <h1>Plasma MFG Dashboard</h1>
        </header>
        <ul id="tabs">
            <li><a href="#" name="tab1">HOURLY WIP</a></li>
            <li><a href="#" name="tab2">LINE REPORT</a></li>

        </ul>
        <div id='content'>

            <div id="tab1">
                <iframe frameborder="0" scrolling="yes"
                    src="http://dm5ie.itg.ti.com/dm5ie/dashboard/DailyMetrics/DM5_InProcess_Hourly_ext.htm"
                    style="width:100%; height:3000px; -ms-zoom: .995; -webkit-transform: scale(.995); -webkit-transform-origin: 0 0; -o-transform: scale(0.995); -o-transform-origin: 0 0;"></iframe>
            </div>

            <div id="tab2">
                <iframe id="lineReport" frameborder="0" scrolling="yes" src="" style="width:100%; height:550px;  "></iframe>

            </div>

        </body>
        <footer>
            <br>

        </footer>
        <script src="js/jquery-1.7.2.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#content").find("[id^='tab']").hide(); // Hide all content
                $("#tabs li:first").attr("id", "current"); // Activate the first tab
                $("#content #tab1").fadeIn(); // Show first tab's content

                $('#tabs a').click(function (e) {
                    e.preventDefault();
                    if ($(this).closest("li").attr("id") == "current") { //detection for current tab
                        return;
                    } else {
                        $("#content").find("[id^='tab']").hide(); // Hide all content
                        $("#tabs li").attr("id", ""); //Reset id's
                        $(this).parent().attr("id", "current"); // Activate this
                        $('#' + $(this).attr('name')).fadeIn(); // Show content for the current tab
                    }
                });
                $(window).scroll(function () {
                    console.log($(window).scrollTop())
                    if ($(window).scrollTop() > 90) {
                        $('#tabs').addClass('navbar-fixed');
                    }
                    if ($(window).scrollTop() < 91) {
                        $('#tabs').removeClass('navbar-fixed');
                    }
                });
            });
            const getDate = () => {
                const newDate = new Date();
                const year = newDate.getFullYear();
                const month = newDate.getMonth() + 1;
                const d = newDate.getDate();

                return `${month.toString().padStart(2, '0')}%2F${d.toString().padStart(2, '0')}%2F${year}`;
            }

            document.getElementById('lineReport').src =
                'http://linereport.sc.ti.com/flowMgmt/AppServlet?facility=DP1DM5&summary=module&customer=ALL&device_group=ALL&archive_date='
                .concat(getDate()) +
                '&realTime=Y&outtype=excel&action=getFlowData&jspURL=flowMgmtSummaryDisplay.jsp&uLogReportName=FlowMgmt&uLogKey1=SummaryLevel&excel=false&uLogValue1=Module';
        </script>

        </html>
</code>```

答:
HTML-part

Add to your
 the class
.

JS-part:

Then simply bind a click handler to each of the ...:

```<code>foreach(document.getElementsByClassName('tab') as tab){
   tab.addEventListener("click", function(){
       var targetTab=this.getAttribute('name');
       // add class 'active' to targetTab
       // and remove class 'active' from every other tab
   }
}
</code>```

CSS-part

Than inside your .css set the class .tab-content to display:none; and add to your css a class .active with display:block;

After this call a click event on the given buttons each 5 minutes.

Title: switching between tabs menu by time

Body:
I'm new to HTML and I am trying to build a site. I have everything I want to display, but I need help clicking between tabs automatically.

Is it possible to switch between tabs every 5 mins?
Can anyone point me into the right direction or help me create the JS to do this?
Thank you in advance!!!

Picture of the Page:

<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1">

        <title>Plasma MFG Dashboard</title>

        <link href="css/style.css" rel="stylesheet" type="text/css" />

Plasma MFG Dashboard

HOURLY WIP

LINE REPORT

Body:
HTML-part

Add to your <div id="tabXY"> the class <div id="tabXY" class="tab-content">.

JS-part:

Then simply bind a click handler to each of the <a href="#" name="tab">...</a>:

foreach(document.getElementsByClassName('tab') as tab){
   tab.addEventListener("click", function(){
       var targetTab=this.getAttribute('name');
       // add class 'active' to targetTab
       // and remove class 'active' from every other tab
   }
}

CSS-part

Than inside your .css set the class .tab-content to display:none; and add to your css a class .active with display:block;

After this call a click event on the given buttons each 5 minutes.


问:
Comet Javascript error
I'm using Orbited as a Comet server on localhost. It is listening to ports:

```<code>9000 for http
61613 for stomp
</code>```

My JavaScript debugger is reporting error: JSON is not defined in the line:

```<code>var vals = JSON.parse(payload);
</code>```

What could be the cause and how do I resolve this issue?

答:
The JSON library is not built into Javascript. You must include a javascript JSON library. If you use the one I linked, your code should work.

Alternatively, since JSON is a subset of Javascript object literals, you may be able to do this:

```<code>var vals = eval('(' + payload + ')');
</code>```

OwnerDisplayName: Alex

Title: Comet Javascript error

Body:
I'm using Orbited as a Comet server on localhost. It is listening to ports:

9000 for http
61613 for stomp

My JavaScript debugger is reporting error: JSON is not defined in the line:

var vals = JSON.parse(payload);

What could be the cause and how do I resolve this issue?

LastEditorDisplayName: David Locke

Body:
The JSON library is not built into Javascript. You must include a javascript JSON library. If you use the one I linked, your code should work.

Alternatively, since JSON is a subset of Javascript object literals, you may be able to do this:

var vals = eval('(' + payload + ')');

OwnerDisplayName: Triptych


问:
Extract a particular div from string
suppose a huge text data is stored in string variable like

```<code><form method="post" action="../Dialog.aspx" id="ctl00">
    <div class="aspNetHidden">
        <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUBMGRkcTeMEXjXlquwdmAmnkFVfUymwaaSdYr/CV1hV+mxr6A=" />
</div>

<div id="frm">
    <table class="form" border="0"  cellpadding="0">
        <tr>
            <td class="labeltag">Name:</td>
            <td class="inputtd">
                <input name="ctl01$txtName" type="text" maxlength="100" id="ctl01_txtName" class="inputfield" />
            </td>
        </tr>
        <tr>
            <td class="labeltag">Subject:</td>
            <td class="inputtd">
                 <input name="ctl01$txtSubjectject" type="text" maxlength="100" id="ctl01_txtSubjectject" class="inputfield" />
            </td>
        </tr>
        <tr>
            <td class="labeltag">Email:</td>
            <td class="inputtd">
                <input name="ctl01$txtEmail" type="text" maxlength="100" id="ctl01_txtEmail" class="inputfield" />
            </td>
        </tr>
        <tr>
            <td class="textfield" colspan="2">
                Message:
                <div class="messagefield">
                    <textarea name="ctl01$txtmessage" rows="7" cols="33" id="ctl01_txtmessage" class="message">
                    </textarea>
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="ctl01$btnSubmit" value="Submit" id="ctl01_btnSubmit" class="button" />
                <input type="submit" name="ctl01$btnCancel" value="Cancel" id="ctl01_btnCancel" class="button" />
        </td>
        </tr>
        <tr>
            <td colspan="2" style="height:10px"></td>
        </tr>
        <tr>
            <td colspan="2">
                <div class="bottomline" id="loader">

                </div>
            </td>
        </tr>
    </table>
</div>
<div class="aspNetHidden">
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBwKni+1oAuj1kf0MAoWeuckCAqCHyBsC34bOwQQC1cvcnQsC67K1+giML7QhoV19G+plAUvDQ7ade0566ipNfJ+BXR02JW5IIQ==" />
</div>
</code>```

from the above data i just need to extract a particlular div having is called "frm" .

so the whole div and its content will be extracted. i know this can be done with regex but i dont know which patter will work in my case.

i use the code to extract a particular div like

```<code> Regex search_string = new Regex("<div.*?id=\"frm\".*?>.*</div>");
        Match match = search_string.Match(outputToReturn);
        string section = match.Groups[0].Value;
</code>```

but section has nothing....match not found. so how to do it.
so please help. thanks

答:
It looks like your string contains html document. In this case you really should use an HTML parser (there are plenty depending on the language).
One that I know of is HtmlAgilityPack.</p>

Title: Extract a particular div from string

Body:
suppose a huge text data is stored in string variable like

<form method="post" action="../Dialog.aspx" id="ctl00">

        <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUBMGRkcTeMEXjXlquwdmAmnkFVfUymwaaSdYr/CV1hV+mxr6A=" />

            Name:

                <input name="ctl01$txtName" type="text" maxlength="100" id="ctl01_txtName" class="inputfield" />

            Subject:

                 <input name="ctl01$txtSubjectject" type="text" maxlength="100" id="ctl01_txtSubjectject" class="inputfield" />

            Email:

                <input name="ctl01$txtEmail" type="text" maxlength="100" id="ctl01_txtEmail" class="inputfield" />

                Message:

                    <textarea name="ctl01$txtmessage" rows="7" cols="33" id="ctl01_txtmessage" class="message">
                    </textarea>

                <input type="submit" name="ctl01$btnSubmit" value="Submit" id="ctl01_btnSubmit" class="button" />
                <input type="submit" name="ctl01$btnCancel" value="Cancel" id="ctl01_btnCancel" class="button" />

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBwKni+1oAuj1kf0MAoWeuckCAqCHyBsC34bOwQQC1cvcnQsC67K1+giML7QhoV19G+plAUvDQ7ade0566ipNfJ+BXR02JW5IIQ==" />

from the above data i just need to extract a particlular div having is called "frm" .

so the whole div and its content will be extracted. i know this can be done with regex but i dont know which patter will work in my case.

i use the code to extract a particular div like

 Regex search_string = new Regex("
.*
");
        Match match = search_string.Match(outputToReturn);
        string section = match.Groups[0].Value;

but section has nothing....match not found. so how to do it.
so please help. thanks


问:
Solr /admin/luke requests sometimes return nulls
I'm trying to get some metadata (document count and last modified date) from Solr, and found /solr/<core>/admin/luke endpoint to do it.

However, my requests sometimes return nulls instead of values. I can reproduce it via both SolrJ and curl:

✗ curl hostname/solr/core_name/admin/luke -s | jq '.index.lastModified'

"2019-06-04T19:59:45.617Z"

✗ curl hostname/solr/core_name/admin/luke -s | jq '.index.lastModified'

null

Without jq results are either:

```<code>{
  "responseHeader":{
    "status":0,
    "QTime":2},
  "index":{
    "numDocs":11,
    "maxDoc":11,
    "deletedDocs":0,
    "indexHeapUsageBytes":-1,
    "version":6,
    "segmentCount":1,
    "current":true,
    "hasDeletions":false,
    "directory":"org.apache.lucene.store.NRTCachingDirectory:NRTCachingDirectory(MMapDirectory@ ... lockFactory=org.apache.lucene.store.NativeFSLockFactory@2846d2cf; maxCacheMB=48.0 maxMergeSizeMB=4.0)",
    "segmentsFile":"segments_1",
    "segmentsFileSizeInBytes":-1,
    "userData":{
      "commitTimeMSec":"1559730066881",
      "commitCommandVer":"1635495514608762880"},
    "lastModified":"2019-06-05T10:21:06.881Z"},
  "fields":{ .... },
  "info":{ .... }
}
</code>```

or:

```<code>{
  "responseHeader":{
    "status":0,
    "QTime":2},
  "index":{
    "numDocs":11,
    "maxDoc":11,
    "deletedDocs":0,
    "indexHeapUsageBytes":-1,
    "version":4,
    "segmentCount":1,
    "current":false,
    "hasDeletions":false,
    "directory":"org.apache.lucene.store.NRTCachingDirectory:NRTCachingDirectory(MMapDirectory@ .... lockFactory=org.apache.lucene.store.NativeFSLockFactory@1e10c435; maxCacheMB=48.0 maxMergeSizeMB=4.0)",
    "segmentsFile":"segments_1",
    "segmentsFileSizeInBytes":-1,
    "userData":{}},
  "fields":{ .... },
  "info":{ .... }
}
</code>```

I've omitted part of index.directory, fields and info. The difference is in version, current, userData and lastModified, everything else looks the same.

I'm using Solr 7.5 in Cloud mode. My collections are on multiple shards with replicas = 2 (or more). I've tried adding ?numTerms=50 to request, but it doesn't help.

Is there something I can do to always receive correct response?

答:
.index.lastModified is calculated from .index.userData.commitTimeMSec by the Luke Request Handler. That's why the last three digits are always the same.

If your core hasn't had any commits yet, .index.userData is empty and Luke simply doesn't add .index.lastModified to the response. That's what you're seeing on your second request.

From LukeRequestHandler.java:

String s = userData.get(SolrIndexWriter.COMMIT_TIME_MSEC_KEY);
if (s != null) {
  indexInfo.add("lastModified", new Date(Long.parseLong(s)));
}
```

Body:
I'm trying to get some metadata (document count and last modified date) from Solr, and found /solr/<core>/admin/luke endpoint to do it.

However, my requests sometimes return nulls instead of values. I can reproduce it via both SolrJ and curl:

✗ curl hostname/solr/core_name/admin/luke -s | jq '.index.lastModified'

"2019-06-04T19:59:45.617Z"

✗ curl hostname/solr/core_name/admin/luke -s | jq '.index.lastModified'

null

Without jq results are either:

{
  "responseHeader":{
    "status":0,
    "QTime":2},
  "index":{
    "numDocs":11,
    "maxDoc":11,
    "deletedDocs":0,
    "indexHeapUsageBytes":-1,
    "version":6,
    "segmentCount":1,
    "current":true,
    "hasDeletions":false,
    "directory":"org.apache.lucene.store.NRTCachingDirectory:NRTCachingDirectory(MMapDirectory@ ... lockFactory=org.apache.lucene.store.NativeFSLockFactory@2846d2cf; maxCacheMB=48.0 maxMergeSizeMB=4.0)",
    "segmentsFile":"segments_1",
    "segmentsFileSizeInBytes":-1,
    "userData":{
      "commitTimeMSec":"1559730066881",
      "commitCommandVer":"1635495514608762880"},
    "lastModified":"2019-06-05T10:21:06.881Z"},
  "fields":{ .... },
  "info":{ .... }
}

or:

{
  "responseHeader":{
    "status":0,
    "QTime":2},
  "index":{
    "numDocs":11,
    "maxDoc":11,
    "deletedDocs":0,
    "indexHeapUsageBytes":-1,
    "version":4,
    "segmentCount":1,
    "current":false,
    "hasDeletions":false,
    "directory":"org.apache.lucene.store.NRTCachingDirectory:NRTCachingDirectory(MMapDirectory@ .... lockFactory=org.apache.lucene.store.NativeFSLockFactory@1e10c435; maxCacheMB=48.0 maxMergeSizeMB=4.0)",
    "segmentsFile":"segments_1",
    "segmentsFileSizeInBytes":-1,
    "userData":{}},
  "fields":{ .... },
  "info":{ .... }
}

I've omitted part of index.directory, fields and info. The difference is in version, current, userData and lastModified, everything else looks the same.

I'm using Solr 7.5 in Cloud mode. My collections are on multiple shards with replicas = 2 (or more). I've tried adding ?numTerms=50 to request, but it doesn't help.

Is there something I can do to always receive correct response?


问:
Check if a word exists in another string in c# without using any inbuilt function
```<code>string sentence = "This is a goodday";
string word = "good";
</code>```

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

答:
Q: Check if a word exists in another string in c# without using any inbuilt function

A: Tricky

It depends on how detailed that "any inbuilt function" really is.

In general the algorithm is simple:

```<code>Loop through the string you're searching in
    for each position, see if you've found the word

    you do this by looping through all the characters in what we're looking for
        and compare each character from the first string with one from the second
    if they all matched, we've found a match
</code>```

but then ... "without using any inbuilt function".

I assume this would mean, do not use the obvious ones, such as Contains, IndexOf, a regular expression, all those things.

But taken to the extreme, does that mean I cannot even know how long the strings are? Is s.Length a built-in function? And thus not allowed?

```<code>public bool Contains(string value, string whatWereLookingFor)
{
    return IndexOf(value, whatWereLookingFor) >= 0;
}

public int Length(string s)
{
    int result = 0;
    for (int i = 0; i <= 2147483647; i++)
    {
        try
        {
            char c = s[i];
        }
        catch (IndexOutOfRangeException)
        {
            break;
        }
        result = i + 1;
    }

    return result;
}

public int IndexOf(string value, string whatWereLookingFor)
{
    int iMax = Length(value);
    int whatMax = Length(whatWereLookingFor);
    for (int i = 0; i <= iMax - whatMax; i++)
    {
        bool isMatch = true;
        for (int j = 0; j < whatMax; j++)
        {
            if (value[i + j] != whatWereLookingFor[j])
            {
                isMatch = false;
                break;
            }
        }
        if (isMatch)
            return i;
    }
    return -1;
}
</code>```

Body:
string sentence = "This is a goodday";
string word = "good";

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

Body:
Q: Check if a word exists in another string in c# without using any inbuilt function

A: Tricky

It depends on how detailed that "any inbuilt function" really is.

In general the algorithm is simple:

Loop through the string you're searching in
    for each position, see if you've found the word

    you do this by looping through all the characters in what we're looking for
        and compare each character from the first string with one from the second
    if they all matched, we've found a match

but then ... "without using any inbuilt function".

I assume this would mean, do not use the obvious ones, such as Contains, IndexOf, a regular expression, all those things.

But taken to the extreme, does that mean I cannot even know how long the strings are? Is s.Length a built-in function? And thus not allowed?

public bool Contains(string value, string whatWereLookingFor)
{
    return IndexOf(value, whatWereLookingFor) >= 0;
}

public int Length(string s)
{
    int result = 0;
    for (int i = 0; i <= 2147483647; i++)
    {
        try
        {
            char c = s[i];
        }
        catch (IndexOutOfRangeException)
        {
            break;
        }
        result = i + 1;
    }

    return result;
}

public int IndexOf(string value, string whatWereLookingFor)
{
    int iMax = Length(value);
    int whatMax = Length(whatWereLookingFor);
    for (int i = 0; i <= iMax - whatMax; i++)
    {
        bool isMatch = true;
        for (int j = 0; j < whatMax; j++)
        {
            if (value[i + j] != whatWereLookingFor[j])
            {
                isMatch = false;
                break;
            }
        }
        if (isMatch)
            return i;
    }
    return -1;
}


问:
Why does Valgrind return executable file's exit code?
I want to run Valgrind in cp Linux command and watch the XML result of Valgrind.

when I run the below command to get XML output, the exit code is 1. because Valgrind runs the cp command.

```<code>valgrind --xml=yes --leak-check=full --verbose --track-origins=no --xml-file=/home/user/Desktop/test/cp_valgrind.xml --log-file=/home/user/Desktop/test/cp_valgrind.txt --error-exitcode=100 /home/user/Desktop/test/cp
</code>```

I got the below error:

```<code>/home/user/Desktop/test/cp: missing file operand
Try '/home/user/Desktop/test/cp --help' for more information.
</code>```

Why does Valgrind return the executable file's exit code?
How can I run Valgrind on an executable file without Valgrind runs it?

答:
Valgrind will return the guest return value by default.

If you specify --error-exitcode then it will return that value if there is an error from the view of the Valgrind tool and the guest returns 0. It will still return the guest return value of the Valgrind tool detects no errors. It does not translate a guest error code into the value specified by --error-exitcode, or override a non-zero guest error code.

In the table below invalid_free is a small testcase that generates a single memcheck error but returns 0.

No mem error, no guest error
No mem error, guest error
Mem error, no guest error

Standalone
pwd ; echo $? -> 0
cp ; echo $? -> 1
invalid_free ; echo $? -> 0

Under memcheck
valgrind -q pwd ; echo $? -> 0
valgrind -q cp ; echo $? -> 1
valgrind -q invalid_free ; echo $? -> 0

Under memcheck with --error-code
valgrind -q --error-exitcode=42 pwd ; echo $? -> 0
valgrind -q --error-exitcode=42 cp ; echo $? -> 1
valgrind -q --error-exitcode=42 invalid_free ; echo $? -> 42

and a 4th column that I can't fit without scrolling

Mem error, guest error

Standalone
invalid_free2 ; echo $? -> 1

Under memcheck
valgrind -q invalid_free2 ; echo $? -> 1

Under memcheck with --error-code
valgrind -q --error-exitcode=42 invalid_free2 ; echo $? -> 1

Body:
I want to run Valgrind in cp Linux command and watch the XML result of Valgrind.

when I run the below command to get XML output, the exit code is 1. because Valgrind runs the cp command.

valgrind --xml=yes --leak-check=full --verbose --track-origins=no --xml-file=/home/user/Desktop/test/cp_valgrind.xml --log-file=/home/user/Desktop/test/cp_valgrind.txt --error-exitcode=100 /home/user/Desktop/test/cp

I got the below error:

/home/user/Desktop/test/cp: missing file operand
Try '/home/user/Desktop/test/cp --help' for more information.

Why does Valgrind return the executable file's exit code?
How can I run Valgrind on an executable file without Valgrind runs it?


问:
Error with simple rollover colour transition please help
trying to do a simple rollover colour transition in Actionscript 3, and I'm getting

```<code>ReferenceError: Error #1069: Property transform not found on
</code>```

fl.transitions.Tween and there is no default value.
            at dell_fla::MainTimeline/tweenToFinal()
            at flash.events::EventDispatcher/dispatchEventFunction()
            at flash.events::EventDispatcher/dispatchEvent()
            at fl.transitions::Tween/setPosition()
            at fl.transitions::Tween/update()
            at fl.transitions::Tween/set time()
            at fl.transitions::Tween/nextFrame()
            at fl.transitions::Tween/onEnterFrame()

Heres my script

```<code>import fl.transitions.Tween;
    import fl.transitions.TweenEvent;
    import fl.transitions.easing.Strong;
    import fl.motion.Color;
    import flash.events.Event;
    import flash.geom.ColorTransform;
    import flash.display.DisplayObject;

    var startColor:uint=0xCCFF00;
    var finalColor:uint=0x003399;
    var colorInfo:ColorTransform;
    // Colour transition for country mouseover
    function initColorTransform(mc:MovieClip):void
    {
        colorInfo = mc.transform.colorTransform;
        var myTween:Tween=new Tween(mc,'alpha',Strong.easeOut,0,1,1,true);
        myTween.addEventListener(TweenEvent.MOTION_CHANGE,tweenToFinal);
    }
    function tweenToFinal(e:TweenEvent):void
    {
        colorInfo.color=Color.interpolateColor(startColor,finalColor,e.position);
        e.target.transform.colorTransform=colorInfo;
    }

    function countryMouseOver(e:Event):void{
        trace('countryMouseOver '+e.target);
        var countryMc = e.target;
        var localPos:Point = new Point(countryMc.x,countryMc.y);
        var globalPos:Point = countryMc.localToGlobal(localPos);
        trace('local pos: '+localPos+ ' global pos:'+globalPos);
        initColorTransform(countryMc);
    }
</code>```

答:
Have a look at the TweenEvent docs. The e.target is not your movie clip but the tween itself. Obtain your movieclip using Tween(e.target).obj.

```<code>   function tweenToFinal(e:TweenEvent):void
    {
        colorInfo.color=Color.interpolateColor(startColor,finalColor,e.position);
        MovieClip(Tween(e.target).obj).transform.colorTransform=colorInfo;
    }
</code>```

Body:
trying to do a simple rollover colour transition in Actionscript 3, and I'm getting

ReferenceError: Error #1069: Property transform not found on

fl.transitions.Tween and there is no default value.
            at dell_fla::MainTimeline/tweenToFinal()
            at flash.events::EventDispatcher/dispatchEventFunction()
            at flash.events::EventDispatcher/dispatchEvent()
            at fl.transitions::Tween/setPosition()
            at fl.transitions::Tween/update()
            at fl.transitions::Tween/set time()
            at fl.transitions::Tween/nextFrame()
            at fl.transitions::Tween/onEnterFrame()

Heres my script

import fl.transitions.Tween;
    import fl.transitions.TweenEvent;
    import fl.transitions.easing.Strong;
    import fl.motion.Color;
    import flash.events.Event;
    import flash.geom.ColorTransform;
    import flash.display.DisplayObject;

    var startColor:uint=0xCCFF00;
    var finalColor:uint=0x003399;
    var colorInfo:ColorTransform;
    // Colour transition for country mouseover
    function initColorTransform(mc:MovieClip):void
    {
        colorInfo = mc.transform.colorTransform;
        var myTween:Tween=new Tween(mc,'alpha',Strong.easeOut,0,1,1,true);
        myTween.addEventListener(TweenEvent.MOTION_CHANGE,tweenToFinal);
    }
    function tweenToFinal(e:TweenEvent):void
    {
        colorInfo.color=Color.interpolateColor(startColor,finalColor,e.position);
        e.target.transform.colorTransform=colorInfo;
    }

    function countryMouseOver(e:Event):void{
        trace('countryMouseOver '+e.target);
        var countryMc = e.target;
        var localPos:Point = new Point(countryMc.x,countryMc.y);
        var globalPos:Point = countryMc.localToGlobal(localPos);
        trace('local pos: '+localPos+ ' global pos:'+globalPos);
        initColorTransform(countryMc);
    }

Body:
Have a look at the TweenEvent docs. The e.target is not your movie clip but the tween itself. Obtain your movieclip using Tween(e.target).obj.

   function tweenToFinal(e:TweenEvent):void
    {
        colorInfo.color=Color.interpolateColor(startColor,finalColor,e.position);
        MovieClip(Tween(e.target).obj).transform.colorTransform=colorInfo;
    }


问:
How to notify the android user if camera permission is denied
I am working with camera permissions. when the user clicks on take photo button, user will be shown with run time permissions menu and lets say user deny's it and then clicks on take photo button, run time permissions will be shown second time.

after this clicking the take photo button nothing happens.

What I want to do is, after the second attempt, i want to show a popup telling the user to go to settings to change the permissions.

How can I know if the user has denied the permission twice.

this is what I have coded so far

```<code>takePhotoBtn.setOnClickListener {
        takePhoto()
    }

private fun takePhoto() {
    activity?.let {
        if (isCameraPermissionsAllowed()) {
            capturePhoto()
        } else {
            permReqLauncher.launch(
                CAMERA_PERMISSION
            )
        }
    }
}

private val permReqLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        val granted = permissions.entries.all {
            it.value == true
        }
        if (granted) {
            capturePhoto()
        }
    }

private fun capturePhoto() {
    onUtilityBillTypeListener.onUtilityBillTypePhotoLink(true)
}
</code>```

where is the right place to add this dinielDialog

```<code>private fun showPermissionDeniedDialog() {
    AlertDialog.Builder(this.requireContext())
        .setTitle("Permission Denied")
        .setMessage("Permission is denied, Please allow permissions from App Settings.")
        .setPositiveButton("Settings",
            DialogInterface.OnClickListener { dialogInterface, i ->
                // send to app settings if permission is denied permanently
                val intent = Intent()
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri = Uri.fromParts("package", getPackageName(this.requireContext()), null)
                intent.data = uri
                startActivity(intent)
            })
        .setNegativeButton("Cancel", null)
        .show()
}
</code>```

答:
resolved it by adding this code</p>
```<code> private fun takePhoto() {
        activity?.let {
            if (isCameraPermissionsAllowed()) {
                capturePhoto()
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        this.requireActivity(),
                        Manifest.permission.CAMERA
                    )
                ) {
                    showPermissionDeniedDialog()
                }
                else{
                    permReqLauncher.launch(
                        CAMERA_PERMISSION
                    )
                }
            }
        }
    }
</code>```

Body:
I am working with camera permissions. when the user clicks on take photo button, user will be shown with run time permissions menu and lets say user deny's it and then clicks on take photo button, run time permissions will be shown second time.

after this clicking the take photo button nothing happens.

What I want to do is, after the second attempt, i want to show a popup telling the user to go to settings to change the permissions.

How can I know if the user has denied the permission twice.

this is what I have coded so far

takePhotoBtn.setOnClickListener {
        takePhoto()
    }

private fun takePhoto() {
    activity?.let {
        if (isCameraPermissionsAllowed()) {
            capturePhoto()
        } else {
            permReqLauncher.launch(
                CAMERA_PERMISSION
            )
        }
    }
}

private val permReqLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        val granted = permissions.entries.all {
            it.value == true
        }
        if (granted) {
            capturePhoto()
        }
    }

private fun capturePhoto() {
    onUtilityBillTypeListener.onUtilityBillTypePhotoLink(true)
}

where is the right place to add this dinielDialog

private fun showPermissionDeniedDialog() {
    AlertDialog.Builder(this.requireContext())
        .setTitle("Permission Denied")
        .setMessage("Permission is denied, Please allow permissions from App Settings.")
        .setPositiveButton("Settings",
            DialogInterface.OnClickListener { dialogInterface, i ->
                // send to app settings if permission is denied permanently
                val intent = Intent()
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri = Uri.fromParts("package", getPackageName(this.requireContext()), null)
                intent.data = uri
                startActivity(intent)
            })
        .setNegativeButton("Cancel", null)
        .show()
}

Body:
resolved it by adding this code

 private fun takePhoto() {
        activity?.let {
            if (isCameraPermissionsAllowed()) {
                capturePhoto()
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        this.requireActivity(),
                        Manifest.permission.CAMERA
                    )
                ) {
                    showPermissionDeniedDialog()
                }
                else{
                    permReqLauncher.launch(
                        CAMERA_PERMISSION
                    )
                }
            }
        }
    }