问:
Crop a squared part of image based on coordinates
this is a 500x500 px image  [source]

and with boundary boxes drawn:

the boundary box of the word "Hello" is :

```<code>bbox_hello = [176, 233,
 190, 186,
 314, 223,
 300, 270]
</code>```

each two integers correspond to the x,y of a point (arranged clock-wise) , so the first point's coordinates are x =176, y =233

I want to crop this bbox and rotate/align it , without an overlap by the second bbox of the word "world".

so that the required result is :

and not someting like :

how to achieve this in python ?

答:
using getPerspectiveTransform and warpPerspective works.

code source

```<code># author:    Adrian Rosebrock
# website:   http://www.pyimagesearch.com

# import the necessary packages
from scipy.spatial import distance as dist
import numpy as np
import cv2

def order_points(pts):
    # sort the points based on their x-coordinates
    xSorted = pts[np.argsort(pts[:, 0]), :]

    # grab the left-most and right-most points from the sorted
    # x-roodinate points
    leftMost = xSorted[:2, :]
    rightMost = xSorted[2:, :]

    # now, sort the left-most coordinates according to their
    # y-coordinates so we can grab the top-left and bottom-left
    # points, respectively
    leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
    (tl, bl) = leftMost

    # now that we have the top-left coordinate, use it as an
    # anchor to calculate the Euclidean distance between the
    # top-left and right-most points; by the Pythagorean
    # theorem, the point with the largest distance will be
    # our bottom-right point
    D = dist.cdist(tl[np.newaxis], rightMost, "euclidean")[0]
    (br, tr) = rightMost[np.argsort(D)[::-1], :]

    # return the coordinates in top-left, top-right,
    # bottom-right, and bottom-left order
    return np.array([tl, tr, br, bl], dtype="float32")

def four_point_transform(image, pts):
    # obtain a consistent order of the points and unpack them
    # individually
    rect = order_points(pts)
    (tl, tr, br, bl) = rect

    # compute the width of the new image, which will be the
    # maximum distance between bottom-right and bottom-left
    # x-coordiates or the top-right and top-left x-coordinates
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
    maxWidth = max(int(widthA), int(widthB))

    # compute the height of the new image, which will be the
    # maximum distance between the top-right and bottom-right
    # y-coordinates or the top-left and bottom-left y-coordinates
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
    maxHeight = max(int(heightA), int(heightB))

    # now that we have the dimensions of the new image, construct
    # the set of destination points to obtain a "birds eye view",
    # (i.e. top-down view) of the image, again specifying points
    # in the top-left, top-right, bottom-right, and bottom-left
    # order
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype="float32")

    # compute the perspective transform matrix and then apply it
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))

    # return the warped image
    return warped
</code>```

Body:
this is a 500x500 px image  [source]

and with boundary boxes drawn:

the boundary box of the word "Hello" is :

bbox_hello = [176, 233,
 190, 186,
 314, 223,
 300, 270]

each two integers correspond to the x,y of a point (arranged clock-wise) , so the first point's coordinates are x =176, y =233

I want to crop this bbox and rotate/align it , without an overlap by the second bbox of the word "world".

so that the required result is :

and not someting like :

how to achieve this in python ?

Body:
using getPerspectiveTransform and warpPerspective works.

code source

# author:    Adrian Rosebrock
# website:   http://www.pyimagesearch.com

# import the necessary packages
from scipy.spatial import distance as dist
import numpy as np
import cv2

def order_points(pts):
    # sort the points based on their x-coordinates
    xSorted = pts[np.argsort(pts[:, 0]), :]

    # grab the left-most and right-most points from the sorted
    # x-roodinate points
    leftMost = xSorted[:2, :]
    rightMost = xSorted[2:, :]

    # now, sort the left-most coordinates according to their
    # y-coordinates so we can grab the top-left and bottom-left
    # points, respectively
    leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
    (tl, bl) = leftMost

    # now that we have the top-left coordinate, use it as an
    # anchor to calculate the Euclidean distance between the
    # top-left and right-most points; by the Pythagorean
    # theorem, the point with the largest distance will be
    # our bottom-right point
    D = dist.cdist(tl[np.newaxis], rightMost, "euclidean")[0]
    (br, tr) = rightMost[np.argsort(D)[::-1], :]

    # return the coordinates in top-left, top-right,
    # bottom-right, and bottom-left order
    return np.array([tl, tr, br, bl], dtype="float32")

def four_point_transform(image, pts):
    # obtain a consistent order of the points and unpack them
    # individually
    rect = order_points(pts)
    (tl, tr, br, bl) = rect

    # compute the width of the new image, which will be the
    # maximum distance between bottom-right and bottom-left
    # x-coordiates or the top-right and top-left x-coordinates
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
    maxWidth = max(int(widthA), int(widthB))

    # compute the height of the new image, which will be the
    # maximum distance between the top-right and bottom-right
    # y-coordinates or the top-left and bottom-left y-coordinates
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
    maxHeight = max(int(heightA), int(heightB))

    # now that we have the dimensions of the new image, construct
    # the set of destination points to obtain a "birds eye view",
    # (i.e. top-down view) of the image, again specifying points
    # in the top-left, top-right, bottom-right, and bottom-left
    # order
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype="float32")

    # compute the perspective transform matrix and then apply it
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))

    # return the warped image
    return warped


来源: stackexchange

问:
Can we add a const to an inherited virtual member function
I am learning inheritance in C++. So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below:

```<code>struct Base
{
  virtual void func(int a)
  {
      std::cout<<"base version called"<<std::endl;
  }
};
struct Derived: Base
{
  void func(int a) const  //note the const here: Is this a new function or this function overrides the old virtual from base
  {
     std::cout<<"derived version called"<<std::endl;
  }
};
</code>```

Note that i have added const for the func member function inside struct Derived. My question is that: is this member function func inside Derive a new(separate from func inside Base) function or does this func in Derived overrides the old virtual func from Base?

PS: My question is not about the meaning of const here since i know that in this context it means a const member function which means that that the object to which this pointer points is treated as const object. My question is whether func inside Derived a different function that the one inside Base.

答: void func(int a) const inside Derived is a different member function. Once a function is declared const, another function is born.

ContentLicense: CC BY-SA 4.0

Body:
I am learning inheritance in C++. So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below:

struct Base
{
  virtual void func(int a)
  {
      std::cout<<"base version called"<<std::endl;
  }
};
struct Derived: Base
{
  void func(int a) const  //note the const here: Is this a new function or this function overrides the old virtual from base
  {
     std::cout<<"derived version called"<<std::endl;
  }
};

Note that i have added const for the func member function inside struct Derived. My question is that: is this member function func inside Derive a new(separate from func inside Base) function or does this func in Derived overrides the old virtual func from Base?

PS: My question is not about the meaning of const here since i know that in this context it means a const member function which means that that the object to which this pointer points is treated as const object. My question is whether func inside Derived a different function that the one inside Base.


问:
Wait the end of subprocesses with multiple parallel jobs
I'm running some subprocesses from python in parallel. I want to wait until every subprocess have finished. I'm doing a non elegant solution:

```<code>runcodes = ["script1.C", "script2.C"]
ps = []
for script in runcodes:
  args = ["root", "-l", "-q", script]
  p = subprocess.Popen(args)
  ps.append(p)
while True:
  ps_status = [p.poll() for p in ps]
  if all([x is not None for x in ps_status]):
    break
</code>```

is there a class that can handle multiple subprocess? The problem is that the wait method block my program.

update: I want to show the progress during the computation: something like "4/7 subprocess finished..."

If you are curious root compile the c++ script and execute it.

答:
This answer is related to this answer and uses a similar mechanism underneath (based on the select syscall) called asyncio.
You can read more about asyncio here.

Asyncio is good when your process is IO-bound. Your process seems to be IO-bound, at least in this section of your program, spending most of its time waiting for the external scripts to complete and only printing a message at their end.

The following code should work for you (with some minor adjustments perhaps):

```<code>import asyncio

# The scripts you want to run concurrently
runcodes = ["script1.C", "script2.C"]

# An awaitable coroutine that calls your script
# and waits (non-blocking) until the script is done
# to print a message
async def run_script(script):
    # You will need to adjust the arguments of create_subprocess_exec here
    # according to your needs
    p = await asyncio.create_subprocess_exec(script)
    await p.wait()
    print("Script", script, "is done")

# You create concurrent tasks for each script
# they will start in parallel as soon as they are
# created
async def main():
    tasks = []
    for script in runcodes:
        tasks.append(asyncio.create_task(run_script(script)))

    # You wait until all the tasks are done before
    # continuing your program
    for task in tasks:
        await task

if __name__ == "__main__":
    asyncio.run(main())
</code>```

Some detailed explanation.

Asyncio allows you to execute concurrent tasks with a single thread by alternating the various asynchronous tasks and simply waiting when all of them are blocked.

The function run_script is asynchronous and will call your script using a similar mechanism to subprocess.Popen. The difference here is that the returning object is awaitable meaning that you can jump to something else while the wait function is blocked.

You can read more about subprocess management with asyncio here. You will notice the management of the subprocess is very similar to the "normal" Python subprocessing. The arguments of the Popen are also similar.

Notice that this is different to threading. In fact, this program is single-threaded. Do not confuse asyncio with multi-threading. They are two different approaches to run tasks concurrently (with pros and cons).

The main function will create multiple tasks, one for each script you want to run and wait on them.

The important thing is that this await will not be blocking and at the same time it will not do live-polling. It will sleep until any of the tasks will be ready. Once a task is ready the execution returns to that task that can print a statement about your message.

The program will not exit the main function until all awaited tasks are done, though. It will stay within the loop of awaited functions generated by asyncio.run until everything is completed.

ContentLicense: CC BY-SA 3.0

Body:
I'm running some subprocesses from python in parallel. I want to wait until every subprocess have finished. I'm doing a non elegant solution:

runcodes = ["script1.C", "script2.C"]
ps = []
for script in runcodes:
  args = ["root", "-l", "-q", script]
  p = subprocess.Popen(args)
  ps.append(p)
while True:
  ps_status = [p.poll() for p in ps]
  if all([x is not None for x in ps_status]):
    break

is there a class that can handle multiple subprocess? The problem is that the wait method block my program.

update: I want to show the progress during the computation: something like "4/7 subprocess finished..."

If you are curious root compile the c++ script and execute it.

Body:
This answer is related to this answer and uses a similar mechanism underneath (based on the select syscall) called asyncio.
You can read more about asyncio here.

Asyncio is good when your process is IO-bound. Your process seems to be IO-bound, at least in this section of your program, spending most of its time waiting for the external scripts to complete and only printing a message at their end.

The following code should work for you (with some minor adjustments perhaps):

import asyncio

# The scripts you want to run concurrently
runcodes = ["script1.C", "script2.C"]

# An awaitable coroutine that calls your script
# and waits (non-blocking) until the script is done
# to print a message
async def run_script(script):
    # You will need to adjust the arguments of create_subprocess_exec here
    # according to your needs
    p = await asyncio.create_subprocess_exec(script)
    await p.wait()
    print("Script", script, "is done")

# You create concurrent tasks for each script
# they will start in parallel as soon as they are
# created
async def main():
    tasks = []
    for script in runcodes:
        tasks.append(asyncio.create_task(run_script(script)))

    # You wait until all the tasks are done before
    # continuing your program
    for task in tasks:
        await task

if __name__ == "__main__":
    asyncio.run(main())

Some detailed explanation.

Asyncio allows you to execute concurrent tasks with a single thread by alternating the various asynchronous tasks and simply waiting when all of them are blocked.

The function run_script is asynchronous and will call your script using a similar mechanism to subprocess.Popen. The difference here is that the returning object is awaitable meaning that you can jump to something else while the wait function is blocked.

You can read more about subprocess management with asyncio here. You will notice the management of the subprocess is very similar to the "normal" Python subprocessing. The arguments of the Popen are also similar.

Notice that this is different to threading. In fact, this program is single-threaded. Do not confuse asyncio with multi-threading. They are two different approaches to run tasks concurrently (with pros and cons).

The main function will create multiple tasks, one for each script you want to run and wait on them.

The important thing is that this await will not be blocking and at the same time it will not do live-polling. It will sleep until any of the tasks will be ready. Once a task is ready the execution returns to that task that can print a statement about your message.

The program will not exit the main function until all awaited tasks are done, though. It will stay within the loop of awaited functions generated by asyncio.run until everything is completed.


问:
c# - cast generic class to its base non-generic class
I have following classes:

```<code>public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
</code>```

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

```<code>    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }
</code>```

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

```<code>public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }
</code>```

答:
Try this:</p>

```<code>if(start.GetType().GetGenericTypeDefinition() == typeof(CustomerWithChildern<>))
</code>```

OwnerDisplayName: Buthrakaur

ContentLicense: CC BY-SA 2.5

Body:
I have following classes:

public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }

LastEditorDisplayName: Buthrakaur

Body:
Try this:

if(start.GetType().GetGenericTypeDefinition() == typeof(CustomerWithChildern<>))

OwnerDisplayName: Sunny


问:
Mathematica - selectively gathering nodes in a tree
I have a tree (expression) on which I want to gather only certain types of nodes - those that follow a certain pattern. I have a simplified example below:

```
A = {{{{},{0.3,0.3}},{0.2,0.2}},{0.1,0.1}};
TreeForm[A, PlotRangePadding->0]
Cases[A, {x_Real, y_Real}, Infinity]
```

The output:

Is this a good way to do it?

If instead of {x_, y_}, if I wanted to look for {{x1_, y1_}, {x2_, y_2}}, how can I exclude expressions like {x_, y_}, which also match?

Regards

EDIT (14/07/2011)

I have found that using a head other than List will greatly aid in finding such sub-expressions without collisions.

For example, reformulating the above:

```<code>A = {{{{}, pt[0.3, 0.3]}, pt[0.2, 0.2]}, pt[0.1, 0.1]};
List @@@ Cases[A, _pt, Infinity]
</code>```

Output:

```<code>{{0.3,0.3},{0.2,0.2},{0.1,0.1}}
</code>```

Body:
I have a tree (expression) on which I want to gather only certain types of nodes - those that follow a certain pattern. I have a simplified example below:

A = {{{{},{0.3,0.3}},{0.2,0.2}},{0.1,0.1}};
TreeForm[A, PlotRangePadding->0]
Cases[A, {x_Real, y_Real}, Infinity]

The output:

Is this a good way to do it?

If instead of {x_, y_}, if I wanted to look for {{x1_, y1_}, {x2_, y_2}}, how can I exclude expressions like {x_, y_}, which also match?

Regards

EDIT (14/07/2011)

I have found that using a head other than List will greatly aid in finding such sub-expressions without collisions.

For example, reformulating the above:

A = {{{{}, pt[0.3, 0.3]}, pt[0.2, 0.2]}, pt[0.1, 0.1]};
List @@@ Cases[A, _pt, Infinity]

Output:

{{0.3,0.3},{0.2,0.2},{0.1,0.1}}

Body:
Here is an alternative to the form acl used, that I find more readable.

b = {{{{}, {0.3, 0.3}}, {0.2, 0.2}}, {{0.1, 0.1}, {0.3, 0.4}}};

With[{p = _?NumericQ}, Cases[b, {{p, p}, {p, p}}, -1] ]


问:
jQuery Async Call only "parallel" when URL's different
I was playing with jQuery and async calls last night and found an unusual issue. I wanted to run multiple Ajax calls inside a loop. I wrote the below (where rand.php just sleeps for a second and returns a random number). Somewhat surprisingly it executes synchronously and takes 20 seconds or so to finish.

```<code>$(document).ready(function () {
    $([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]).each(function() {
        var number = this;

        $.get("rand.php", function(data) {
            $('#'+number).html(data);
        });
    });
});
</code>```

The PHP code is as follows,

```<code><?php
sleep(1);
echo rand();
?>
</code>```

I was thinking this is clearly wrong as the async calls should be no blocking and return almost in parallel. After much playing around (assuming it was a server issue) I discovered that appending anything to the URL to make it look like it was different worked as expected. That is it returned in 3 seconds or so (6 or so calls at a time).

```<code>$(document).ready(function () {
    $([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]).each(function() {
        var number = this;

        $.get("rand.php?"+number, function(data) {
            $('#'+number).html(data);
        });
    });
});
</code>```

I don't suppose a jQuery/Javascript Guru can explain this behavior? Is it some browser limitation? Why is it that only when the URL's are different that it runs as I would expect?

EDIT - Rather then reply, this was using Chrome (whatever the latest is) and Firefox 5/6. I did try it in IE which did cache it, so ignored that and focused on Chrome. Interesting the first one works as expected in IE9 on the first page load, but then just displays cached results when reloaded.

答:
You are in ie aren't you. Bad! Bad IE user! IE caches get requests as if it was any other content. Jquery has a built in function to address this:

```<code>$.ajaxSetup({ cache : false });
</code>```

This will add a nifty spoiler to take care of this. But why add the spoiler in other browsers? So usually I do this:

```<code>if(!+"\v1"){
    $.ajaxSetup({ cache : false });
}
</code>```

Which is the tests for IE and set it only in that browser.

Body:
I was playing with jQuery and async calls last night and found an unusual issue. I wanted to run multiple Ajax calls inside a loop. I wrote the below (where rand.php just sleeps for a second and returns a random number). Somewhat surprisingly it executes synchronously and takes 20 seconds or so to finish.

$(document).ready(function () {
    $([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]).each(function() {
        var number = this;

        $.get("rand.php", function(data) {
            $('#'+number).html(data);
        });
    });
});

The PHP code is as follows,

<?php
sleep(1);
echo rand();
?>

I was thinking this is clearly wrong as the async calls should be no blocking and return almost in parallel. After much playing around (assuming it was a server issue) I discovered that appending anything to the URL to make it look like it was different worked as expected. That is it returned in 3 seconds or so (6 or so calls at a time).

$(document).ready(function () {
    $([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]).each(function() {
        var number = this;

        $.get("rand.php?"+number, function(data) {
            $('#'+number).html(data);
        });
    });
});

I don't suppose a jQuery/Javascript Guru can explain this behavior? Is it some browser limitation? Why is it that only when the URL's are different that it runs as I would expect?

EDIT - Rather then reply, this was using Chrome (whatever the latest is) and Firefox 5/6. I did try it in IE which did cache it, so ignored that and focused on Chrome. Interesting the first one works as expected in IE9 on the first page load, but then just displays cached results when reloaded.

Body:
You are in ie aren't you. Bad! Bad IE user! IE caches get requests as if it was any other content. Jquery has a built in function to address this:

$.ajaxSetup({ cache : false });

This will add a nifty spoiler to take care of this. But why add the spoiler in other browsers? So usually I do this:

if(!+"\v1"){
    $.ajaxSetup({ cache : false });
}

Which is the tests for IE and set it only in that browser.


问:
What should I learn to code a bot in Telegram?
I want to code and creat a bot for telegram that does these things:

1 - shows a massage to the person that hit start button

2 - then it gets a name as an input

3 - then again shows a massage

4 - getting an input

5 - at the end add the inputs to a defualt text and showing it;

for exampele:

-start

+Hi What is your name?

-X

+How old are you?

-Y

+Your name is X and you are Y years old.

My second Question is that how can I Connect to bots together, for example imagine I want to pass some input from this bot to make a poll(voting massage), in order to do that I should send the name to let's say @vote, how is that possible and what should I learn to do such things with my bot?

答:
First you're gonna have to explore telegram bot API documentation here.

Then you should choose your programming language and the library you want to use.

There are different libraries for each language, I'm gonna name a few:

Go: https://github.com/aliforever/go-telegram-bot-api (DISCLAIMER: I wrote and maintain it)

Python: https://github.com/eternnoir/pyTelegramBotAPI

NodeJS: https://github.com/telegraf/telegraf

I'm gonna give you an example for what you want in python using pyTelegramBotAPI:

First install the library using pip:

```<code>pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git
</code>```

Then run this script:

import telebot

API_TOKEN = 'PLACE_BOT_TOKEN_HERE'

bot = telebot.TeleBot(API_TOKEN)

user_info = {}

def set_user_state(user_id, state):
    if user_id not in user_info:
        user_info[user_id] = {}

    user_info[user_id]["state"] = state

def get_user_state(user_id):
    if user_id in user_info:
        if "state" in user_info[user_id]:
            return user_info[user_id]["state"]
    return "Welcome"

def set_user_info(user_id, name=None, age=None):
    if name is None and age is None:
        return
    if name is not None:
        user_info[user_id]["name"] = name
    if age is not None:
        user_info[user_id]["age"] = age

def get_user_info(user_id):
    return user_info[user_id]

@bot.message_handler()
def echo_all(message):
    user_id = message.from_user.id

    if message.text == "/start":
        bot.reply_to(message, "Hi What is your name?")
        set_user_state(user_id, "EnterName")
        return

    user_state = get_user_state(user_id)

    if user_state == "EnterName":
        set_user_info(user_id, name=message.text)
        bot.reply_to(message, "How old are you?")
        set_user_state(user_id, "EnterAge")
        return
    if user_state == "EnterAge":
        set_user_info(user_id, age=message.text)
        info = get_user_info(user_id)
        bot.reply_to(message, "Your name is %s and you are %s years old." %(info["name"], info["age"]))
        set_user_state(user_id, "Welcome")
        return
    bot.reply_to(message, "To restart please send /start")

bot.infinity_polling()
```

Here we use a dictionary to place user state and info, you can place them anywhere like databases or json files.

Then we update a user's state based on their interactions with the bot.

For your second question, bots cannot communicate with each other so you should look for other solutions. In the case of your question where you want to create a poll, you should check sendPoll method as well as PollAnswer object which you receive when a user votes in a poll.

Body:
First you're gonna have to explore telegram bot API documentation here.

Then you should choose your programming language and the library you want to use.

There are different libraries for each language, I'm gonna name a few:

Go: https://github.com/aliforever/go-telegram-bot-api (DISCLAIMER: I wrote and maintain it)

Python: https://github.com/eternnoir/pyTelegramBotAPI

NodeJS: https://github.com/telegraf/telegraf

I'm gonna give you an example for what you want in python using pyTelegramBotAPI:

First install the library using pip:

pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git

Then run this script:

import telebot

API_TOKEN = 'PLACE_BOT_TOKEN_HERE'

bot = telebot.TeleBot(API_TOKEN)

user_info = {}

def set_user_state(user_id, state):
    if user_id not in user_info:
        user_info[user_id] = {}

    user_info[user_id]["state"] = state

def get_user_state(user_id):
    if user_id in user_info:
        if "state" in user_info[user_id]:
            return user_info[user_id]["state"]
    return "Welcome"

def set_user_info(user_id, name=None, age=None):
    if name is None and age is None:
        return
    if name is not None:
        user_info[user_id]["name"] = name
    if age is not None:
        user_info[user_id]["age"] = age

def get_user_info(user_id):
    return user_info[user_id]

@bot.message_handler()
def echo_all(message):
    user_id = message.from_user.id

    if message.text == "/start":
        bot.reply_to(message, "Hi What is your name?")
        set_user_state(user_id, "EnterName")
        return

    user_state = get_user_state(user_id)

    if user_state == "EnterName":
        set_user_info(user_id, name=message.text)
        bot.reply_to(message, "How old are you?")
        set_user_state(user_id, "EnterAge")
        return
    if user_state == "EnterAge":
        set_user_info(user_id, age=message.text)
        info = get_user_info(user_id)
        bot.reply_to(message, "Your name is %s and you are %s years old." %(info["name"], info["age"]))
        set_user_state(user_id, "Welcome")
        return
    bot.reply_to(message, "To restart please send /start")

bot.infinity_polling()

Here we use a dictionary to place user state and info, you can place them anywhere like databases or json files.

Then we update a user's state based on their interactions with the bot.

For your second question, bots cannot communicate with each other so you should look for other solutions. In the case of your question where you want to create a poll, you should check sendPoll method as well as PollAnswer object which you receive when a user votes in a poll.


问:
Spring Boot 2: Basic Http Auth causes unprotected endpoints to respond with 401 "Unauthorized" if Authorization header is attached
After migration to Spring Boot 2 and adding basic authorization requirement for actuator and another application controlling endpoint it became impossible to call any unprotected endpoint with Authorization header.

Configuration snippet:

```<code>@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .and().httpBasic();
}
</code>```

E.g. call to .../health with "Authorization: Basic ..." will cause 401 "Unauthorized" even though it is not protected by spring security.

Question: How can i adjust the configuration so that it is possible to send request with Authorization header to any unprotected endpoint without being denied?

UPD: This fix worked as i wanted

```<code>@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .antMatchers("/payment/**").permitAll()
            .and().httpBasic();
}
</code>```

UPD2: Nevermind, just tested another request and still receive 401 "Unauthorized".

```<code>curl localhost:8080/payment/<any_endpoint> -H "Authorization: Basic asdadas"
{"code":401,"message":"Unauthorized"}
</code>```

This approach unfortunately overrides HttpSecurity matchers, e.g.: /payment/ becomes accessible

```<code>@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .and().httpBasic();
}

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity.ignoring().antMatchers("/payment/**");
}
</code>```

UPD 3: I've created a simple project with this issue being reproduced
https://github.com/Anoobizzz/SpringSecurity2BasicAuthDemo

/internal & /shutdown are only accessible with user:P455W0RD

/exposed accessible without authorization

/exposed with header "Authorization: Basic 123123" responds with 401 "Unauthorized"

答:
Found a solution un cased if case when using the spring security oauth2 library. For me it went wrong in the org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter. The default behaviour this filter extracts all Authorization when send.

I solved this by reconfiguring this one;

```<code>OAuth2AuthenticationProcessingFilter.setTokenExtractor(myTokenExtractor)
</code>```

My token extractor I have implemented like this

```<code>public class MyTokenExtractor implements TokenExtractor {

private final BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor()
@Overide
public Authentication extract(HttpServletRequest request) {
  String requestURI = request.getRequestURI();
  if (requestURI.startsWith("/someuri") {
    return null;
  }
  return bearerTokenExtractor.extract(request);
}
</code>```

Body:
After migration to Spring Boot 2 and adding basic authorization requirement for actuator and another application controlling endpoint it became impossible to call any unprotected endpoint with Authorization header.

Configuration snippet:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .and().httpBasic();
}

E.g. call to .../health with "Authorization: Basic ..." will cause 401 "Unauthorized" even though it is not protected by spring security.

Question: How can i adjust the configuration so that it is possible to send request with Authorization header to any unprotected endpoint without being denied?

UPD: This fix worked as i wanted

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .antMatchers("/payment/**").permitAll()
            .and().httpBasic();
}

UPD2: Nevermind, just tested another request and still receive 401 "Unauthorized".

curl localhost:8080/payment/<any_endpoint> -H "Authorization: Basic asdadas"
{"code":401,"message":"Unauthorized"}

This approach unfortunately overrides HttpSecurity matchers, e.g.: /payment/ becomes accessible

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .and().httpBasic();
}

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity.ignoring().antMatchers("/payment/**");
}

UPD 3: I've created a simple project with this issue being reproduced
https://github.com/Anoobizzz/SpringSecurity2BasicAuthDemo

/internal & /shutdown are only accessible with user:P455W0RD

/exposed accessible without authorization

/exposed with header "Authorization: Basic 123123" responds with 401 "Unauthorized"

Body:
Found a solution un cased if case when using the spring security oauth2 library. For me it went wrong in the org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter. The default behaviour this filter extracts all Authorization when send.

I solved this by reconfiguring this one;

OAuth2AuthenticationProcessingFilter.setTokenExtractor(myTokenExtractor)

My token extractor I have implemented like this

public class MyTokenExtractor implements TokenExtractor {

private final BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor()
@Overide
public Authentication extract(HttpServletRequest request) {
  String requestURI = request.getRequestURI();
  if (requestURI.startsWith("/someuri") {
    return null;
  }
  return bearerTokenExtractor.extract(request);
}


问:
stimulus.js live update field outside of controller
On a rails 6 installation, I have the following:

Controller:

```<code># app/controllers/foo_controller.rb
def bar
  @items = [["firstname", "{{ FIRSTNAME }}"], ["lastname", "{{ LASTNAME }}"], ["company", "{{ COMPANY }}"]]
end
</code>```

View:

```<code># app/views/foo/bar.html.erb
<p>Quia <span data-field="firstname">{{ FIRSTNAME }}</span> quibusd <span data-field="firstname">{{ FIRSTNAME }}</span> am sint culpa velit necessi <span data-field="lastname">{{ LASTNAME }}</span> tatibus  s impedit recusandae modi dolorem  <span data-field="company">{{ COMPANY }}</span> aut illo ducimus unde quo u <span data-field="firstname">{{ FIRSTNAME }}</span> tempore voluptas.</p>

<% @items.each do |variable, placeholder| %>
<div data-controller="hello">
  <input
  type="text"
  data-hello-target="name"
  data-action="hello#greet"
  data-field="<%= variable %>"
  value="<%= placeholder %>">
</div>
<% end %>
</code>```

and the relevant stimulus code (vanilla JS):

```<code>//app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name" ]

  greet() {
    var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerText = this.nameTarget.value;
    };
  }
}
</code>```

Now, as you might have guessed, the idea is to generate one <input> field per item from the @items hash, pre-filled with the relevant value and "linked" with a , which it updates on value change. So far, everything works.

Here's my issue though. This part is plain old dirty vanilla js, which doesn't feel too 'stimulusy':

```<code>var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
for (var i = 0; i < elements.length; i++) {
  elements[i].innerText = this.nameTarget.value;
};
</code>```

Surely there's some way to improve this. Any suggestion as to how to refactor this code in a more elegant way would be most welcome.

答:
An alternate approach is to follow the Publish-Subscribe pattern and simply have one controller that can both publish events and subscribe to them.

This leverages the recommended approach of Cross-controller coordination with events.

This approach adds a single controller that will be 'close' to the elements that need to publish/subscribe and is overall simpler to the first answer.

PubSubController - JS code example

In the controller below we have two methods, a publish which will dispatch an event, and a subscribe which will receive an event and update the contoller's element.

The value used by this controller is a key which will serve as the reference for what values matter to what subscription.

class PubSubController extends Controller {
  static values = { key: String };

  publish(event) {
    const key = this.keyValue;
    const value = event.target.value;
    this.dispatch('send', { detail: { key, value } });
  }

  subscribe(event) {
    const { key, value } = event.detail;

    if (this.keyValue !== key) return;

    this.element.innerText = value;
  }
}
```
<h2>PubSubController - HTML usage example</h2>
<ul>
<li>The controller will be added to each input (to publish) and each DOM element you want to be updated (to subscribe).</li>
<li>Looking at the <code>input</code>s you can see that they have the controller <code>pub-sub</code> and also an action (defaults to triggering when the input changes) to fire the publish method.</li>
<li>Each <code>input</code> also contains a reference to its <code>key</code> (e.g email or name).</li>
<li>Finally, the two spans that 'subscribe' to the content are triggered on the event <code>pub-sub:send</code> and pass the event to the <code>subscribe</code> method. These also have a key.</li>
</ul>
<pre class="lang-html prettyprint-override"><code><body>
  <div class="container">
    <h1 class="title">
      Hello
      <span
        data-controller="pub-sub"
        data-action="pub-sub:send@window->pub-sub#subscribe"
        data-pub-sub-key-value="name"
        >Joe</span
      >
    </h1>
    <p>
      Email:
      <span
        data-controller="pub-sub"
        data-action="pub-sub:send@window->pub-sub#subscribe"
        data-pub-sub-key-value="email"
        >joe@joe.co</span
      >
    </p>
  </div>
  <div>
    <input
      type="text"
      data-controller="pub-sub"
      data-action="pub-sub#publish"
      data-pub-sub-key-value="name"
      value="Joe"
    />
    <input
      type="text"
      data-controller="pub-sub"
      data-action="pub-sub#publish"
      data-pub-sub-key-value="email"
      value="joe@joe.co"
    />
  </div>
</body>
</code>```

Body:
On a rails 6 installation, I have the following:

Controller:

# app/controllers/foo_controller.rb
def bar
  @items = [["firstname", "{{ FIRSTNAME }}"], ["lastname", "{{ LASTNAME }}"], ["company", "{{ COMPANY }}"]]
end

View:

# app/views/foo/bar.html.erb

Quia {{ FIRSTNAME }} quibusd {{ FIRSTNAME }} am sint culpa velit necessi {{ LASTNAME }} tatibus  s impedit recusandae modi dolorem  {{ COMPANY }} aut illo ducimus unde quo u {{ FIRSTNAME }} tempore voluptas.

<% @items.each do |variable, placeholder| %>

  <input
  type="text"
  data-hello-target="name"
  data-action="hello#greet"
  data-field="<%= variable %>"
  value="<%= placeholder %>">

<% end %>

and the relevant stimulus code (vanilla JS):

//app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name" ]

  greet() {
    var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerText = this.nameTarget.value;
    };
  }
}

Now, as you might have guessed, the idea is to generate one <input> field per item from the @items hash, pre-filled with the relevant value and "linked" with a , which it updates on value change. So far, everything works.

Here's my issue though. This part is plain old dirty vanilla js, which doesn't feel too 'stimulusy':

var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
for (var i = 0; i < elements.length; i++) {
  elements[i].innerText = this.nameTarget.value;
};

Surely there's some way to improve this. Any suggestion as to how to refactor this code in a more elegant way would be most welcome.

Body:
An alternate approach is to follow the Publish-Subscribe pattern and simply have one controller that can both publish events and subscribe to them.

This leverages the recommended approach of Cross-controller coordination with events.

This approach adds a single controller that will be 'close' to the elements that need to publish/subscribe and is overall simpler to the first answer.

PubSubController - JS code example

In the controller below we have two methods, a publish which will dispatch an event, and a subscribe which will receive an event and update the contoller's element.

The value used by this controller is a key which will serve as the reference for what values matter to what subscription.

class PubSubController extends Controller {
  static values = { key: String };

  publish(event) {
    const key = this.keyValue;
    const value = event.target.value;
    this.dispatch('send', { detail: { key, value } });
  }

  subscribe(event) {
    const { key, value } = event.detail;

    if (this.keyValue !== key) return;

    this.element.innerText = value;
  }
}

PubSubController - HTML usage example

The controller will be added to each input (to publish) and each DOM element you want to be updated (to subscribe).

Looking at the inputs you can see that they have the controller pub-sub and also an action (defaults to triggering when the input changes) to fire the publish method.

Each input also contains a reference to its key (e.g email or name).

Finally, the two spans that 'subscribe' to the content are triggered on the event pub-sub:send and pass the event to the subscribe method. These also have a key.

<body>
  <div class="container">
    <h1 class="title">
      Hello
      <span
        data-controller="pub-sub"
        data-action="pub-sub:send@window->pub-sub#subscribe"
        data-pub-sub-key-value="name"
        >Joe</span
      >
    </h1>
    <p>
      Email:
      <span
        data-controller="pub-sub"
        data-action="pub-sub:send@window->pub-sub#subscribe"
        data-pub-sub-key-value="email"
        >joe@joe.co</span
      >
    </p>
  </div>
  <div>
    <input
      type="text"
      data-controller="pub-sub"
      data-action="pub-sub#publish"
      data-pub-sub-key-value="name"
      value="Joe"
    />
    <input
      type="text"
      data-controller="pub-sub"
      data-action="pub-sub#publish"
      data-pub-sub-key-value="email"
      value="joe@joe.co"
    />
  </div>
</body>


问:
Elm - fold on recursive type with list does not compile
I'm following this article on catamorphism and I'm trying to define a fold function for a recursive data type like this

```<code>type Node anyType
    = Leaf Id (Maybe anyType)
    | Tree Id (List (Node anyType))
</code>```

What i wrote is this:

```<code>foldTree fLeaf fTree acc node =
let
    recurse =
        foldTree fLeaf fTree
in
case node of
    Leaf id v ->
        let
            newAcc = fLeaf acc (id, v)
        in
            newAcc

    Tree id l ->
        let
            newAcc = fTree acc id

        in
            l |> List.foldl recurse newAcc
</code>```

If i don't infer the types for foldTree the function compiles, but it seems to not be usable:

```<code>collectIds node =
let
    fLeaf acc (id,v) = id :: acc
    fTree acc id = id :: acc
in

foldTree fLeaf fTree [] node
</code>```

throws the following:

```<code>TYPE MISMATCH - The 1st argument to `foldTree` is not what I expect:

173|     foldTree fLeaf fTree [] node
              #^^^^^#
This `fLeaf` value is a:

#List a# -> ( a, b ) -> #List a#

But `foldTree` needs the 1st argument to be:

#Node anyType# -> ( Id, Maybe anyType ) -> #Node anyType#
</code>```

Auto inferring the types for foldTree makes it not compilable and throws the following:

```<code>-- Auto Inferred
foldTree : (c -> (Id, Maybe anyType) -> a) -> (c -> Id -> b) -> c -> Node anyType -> d

TYPE MISMATCH - Something is off with the 1st branch of this `case` expression:

126|                 newAcc
                     #^^^^^^#
This `newAcc` value is a:
#a#

But the type annotation on `foldTree` says it should be:

    #d#

#Hint#: Your type annotation uses `a` and `d` as separate type variables. Your
code seems to be saying they are the same though. Maybe they should be the same
in your type annotation? Maybe your code uses them in a weird way?
</code>```

and if I try to follow the hint, still does not compile

```<code>foldTree : (c -> (Id, Maybe anyType) -> a) -> (c -> Id -> b) -> c -> Node anyType -> a

TYPE MISMATCH - This function cannot handle the argument sent through the (|>) pipe:

134|                 l |> List.foldl recurse newAcc
                          #^^^^^^^^^^^^^^^^^^^^^^^^^#
The argument is:

    List #(Node anyType)#

But (|>) is piping it to a function that expects:

    List #c#

#Hint#: Your type annotation uses type variable `c` which means ANY type of value
can flow through, but your code is saying it specifically wants a `Node` value.
Maybe change your type annotation to be more specific? Maybe change the code to
be more general?

Read <https://elm-lang.org/0.19.1/type-annotations> for more advice!Elm
TYPE MISMATCH - The 1st argument to `foldl` is not what I expect:

134|                 l |> List.foldl recurse newAcc
                                     #^^^^^^^#
This `recurse` value is a:

    c -> Node anyType -> #a#

But `foldl` needs the 1st argument to be:

    c -> Node anyType -> #Node anyType#

#Hint#: Your type annotation uses type variable `a` which means ANY type of value
can flow through, but your code is saying it specifically wants a `Node` value.
Maybe change your type annotation to be more specific? Maybe change the code to
be more general?
</code>```

I'm stuck. Following the types on the article precisely also does not seem to work. I understand that the code on the article is F# and I'm working on Elm but I thought that in this case it would have been 100% translatable.

Where am I going wrong?

Thanks in advance!

答:
You've flipped the arguments to List.foldl. The fold function takes the value first and the accumulator second, while your recurse function takes the accumulator first and the value second.

The simple fix to this is to eta expand the recurse function and flip the arguments when passing it to foldTree:

```<code>recurse v a = foldTree fLeaf fTree a v
</code>```

Also, interestingly, annotating the type of recurse will make it compile, but obviously produces the wrong result. I didn't pursue this further to understand why, as it was wrong, but the lesson you should take from this is to always annotate your top level functions. This will give you better error messages, but also prevents your code from accidentally compiling but producing the wrong result.

Body:
I'm following this article on catamorphism and I'm trying to define a fold function for a recursive data type like this

type Node anyType
    = Leaf Id (Maybe anyType)
    | Tree Id (List (Node anyType))

What i wrote is this:

foldTree fLeaf fTree acc node =
let
    recurse =
        foldTree fLeaf fTree
in
case node of
    Leaf id v ->
        let
            newAcc = fLeaf acc (id, v)
        in
            newAcc

    Tree id l ->
        let
            newAcc = fTree acc id

        in
            l |> List.foldl recurse newAcc

If i don't infer the types for foldTree the function compiles, but it seems to not be usable:

collectIds node =
let
    fLeaf acc (id,v) = id :: acc
    fTree acc id = id :: acc
in

foldTree fLeaf fTree [] node

throws the following:

TYPE MISMATCH - The 1st argument to `foldTree` is not what I expect:

173|     foldTree fLeaf fTree [] node
              #^^^^^#
This `fLeaf` value is a:

#List a# -> ( a, b ) -> #List a#

But `foldTree` needs the 1st argument to be:

#Node anyType# -> ( Id, Maybe anyType ) -> #Node anyType#

Auto inferring the types for foldTree makes it not compilable and throws the following:

-- Auto Inferred
foldTree : (c -> (Id, Maybe anyType) -> a) -> (c -> Id -> b) -> c -> Node anyType -> d

TYPE MISMATCH - Something is off with the 1st branch of this `case` expression:

126|                 newAcc
                     #^^^^^^#
This `newAcc` value is a:
#a#

But the type annotation on `foldTree` says it should be:

    #d#

#Hint#: Your type annotation uses `a` and `d` as separate type variables. Your
code seems to be saying they are the same though. Maybe they should be the same
in your type annotation? Maybe your code uses them in a weird way?

and if I try to follow the hint, still does not compile

foldTree : (c -> (Id, Maybe anyType) -> a) -> (c -> Id -> b) -> c -> Node anyType -> a

TYPE MISMATCH - This function cannot handle the argument sent through the (|>) pipe:

134|                 l |> List.foldl recurse newAcc
                          #^^^^^^^^^^^^^^^^^^^^^^^^^#
The argument is:

    List #(Node anyType)#

But (|>) is piping it to a function that expects:

    List #c#

#Hint#: Your type annotation uses type variable `c` which means ANY type of value
can flow through, but your code is saying it specifically wants a `Node` value.
Maybe change your type annotation to be more specific? Maybe change the code to
be more general?

Read <https://elm-lang.org/0.19.1/type-annotations> for more advice!Elm
TYPE MISMATCH - The 1st argument to `foldl` is not what I expect:

134|                 l |> List.foldl recurse newAcc
                                     #^^^^^^^#
This `recurse` value is a:

    c -> Node anyType -> #a#

But `foldl` needs the 1st argument to be:

    c -> Node anyType -> #Node anyType#

#Hint#: Your type annotation uses type variable `a` which means ANY type of value
can flow through, but your code is saying it specifically wants a `Node` value.
Maybe change your type annotation to be more specific? Maybe change the code to
be more general?

I'm stuck. Following the types on the article precisely also does not seem to work. I understand that the code on the article is F# and I'm working on Elm but I thought that in this case it would have been 100% translatable.

Where am I going wrong?

Thanks in advance!

Body:
You've flipped the arguments to List.foldl. The fold function takes the value first and the accumulator second, while your recurse function takes the accumulator first and the value second.

The simple fix to this is to eta expand the recurse function and flip the arguments when passing it to foldTree:

recurse v a = foldTree fLeaf fTree a v

Also, interestingly, annotating the type of recurse will make it compile, but obviously produces the wrong result. I didn't pursue this further to understand why, as it was wrong, but the lesson you should take from this is to always annotate your top level functions. This will give you better error messages, but also prevents your code from accidentally compiling but producing the wrong result.


问:
Uncaught TypeError: Class extends value #<Object> is not a constructor or null - with superagent-throttle
I am trying to import the npm package superagent-throttle in my TypeScript project, but when I do so I get this message:

```<code>Uncaught TypeError: Class extends value #<Object> is not a constructor or null
</code>```

If I use require it works fine:

```<code>const Throttle = require("superagent-throttle");
</code>```

But, I've started using Vite which does not allow require so I have to use import instead.

The code where I reference it wants to instantiate a class ie:

```<code>        this.throttle = new Throttle({
            // set false to pause queue
            active: true,
            // how many requests can be sent every `ratePer`
            rate: 10000,
            // number of ms in which `rate` requests may be sent
            ratePer: 1000,
            // How many requests can be sent concurrently
            concurrent: 2
        });
</code>```

I have tried different variations of the import statement, but none of these work for me:

```<code>import { Throttle } from "superagent-throttle";
import Throttle from "superagent-throttle";
import * as Throttle from "superagent-throttle";
</code>```

They all give the same result - they compile ok but fail at runtime with the same error message (as above).

The code in the superagent-throttle JS file looks rather obscure, I have no idea what it's trying to do, so I'm struggling to try and understand how I could fix this issue:

Package file: node_modules/superagent-throttle/dist/index.js:

```<code>'use strict';

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
...
class Throttle extends _events2.default {
  constructor(options) {
    super();
    // instance properties
    this._options({
      _requestTimes: [0],
      _current: 0,
      _buffer: [],
      _serials: {},
      _timeout: false
    });
... etc ...
</code>```

答:
The error message points to _events2.default in the offending code:

var _events = require('events');

var _events2 = _interopRequireDefault(_events);
⋮                                 /* not a constructor or null */
class Throttle extends _events2.default {
```
<p>The debugger reveals that <code>_events.default</code> is stubbed as an empty object, which means the <code>events</code> module is not available. <code>events</code> (from Node) is normally unavailable in the browser, leading to the error you observed.</p>
<p>One solution is to install an <code>events</code> shim:</p>
```npm i -S events
```

demo

Body:
I am trying to import the npm package superagent-throttle in my TypeScript project, but when I do so I get this message:

Uncaught TypeError: Class extends value #<Object> is not a constructor or null

If I use require it works fine:

const Throttle = require("superagent-throttle");

But, I've started using Vite which does not allow require so I have to use import instead.

The code where I reference it wants to instantiate a class ie:

        this.throttle = new Throttle({
            // set false to pause queue
            active: true,
            // how many requests can be sent every `ratePer`
            rate: 10000,
            // number of ms in which `rate` requests may be sent
            ratePer: 1000,
            // How many requests can be sent concurrently
            concurrent: 2
        });

I have tried different variations of the import statement, but none of these work for me:

import { Throttle } from "superagent-throttle";
import Throttle from "superagent-throttle";
import * as Throttle from "superagent-throttle";

They all give the same result - they compile ok but fail at runtime with the same error message (as above).

The code in the superagent-throttle JS file looks rather obscure, I have no idea what it's trying to do, so I'm struggling to try and understand how I could fix this issue:

Package file: node_modules/superagent-throttle/dist/index.js:

'use strict';

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
...
class Throttle extends _events2.default {
  constructor(options) {
    super();
    // instance properties
    this._options({
      _requestTimes: [0],
      _current: 0,
      _buffer: [],
      _serials: {},
      _timeout: false
    });
... etc ...

Body:
The error message points to _events2.default in the offending code:

var _events = require('events');

var _events2 = _interopRequireDefault(_events);
⋮                                 /* not a constructor or null */
class Throttle extends _events2.default {

The debugger reveals that _events.default is stubbed as an empty object, which means the events module is not available. events (from Node) is normally unavailable in the browser, leading to the error you observed.

One solution is to install an events shim:

npm i -S events

demo


问:
How to clear TextField after ENTER key press in React
I am using Mui component TextField in TypeSCript and I want to clear TextField after ENTER key is pressed.

Here is my code snippet

```<code><TextField
      {...params}
      autoFocus
      className="SymbolInput"
      onChange={(e) => {
       setSearchTerm(e.target.value);
        handleInputdebounced(e.target.value);
      }}
      onBlur={clearState}
      onFocus={() => setSearchResults([])}
      placeholder="Add symbols"
      name="searchname"
      onKeyPress={(e) => {
        if (e.key === 'Enter') {
          onPressEnter();
          setSearchTerm('');
        }
      }}
      InputProps={{
        ...params.InputProps,
        type: 'search',
        sx: { pb: '2px', pt: '2px'  },
        endAdornment: (
          <InputAdornment position="end" sx={{width:0}}>
            {loading ? <CircularProgress color="inherit" size={20} /> : <SearchIcon />}
          </InputAdornment>
        ),
      }}
      inputProps={{
        ...params.inputProps,
        sx: { textTransform: 'uppercase', },
      }}
    />

const onPressEnter = async () => {
  if (searchTerm && searchTerm.length > 0) {
    onAddSymbol(searchTerm);
  }
};

const handleSearchChange = async (searchTerm: string) => {
const searchValue = searchTerm;
//Check if there are any previous pending requests
if (typeof autoCompleteCancelToken != typeof undefined) {
  autoCompleteCancelToken?.cancel('Operation canceled due to new request.');
}
//Save the cancel token for the current request
autoCompleteCancelToken = axios.CancelToken.source();
if (searchValue && searchValue.length > 0) {
  setLoading(true);
  setSearchTerm(searchTerm);
  const response = await companyLookup(searchTerm, { cancelToken: autoCompleteCancelToken?.token });
  if (!response.hasErrors) {
    setSearchResults(response.data || []);
  }
  setGetValue(searchValue);
  setEditable(false);
  setLoading(false);
}
if (searchValue.length == 0) {
  setSearchResults([]);
}
};

const handleInputdebounced = useMemo(() => debounce(handleSearchChange, 200), []);
</code>```

I am setting the value of textfield (searchTerm) in setSearchTersm useState but it is not working.

Can someone please help me on this?

答:
```<code><TextField
      {...params}
      value={searchTerm}
      autoFocus
      className="SymbolInput"
      onChange={(e) => {
       setSearchTerm(e.target.value);
        handleInputdebounced(e.target.value);
      }}
      onBlur={clearState}
      onFocus={() => setSearchResults([])}
      placeholder="Add symbols"
      name="searchname"
      onKeyPress={(e) => {
        if (e.key === 'Enter') {
          onPressEnter();
          setSearchTerm('');
        }
      }}
      InputProps={{
        ...params.InputProps,
        type: 'search',
        sx: { pb: '2px', pt: '2px'  },
        endAdornment: (
          <InputAdornment position="end" sx={{width:0}}>
            {loading ? <CircularProgress color="inherit" size={20} /> : <SearchIcon />}
          </InputAdornment>
        ),
      }}
      inputProps={{
        ...params.inputProps,
        sx: { textTransform: 'uppercase', },
      }}
    />
</code>```

Just add a value property to TextField and assign it to searchTerm( searchTerm is the state variable ).
I hope this solves your issue .
Please upvote if it does :)

Body:
I am using Mui component TextField in TypeSCript and I want to clear TextField after ENTER key is pressed.

Here is my code snippet

<TextField
      {...params}
      autoFocus
      className="SymbolInput"
      onChange={(e) => {
       setSearchTerm(e.target.value);
        handleInputdebounced(e.target.value);
      }}
      onBlur={clearState}
      onFocus={() => setSearchResults([])}
      placeholder="Add symbols"
      name="searchname"
      onKeyPress={(e) => {
        if (e.key === 'Enter') {
          onPressEnter();
          setSearchTerm('');
        }
      }}
      InputProps={{
        ...params.InputProps,
        type: 'search',
        sx: { pb: '2px', pt: '2px'  },
        endAdornment: (
          <InputAdornment position="end" sx={{width:0}}>
            {loading ? <CircularProgress color="inherit" size={20} /> : <SearchIcon />}
          </InputAdornment>
        ),
      }}
      inputProps={{
        ...params.inputProps,
        sx: { textTransform: 'uppercase', },
      }}
    />

const onPressEnter = async () => {
  if (searchTerm && searchTerm.length > 0) {
    onAddSymbol(searchTerm);
  }
};

const handleSearchChange = async (searchTerm: string) => {
const searchValue = searchTerm;
//Check if there are any previous pending requests
if (typeof autoCompleteCancelToken != typeof undefined) {
  autoCompleteCancelToken?.cancel('Operation canceled due to new request.');
}
//Save the cancel token for the current request
autoCompleteCancelToken = axios.CancelToken.source();
if (searchValue && searchValue.length > 0) {
  setLoading(true);
  setSearchTerm(searchTerm);
  const response = await companyLookup(searchTerm, { cancelToken: autoCompleteCancelToken?.token });
  if (!response.hasErrors) {
    setSearchResults(response.data || []);
  }
  setGetValue(searchValue);
  setEditable(false);
  setLoading(false);
}
if (searchValue.length == 0) {
  setSearchResults([]);
}
};

const handleInputdebounced = useMemo(() => debounce(handleSearchChange, 200), []);

I am setting the value of textfield (searchTerm) in setSearchTersm useState but it is not working.

Can someone please help me on this?

Body:
<TextField
      {...params}
      value={searchTerm}
      autoFocus
      className="SymbolInput"
      onChange={(e) => {
       setSearchTerm(e.target.value);
        handleInputdebounced(e.target.value);
      }}
      onBlur={clearState}
      onFocus={() => setSearchResults([])}
      placeholder="Add symbols"
      name="searchname"
      onKeyPress={(e) => {
        if (e.key === 'Enter') {
          onPressEnter();
          setSearchTerm('');
        }
      }}
      InputProps={{
        ...params.InputProps,
        type: 'search',
        sx: { pb: '2px', pt: '2px'  },
        endAdornment: (
          <InputAdornment position="end" sx={{width:0}}>
            {loading ? <CircularProgress color="inherit" size={20} /> : <SearchIcon />}
          </InputAdornment>
        ),
      }}
      inputProps={{
        ...params.inputProps,
        sx: { textTransform: 'uppercase', },
      }}
    />

Just add a value property to TextField and assign it to searchTerm( searchTerm is the state variable ).
I hope this solves your issue .
Please upvote if it does :)


问:
OpenGL texturing level
I'm trying to learn OpenGL, and I want to start texturing but I got stuck. I've created a level with two rooms and a corridor, so I want diferent textures for different parts (that is, a texture for the floor, texture for the walls and so on) but after looking at the NeHe tutorial I'm still stuck, where do I need to put it in my code?</p>

```<code>#include <windows.h>
#include <gl\gl.h>
#include <gl\glut.h>
#include <gl\glu.h>

void init(void);
void display(void);
void keyboard(unsigned char, int, int);
void resize(int, int);

int is_depth; /* depth testing flag */

int main (int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(600, 600);
    glutInitWindowPosition(40, 40);
    glutCreateWindow("The Cube World");
    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);

    /* This time we're going to keep the aspect ratio
    constant by trapping the window resizes. */
    glutReshapeFunc(resize);

    glutMainLoop();
    return 0;
}

void init(void)
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    is_depth = 1;
    glMatrixMode(GL_MODELVIEW);
}

void display(void)
{
    if (is_depth)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    else
        glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_QUADS);

    //floor
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 0.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 0.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -25.0);

    //left wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 00.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 25.0, -25.0);

    //right wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 00.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -25.0);

    //roof
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 25.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 25.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -25.0);

    //right panel
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(10.0, 15.0, -25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 15.0, -25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -25.0);

    //left panel
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 15.0, -25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 15.0, -25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 0.0, -25.0);

    //top panel
    glColor3f(0.2f, 0.2f, 0.2f);
    //bottom right
    glVertex3f(50.0, 15.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    //top right
    glVertex3f(50.0, 25.0, -25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    //top left
    glVertex3f(-50.0, 25.0, -25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    //bottom left
    glVertex3f(-50.0, 15.0, -25.0);

    // corridor floor
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 0.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(10.0, 0.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(10.0, 0.0, -25.0);

    // corridor left wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 00.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-10.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-10.0, 15.0, -25.0);

    // corridor right wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(10.0, 00.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(10.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(10.0, 15.0, -25.0);

    //corridor roof
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 15.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 15.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(10.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(10.0, 15.0, -25.0);

    //right panel room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(10.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(10.0, 15.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -275.0);

    //left panel room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 15.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 0.0, -275.0);

    //top panel room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 15.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 25.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 15.0, -275.0);

    //right wall room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 00.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -275.0);

    //left wall room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 00.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 25.0, -275.0);

    //roof room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 25.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 25.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -275.0);

    //back wall room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 0.0, -325.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 25.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 0.0, -325.0);

    //floor room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 0.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 0.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -275.0);

    glEnd();
    glutSwapBuffers();
}

void keyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
        case 'a':
        case 'A':
            glTranslatef(5.0, 0.0, 0.0);
            break;
        case 'd':
        case 'D':
            glTranslatef(-5.0, 0.0, 0.0);
            break;
        case 'w':
        case 'W':
            glTranslatef(0.0, 0.0, 5.0);
            break;
        case 's':
        case 'S':
            glTranslatef(0.0, 0.0, -5.0);
            break;
        case 't':
        case 'T':
            if (is_depth)
            {
                is_depth = 0;
                glDisable(GL_DEPTH_TEST);
            }
            else
            {
                is_depth = 1;
                glEnable(GL_DEPTH_TEST);
            }
    }
    display();
}

void resize(int width, int height)
{
    if (height == 0)
        height = 1;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    /* Note we divide our width by our height to get the aspect ratio. */
    gluPerspective(45.0, width / height, 1.0, 400.0);

    /* Set initial position */
    glTranslatef(0.0, -5.0, -150.0);

    glMatrixMode(GL_MODELVIEW);
}
</code>```

答:
You don't seem to have any code for texture loading. I'd suggest you head back to NeHe and read this tutorial http://nehe.gamedev.net/tutorial/texture_mapping/12038/

It feels like you are getting too far ahead of yourself, and you should be going through most (if not all) of the tutorials in order. If you're trying to make a first person shooter, I'd also suggest loading the level from a model file (there are articles about this on NeHe too)

Title: OpenGL texturing level

Body:
I'm trying to learn OpenGL, and I want to start texturing but I got stuck. I've created a level with two rooms and a corridor, so I want diferent textures for different parts (that is, a texture for the floor, texture for the walls and so on) but after looking at the NeHe tutorial I'm still stuck, where do I need to put it in my code?

#include <windows.h>
#include <gl\gl.h>
#include <gl\glut.h>
#include <gl\glu.h>

void init(void);
void display(void);
void keyboard(unsigned char, int, int);
void resize(int, int);

int is_depth; /* depth testing flag */

int main (int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(600, 600);
    glutInitWindowPosition(40, 40);
    glutCreateWindow("The Cube World");
    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);

    /* This time we're going to keep the aspect ratio
    constant by trapping the window resizes. */
    glutReshapeFunc(resize);

    glutMainLoop();
    return 0;
}

void init(void)
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    is_depth = 1;
    glMatrixMode(GL_MODELVIEW);
}

void display(void)
{
    if (is_depth)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    else
        glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_QUADS);

    //floor
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 0.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 0.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -25.0);

    //left wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 00.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 25.0, -25.0);

    //right wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 00.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -25.0);

    //roof
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 25.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 25.0, 25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, 25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -25.0);

    //right panel
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(10.0, 15.0, -25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 15.0, -25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -25.0);

    //left panel
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 15.0, -25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 15.0, -25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 0.0, -25.0);

    //top panel
    glColor3f(0.2f, 0.2f, 0.2f);
    //bottom right
    glVertex3f(50.0, 15.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    //top right
    glVertex3f(50.0, 25.0, -25.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    //top left
    glVertex3f(-50.0, 25.0, -25.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    //bottom left
    glVertex3f(-50.0, 15.0, -25.0);

    // corridor floor
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 0.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(10.0, 0.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(10.0, 0.0, -25.0);

    // corridor left wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 00.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-10.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-10.0, 15.0, -25.0);

    // corridor right wall
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(10.0, 0.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(10.0, 00.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(10.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(10.0, 15.0, -25.0);

    //corridor roof
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 15.0, -25.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 15.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(10.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(10.0, 15.0, -25.0);

    //right panel room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(10.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(10.0, 15.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -275.0);

    //left panel room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-10.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-10.0, 15.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 15.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 0.0, -275.0);

    //top panel room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 15.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 25.0, -275.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, -275.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 15.0, -275.0);

    //right wall room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 00.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -275.0);

    //left wall room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 00.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 25.0, -275.0);

    //roof room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 25.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 25.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 25.0, -275.0);

    //back wall room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(50.0, 0.0, -325.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(50.0, 25.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(-50.0, 25.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(-50.0, 0.0, -325.0);

    //floor room 2
    glColor3f(0.2f, 0.2f, 0.2f);
    glVertex3f(-50.0, 0.0, -275.0);
    glColor3f(0.4f, 0.4f, 0.4f);
    glVertex3f(-50.0, 0.0, -325.0);
    glColor3f(0.6f, 0.6f, 0.6f);
    glVertex3f(50.0, 0.0, -325.0);
    glColor3f(0.8f, 0.8f, 0.8f);
    glVertex3f(50.0, 0.0, -275.0);

    glEnd();
    glutSwapBuffers();
}

void keyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
        case 'a':
        case 'A':
            glTranslatef(5.0, 0.0, 0.0);
            break;
        case 'd':
        case 'D':
            glTranslatef(-5.0, 0.0, 0.0);
            break;
        case 'w':
        case 'W':
            glTranslatef(0.0, 0.0, 5.0);
            break;
        case 's':
        case 'S':
            glTranslatef(0.0, 0.0, -5.0);
            break;
        case 't':
        case 'T':
            if (is_depth)
            {
                is_depth = 0;
                glDisable(GL_DEPTH_TEST);
            }
            else
            {
                is_depth = 1;
                glEnable(GL_DEPTH_TEST);
            }
    }
    display();
}

void resize(int width, int height)
{
    if (height == 0)
        height = 1;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    /* Note we divide our width by our height to get the aspect ratio. */
    gluPerspective(45.0, width / height, 1.0, 400.0);

    /* Set initial position */
    glTranslatef(0.0, -5.0, -150.0);

    glMatrixMode(GL_MODELVIEW);
}


问:
CocoaPods not installed. Skipping pod install in flutter Mac Mini M1
I am not able to run flutter app. I am getting below error :

```<code>Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.
</code>```

I have tried all possible ways like restart IDE, sudo arch -x86_64 gem install ffi
arch -x86_64 pod install everything but still getting the same issue.

I am using flutter 2.8.1

答:
The issue has been resolved. Android studio has released patch for android studio bumblebee !

But now facing another issue Could not build the precompiled application for the device.

Body:
I am not able to run flutter app. I am getting below error :

Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I have tried all possible ways like restart IDE, sudo arch -x86_64 gem install ffi
arch -x86_64 pod install everything but still getting the same issue.

I am using flutter 2.8.1


问:
MongoDB and NodeJS TypeError: mongoClient.close is not a function
When i try to close the connection between NodeJS and MongoDB cluster i get mongoClient.close is not a function. Please help

Node JS MongoDB code

```<code>const mongoClient = require("mongodb").MongoClient;

exports.getInfo = async (czytnik_id) => {
    return new Promise((resolve, reject) => {
        mongoClient.connect(process.env.URI, { useUnifiedTopology: true }, (err, db) => {
            if (err) reject(err);
            const dbo = db.db('TTI');
            const res = dbo.collection('3P').findOne({ id: czytnik_id });
            mongoClient.close()
            resolve(res);
        });
    });
}
</code>```

答: According to the docs, the callback in MongoClient.connect() takes an error and a connected client instance, which is the one to be closed. In your case, it seems to be db, so try db.close() instead of mongoClient.close().

Body:
When i try to close the connection between NodeJS and MongoDB cluster i get mongoClient.close is not a function. Please help

Node JS MongoDB code

const mongoClient = require("mongodb").MongoClient;

exports.getInfo = async (czytnik_id) => {
    return new Promise((resolve, reject) => {
        mongoClient.connect(process.env.URI, { useUnifiedTopology: true }, (err, db) => {
            if (err) reject(err);
            const dbo = db.db('TTI');
            const res = dbo.collection('3P').findOne({ id: czytnik_id });
            mongoClient.close()
            resolve(res);
        });
    });
}


问:
Not getting any data entry with 'find_all' while scraping Spotify Charts webpage
I am trying to scrape the spotify charts containing top 200 songs in India on 2022-02-01. My python code :

```<code>#It reads the webpage.
def get_webpage(link):
    page = requests.get(link)
    soup = bs(page.content, 'html.parser')
    return(soup)

#It collects the data for each country, and write them in a list.
#The entries are (in order): Song, Artist, Date, Play Count, Rank
def get_data():
    rows = []
    soup = get_webpage('https://spotifycharts.com/regional/in/daily/2022-02-01')
    entries = soup.find_all("td", class_ = "chart-table-track")
    streams = soup.find_all("td", class_= "chart-table-streams")
    print(entries)
    for i, (entry, stream) in enumerate(zip(entries,streams)):
         song = entry.find('strong').get_text()
         artist = entry.find('span').get_text()[3:]
         play_count = stream.get_text()
         rows.append([song, artist, date, play_count, i+1])
return(rows)
</code>```

I tried printing the entries and streams but get a blank value

```<code>entries = soup.find_all("td", class_ = "chart-table-track")
streams = soup.find_all("td", class_= "chart-table-streams")
</code>```

I have copied/referenced this from  Here
and tried running the full script but that gives error : 'NoneType' object has no attribute 'find_all'  in the country  function. Hence I tried for a smaller section as above.

答:
NoneType suggests that is doesn't find the "Entries" or "Streams", if you print soup it will show you that the selectors set up for entries and streams does not exist.

After checking your soup object, it seems that Cloudflare is blocking your access to Spotify and you need to complete a CAPTCHA to get around this. There is a library set up for bypassing cloudflare called "cloudscraper".

Body:
I am trying to scrape the spotify charts containing top 200 songs in India on 2022-02-01. My python code :

#It reads the webpage.
def get_webpage(link):
    page = requests.get(link)
    soup = bs(page.content, 'html.parser')
    return(soup)

#It collects the data for each country, and write them in a list.
#The entries are (in order): Song, Artist, Date, Play Count, Rank
def get_data():
    rows = []
    soup = get_webpage('https://spotifycharts.com/regional/in/daily/2022-02-01')
    entries = soup.find_all("td", class_ = "chart-table-track")
    streams = soup.find_all("td", class_= "chart-table-streams")
    print(entries)
    for i, (entry, stream) in enumerate(zip(entries,streams)):
         song = entry.find('strong').get_text()
         artist = entry.find('span').get_text()[3:]
         play_count = stream.get_text()
         rows.append([song, artist, date, play_count, i+1])
return(rows)

I tried printing the entries and streams but get a blank value

entries = soup.find_all("td", class_ = "chart-table-track")
streams = soup.find_all("td", class_= "chart-table-streams")

I have copied/referenced this from  Here
and tried running the full script but that gives error : 'NoneType' object has no attribute 'find_all'  in the country  function. Hence I tried for a smaller section as above.


问:
Getting the SQL exception error in PowerApps
I have an simple SQL error displayed on my screen.

It's a violation of a primary key - that's all it is.

I am using application insights to log all the errors but it seems the error is split into different parts. It seems the server response is the area within the error that gives the most information. I cannot seem to get that in application insights.

I just get this in the application insights :

```<code>[{"Message":"The requested operation is invalid."}
</code>```

Which is guess is the PowerApps generic error and the server is error is what I want.

I am using a collection to store all the errors from the patch like this:

```<code>Collect(PatchErrors,Errors(Persons));
</code>```

Persons is the SQL tables and PatchErrors is just the name of the collection. The collection has these rows in it:
Column, Error, Message, Record - which makes sense from the Microsoft articles.

And then I am using a Trace command to push to application insights :

```<code>Trace(
"Patch to the SQL Error",
TraceSeverity.Critical,
{
UserName: User().FullName,
Error: PatchErrors.Error,
Message: PatchErrors.Message,
Record: PatchErrors.Record,
Column: PatchErrors.Column
}
</code>```

I am not just seeing the server error at all and I cannot find it in the Error function.

答:
```<code>Collect(PatchErrors,Errors(Persons));
</code>```

This line states an array of items is being collected, since you don't clear the collection before doing something with it.

```<code>{
  Message: PatchErrors.Message
}
</code>```

This expects a record to be processed, not an array.

First( PatchErrors ).Message for example should you you the message.

Body:
I have an simple SQL error displayed on my screen.

It's a violation of a primary key - that's all it is.

I am using application insights to log all the errors but it seems the error is split into different parts. It seems the server response is the area within the error that gives the most information. I cannot seem to get that in application insights.

I just get this in the application insights :

[{"Message":"The requested operation is invalid."}

Which is guess is the PowerApps generic error and the server is error is what I want.

I am using a collection to store all the errors from the patch like this:

Collect(PatchErrors,Errors(Persons));

Persons is the SQL tables and PatchErrors is just the name of the collection. The collection has these rows in it:
Column, Error, Message, Record - which makes sense from the Microsoft articles.

And then I am using a Trace command to push to application insights :

Trace(
"Patch to the SQL Error",
TraceSeverity.Critical,
{
UserName: User().FullName,
Error: PatchErrors.Error,
Message: PatchErrors.Message,
Record: PatchErrors.Record,
Column: PatchErrors.Column
}

I am not just seeing the server error at all and I cannot find it in the Error function.

Body:
Collect(PatchErrors,Errors(Persons));

This line states an array of items is being collected, since you don't clear the collection before doing something with it.

{
  Message: PatchErrors.Message
}

This expects a record to be processed, not an array.

First( PatchErrors ).Message for example should you you the message.


问:
Does anyone know if there is any UI to create and manage stuff in one Google Cloud instance
I'm very curious if there is a UI that allows a non dev user to manage content inside an instance of Google Cloud.

So instead of ssh-ing into a instance, there could be like a webportal where one could login with google and view stuff that is created in that instance?

答:
While it's not a complete solution. I've found a github project that gives you an UI of your NGINX

https://github.com/schenkd/nginx-ui