问:
How to predicted the response values for some selected predictors values in multiple linear regression?
I have a pandas data frame and I have done single linear regression on it. Using the following code I have predicted the response values for some selected predictor values.

```<code>X = df['predictor1'].tolist()
y = df['response'].tolist()
X = sm.add_constant(X)
reg = sm.OLS(y, X).fit()
reg.predict(pd.DataFrame({'predictor1': 1, 'response': [12, 89, 90]}),'prediction')
</code>```

Then, I have done multiple linear regression on the same data frame using the code below:

```<code>def multiple_lin_reg(df, predictors, response):
    y = dataset[response]
    X = dataset[predictors]
    X = sm.add_constant(X)
    reg = sm.OLS(y, X).fit()
    print(reg.summary())

multiple_lin_reg(df, ["predictor1","predictor2"], "response")
</code>```

And everything works fine. Now, I just want to predict the response value for selected values for more that one predictor. Let's say for predictor1 = [12,22,33] and predictor2 = [90,21,23]

How can I write the similar code to the single linear regression for solving this issue?

Note: I know that in R, it can be done by using the following commands but I want to do it in Python.

```<code>pridictor1C=c(12,22,33)
predictor2C=c(90,21,23)
selected_predictor_values = expand.grid(predictor1 = pridictor1C, predictor2 = pridictor2C)

lm.fit=lm(response~predictor1+predictor2 ,data=df)
predict(lm.fit, selected_predictor_values, interval ="prediction")
</code>```

答:
I think you misunderstood something in python. You can't make a response if your model was not created with the predictor. I'm not so sure but I think that some models in R allow this much easier.

To be sure we are on the same page, we need one linear regression for each group of predictors. Let me make myself clear, if you want to predict with "age", you need one linear regression. If you want to predict with ("age", "height"), you need another one. In total, we have 2.

Let's' see your code:

```<code>[1] X = df['predictor1'].tolist()
[2] y = df['response'].tolist()
[3] X = sm.add_constant(X)
[4] reg = sm.OLS(y, X).fit()
[5] reg.predict(pd.DataFrame({'predictor1': 1, 'response': [12, 89, 90]}),'prediction')
</code>```

To create model with multiples predictors, you can create a list with the names that you want or any other method that you want. You just need to edit you first line like this:X = df[Your_List_of_Strings].tolist()

The others line remains the same, except the [5]. In [5], you can't make predictions with your model if your model hasn't been trained with the same predictors. With this in mind you can make the predictions replacing the line like this:  reg.predict(pd.DataFrame({'predictor1': 1,'predictor2': 1, 'response': [12, 89, 90]}),'prediction')

I don't advise you to use pd.DataFrame with dictionaries (This define a dictionary on python ->'{}'). For your application, you can use the Numpy library to do this much easier. You can pass how much data as you want with NumPy, take a look at how to manipulate the shapes, and after you know that, you can pass the numpy array to create a pandas data frame setting the argument columns with the right column title and then you are ready to predict. In this case, the linear regression will give you a response equal to the number of rows on the table in the same order.

Note: The second block doesn't make any sense, your dataset variable has the wrong name, the right name isn't df? and what do you want to return with this? If you want to create n numbers of trained models with a different set of predictors, you can add return reg to your function, and make a for loop over the different sets of predictors calling your function which return the trained regressor. A list can be used to keep the trained model.

Body:
I have a pandas data frame and I have done single linear regression on it. Using the following code I have predicted the response values for some selected predictor values.

X = df['predictor1'].tolist()
y = df['response'].tolist()
X = sm.add_constant(X)
reg = sm.OLS(y, X).fit()
reg.predict(pd.DataFrame({'predictor1': 1, 'response': [12, 89, 90]}),'prediction')

Then, I have done multiple linear regression on the same data frame using the code below:

def multiple_lin_reg(df, predictors, response):
    y = dataset[response]
    X = dataset[predictors]
    X = sm.add_constant(X)
    reg = sm.OLS(y, X).fit()
    print(reg.summary())

multiple_lin_reg(df, ["predictor1","predictor2"], "response")

And everything works fine. Now, I just want to predict the response value for selected values for more that one predictor. Let's say for predictor1 = [12,22,33] and predictor2 = [90,21,23]

How can I write the similar code to the single linear regression for solving this issue?

Note: I know that in R, it can be done by using the following commands but I want to do it in Python.

pridictor1C=c(12,22,33)
predictor2C=c(90,21,23)
selected_predictor_values = expand.grid(predictor1 = pridictor1C, predictor2 = pridictor2C)

lm.fit=lm(response~predictor1+predictor2 ,data=df)
predict(lm.fit, selected_predictor_values, interval ="prediction")

Body:
I think you misunderstood something in python. You can't make a response if your model was not created with the predictor. I'm not so sure but I think that some models in R allow this much easier.

To be sure we are on the same page, we need one linear regression for each group of predictors. Let me make myself clear, if you want to predict with "age", you need one linear regression. If you want to predict with ("age", "height"), you need another one. In total, we have 2.

Let's' see your code:

[1] X = df['predictor1'].tolist()
[2] y = df['response'].tolist()
[3] X = sm.add_constant(X)
[4] reg = sm.OLS(y, X).fit()
[5] reg.predict(pd.DataFrame({'predictor1': 1, 'response': [12, 89, 90]}),'prediction')

To create model with multiples predictors, you can create a list with the names that you want or any other method that you want. You just need to edit you first line like this:X = df[Your_List_of_Strings].tolist()

The others line remains the same, except the [5]. In [5], you can't make predictions with your model if your model hasn't been trained with the same predictors. With this in mind you can make the predictions replacing the line like this:  reg.predict(pd.DataFrame({'predictor1': 1,'predictor2': 1, 'response': [12, 89, 90]}),'prediction')

I don't advise you to use pd.DataFrame with dictionaries (This define a dictionary on python ->'{}'). For your application, you can use the Numpy library to do this much easier. You can pass how much data as you want with NumPy, take a look at how to manipulate the shapes, and after you know that, you can pass the numpy array to create a pandas data frame setting the argument columns with the right column title and then you are ready to predict. In this case, the linear regression will give you a response equal to the number of rows on the table in the same order.

Note: The second block doesn't make any sense, your dataset variable has the wrong name, the right name isn't df? and what do you want to return with this? If you want to create n numbers of trained models with a different set of predictors, you can add return reg to your function, and make a for loop over the different sets of predictors calling your function which return the trained regressor. A list can be used to keep the trained model.


来源: stackexchange

问:
Kivy : AttributeError: 'Mylayout' object has no attribute 'hint'
I'm new to python and I am developing a US states flashcard with Kivy. The flashcard will shuffle the US states letter, the user will need to input the answer. When the user is not sure, he may click the Get Hint button, the flashcard will display a letter, the user may click for another letter until all letters are shown.

us_state_flaskcard_3.py file

        from kivy.app import App
        from kivy.lang import Builder
        from kivy.uix.widget import Widget
        from kivy.core.window import Window
        from kivy.uix.button import Button

        from random import choice
        from random import shuffle

        Builder.load_file('us_state_flashcard.kv')

        Window.size = (350, 600)

        class MainApp(App):
            title='US State Flashcard'
            def build(self):
                Window.clearcolor = (255/255, 255/255, 0, 1)
                return Mylayout()

            def shuffler(self):

                self.root.ids.entry_answer.text = ''
                self.root.ids.answer_label.text = ''
                self.root.ids.hint_label.text = ''

                global hint_count
                hint_count = 0

                states= ['Washington', 'Oregon','California','Ohio','Nebraska',
                    'Wisconsin', 'Daleware','Arkansas','Louisiana','California',
                    'Michigan','Florida', 'Taxes','Kectucky','Alabama','Alaska',
                    'Arizona','Colorado','Connecticut',' Georgia','Hawaii',
                    'Illinois','Indiana', 'Iowa','Maryland','Massachusetts',
                    'Rhode Island','New York']

                global word
                self.word = choice(states)
                self.root.ids.my_label.text = self.word
                break_apart_word = list(self.word)
                shuffle(break_apart_word)

                global shuffled_word
                shuffled_word = ''
                for letter in break_apart_word:
                    shuffled_word += letter

                self.root.ids.my_label.text = shuffled_word

            def answer(self):
                if self.word == self.root.ids.entry_answer.text :
                    self.root.ids.answer_label.text= "Correct!!"
                else:
                    self.root.ids.answer_label.text = "Incorrect!!"
            global hint_count
            hint_count = 0

            def hint(self, count):
                global hint_count
                hint_count = count

                word_length = len(self.word)

                if count < word_length:
                    self.root.ids.hint_label.text = f'{self.hint_label["text"]} {self.word[count]}'
                    hint_count +=1

            def on_start(self, **kwargs):
                self.shuffler()

        class Mylayout(Widget):
          def __init__(self, **kwargs):
                super(Mylayout, self).__init__(**kwargs)

                self.btn1 = Button(
                    text ='hint_button',
                    font_size ="20sp",
                    background_color =(1, 1, 1, 1),
                    color =(1, 1, 1, 1),
                    size =(200, 50),
                    pos =(80, 130)
                    )

                buttoncallback = lambda x : self.hint(hint_count)
                self.btn1.bind(on_press=buttoncallback)
                self.add_widget(self.btn1)

        if __name__ == '__main__':
            MainApp().run()
```
<p><strong>us_state_flaskcard_3.kv file</strong></p>
```        <MyLayout>

          FloatLayout:
                Label:
                    id: my_label
                    font_size: 25
                    text: 'abc'
                    pos_hint: {'x': 1.3, 'y':5}
                    size_hint: (1, 1)
                    color: 'black'

                TextInput:
                    id: entry_answer
                    multiline: False
                    font_size: 24
                    pos_hint: {'x': .8, 'y':4.5}
                    size_hint: (2, .4)
                    halign: "center"

                Button:
                    font_size: 20
                    text: "Answer"
                    on_press: app.answer()
                    pos_hint: {'x': .8, 'y':3.5 }
                    size_hint: (2, .5)

                Label:
                    id: answer_label
                    font_size: 25
                    text: ''
                    pos_hint: {'x': 0.8, 'y':2.8}
                    size_hint: (2, .5)
                    color: 'black'

                Button:
                    font_size: 20
                    text: "Pick Another Word"
                    on_press: app.shuffler()
                    pos_hint: {'x': .8, 'y':2 }
                    size_hint: (2, .5)

                Label:
                    id: hint_label
                    font_size: 20
                    text: 'Hint Label'
                    pos_hint: {'x': .8, 'y':1.5}
                    size_hint: (2, .5)
                    color: 'black'
```
<p>When I click the Get Hint Button, the error shown:</p>
<pre class="lang-py prettyprint-override"><code>     File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
         post_dispatch_input(*pop(0))
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
         listener.dispatch('on_motion', etype, me)
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
         self.dispatch('on_touch_down', me)
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
         if w.dispatch('on_touch_down', touch):
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
         if child.dispatch('on_touch_down', touch):
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
         self.dispatch('on_press')
       File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
       File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
       File "kivy\_event.pyx", line 1172, in kivy._event.EventObservers._dispatch
       File "c:\Users\Kelvin Loh\Documents\kivyMD\us_state_flaskcard_3.py", line 115, in <lambda>
         buttoncallback = lambda x : self.hint(hint_count)
     AttributeError: 'Mylayout' object has no attribute 'hint'
</code>```

答:
The reason behind this error lies in buttoncallback where you are triggering hint method. But you defined that method in the App's subclass namely, MainApp. So if you want to access that method from the Mylayout class, you have to first access the running app instance which you might do as follows,

        app = App.get_running_app()
        buttoncallback = lambda x : app.hint(hint_count)
        self.btn1.bind(on_press=buttoncallback)
```
<p>Also, perhaps you may need some change in method <code>hint</code>,</p>
<pre class="lang-py prettyprint-override"><code>    def hint(self, count):
        global hint_count
        hint_count = count

        word_length = len(self.word)

        if count < word_length:
            self.root.ids.hint_label.text = f'{self.word[count]}'
            hint_count +=1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to python and I am developing a US states flashcard with Kivy. The flashcard will shuffle the US states letter, the user will need to input the answer. When the user is not sure, he may click the Get Hint button, the flashcard will display a letter, the user may click for another letter until all letters are shown.

us_state_flaskcard_3.py file

        from kivy.app import App
        from kivy.lang import Builder
        from kivy.uix.widget import Widget
        from kivy.core.window import Window
        from kivy.uix.button import Button

        from random import choice
        from random import shuffle

        Builder.load_file('us_state_flashcard.kv')

        Window.size = (350, 600)

        class MainApp(App):
            title='US State Flashcard'
            def build(self):
                Window.clearcolor = (255/255, 255/255, 0, 1)
                return Mylayout()

            def shuffler(self):

                self.root.ids.entry_answer.text = ''
                self.root.ids.answer_label.text = ''
                self.root.ids.hint_label.text = ''

                global hint_count
                hint_count = 0

                states= ['Washington', 'Oregon','California','Ohio','Nebraska',
                    'Wisconsin', 'Daleware','Arkansas','Louisiana','California',
                    'Michigan','Florida', 'Taxes','Kectucky','Alabama','Alaska',
                    'Arizona','Colorado','Connecticut',' Georgia','Hawaii',
                    'Illinois','Indiana', 'Iowa','Maryland','Massachusetts',
                    'Rhode Island','New York']

                global word
                self.word = choice(states)
                self.root.ids.my_label.text = self.word
                break_apart_word = list(self.word)
                shuffle(break_apart_word)

                global shuffled_word
                shuffled_word = ''
                for letter in break_apart_word:
                    shuffled_word += letter

                self.root.ids.my_label.text = shuffled_word

            def answer(self):
                if self.word == self.root.ids.entry_answer.text :
                    self.root.ids.answer_label.text= "Correct!!"
                else:
                    self.root.ids.answer_label.text = "Incorrect!!"
            global hint_count
            hint_count = 0

            def hint(self, count):
                global hint_count
                hint_count = count

                word_length = len(self.word)

                if count < word_length:
                    self.root.ids.hint_label.text = f'{self.hint_label["text"]} {self.word[count]}'
                    hint_count +=1

            def on_start(self, **kwargs):
                self.shuffler()

        class Mylayout(Widget):
          def __init__(self, **kwargs):
                super(Mylayout, self).__init__(**kwargs)

                self.btn1 = Button(
                    text ='hint_button',
                    font_size ="20sp",
                    background_color =(1, 1, 1, 1),
                    color =(1, 1, 1, 1),
                    size =(200, 50),
                    pos =(80, 130)
                    )

                buttoncallback = lambda x : self.hint(hint_count)
                self.btn1.bind(on_press=buttoncallback)
                self.add_widget(self.btn1)

        if __name__ == '__main__':
            MainApp().run()

us_state_flaskcard_3.kv file

        <MyLayout>

          FloatLayout:
                Label:
                    id: my_label
                    font_size: 25
                    text: 'abc'
                    pos_hint: {'x': 1.3, 'y':5}
                    size_hint: (1, 1)
                    color: 'black'

                TextInput:
                    id: entry_answer
                    multiline: False
                    font_size: 24
                    pos_hint: {'x': .8, 'y':4.5}
                    size_hint: (2, .4)
                    halign: "center"

                Button:
                    font_size: 20
                    text: "Answer"
                    on_press: app.answer()
                    pos_hint: {'x': .8, 'y':3.5 }
                    size_hint: (2, .5)

                Label:
                    id: answer_label
                    font_size: 25
                    text: ''
                    pos_hint: {'x': 0.8, 'y':2.8}
                    size_hint: (2, .5)
                    color: 'black'

                Button:
                    font_size: 20
                    text: "Pick Another Word"
                    on_press: app.shuffler()
                    pos_hint: {'x': .8, 'y':2 }
                    size_hint: (2, .5)

                Label:
                    id: hint_label
                    font_size: 20
                    text: 'Hint Label'
                    pos_hint: {'x': .8, 'y':1.5}
                    size_hint: (2, .5)
                    color: 'black'

When I click the Get Hint Button, the error shown:

     File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
         post_dispatch_input(*pop(0))
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
         listener.dispatch('on_motion', etype, me)
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
         self.dispatch('on_touch_down', me)
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
         if w.dispatch('on_touch_down', touch):
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
         if child.dispatch('on_touch_down', touch):
       File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
       File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
         self.dispatch('on_press')
       File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
       File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
       File "kivy\_event.pyx", line 1172, in kivy._event.EventObservers._dispatch
       File "c:\Users\Kelvin Loh\Documents\kivyMD\us_state_flaskcard_3.py", line 115, in <lambda>
         buttoncallback = lambda x : self.hint(hint_count)
     AttributeError: 'Mylayout' object has no attribute 'hint'

Body:
The reason behind this error lies in buttoncallback where you are triggering hint method. But you defined that method in the App's subclass namely, MainApp. So if you want to access that method from the Mylayout class, you have to first access the running app instance which you might do as follows,

        app = App.get_running_app()
        buttoncallback = lambda x : app.hint(hint_count)
        self.btn1.bind(on_press=buttoncallback)

Also, perhaps you may need some change in method hint,

    def hint(self, count):
        global hint_count
        hint_count = count

        word_length = len(self.word)

        if count < word_length:
            self.root.ids.hint_label.text = f'{self.word[count]}'
            hint_count +=1


问:
Vue.js Vite Build Error with <video><source> tags
I'm working on a Vue 3 app and am trying to swap out a static image for a video and it's throwing a

```<code>[vite] Build errored out.
Error: Unexpected character '' (Note that you need plugins to import files that are not JavaScript) at error (/myapp/node_modules/rollup/dist/shared/rollup.js:5275:30)
...
</code>```

This builds (not that you'd use an image but just to show):

<video class="w-2/3 xs:w-full" controls="controls" name="Video Name">
     <source src="/images/my_image.png">
</video>
```
<p>This does not:</p>
<pre class="lang-html prettyprint-override"><code><video class="w-2/3 xs:w-full" controls="controls" name="Video Name">
     <source src="/images/my_movie.mov">
</video>
</code>```

I'm new to Vite and am trying to understand why it seems to be wanting to import the video from the HTML tag.

答:
Vite seem can not resolve .mov video files. Read the document, set assetsInclude , build successed.

```<code>export default defineConfig({
  assetsInclude: ['**/*.mov'],
  ...
})
</code>```

Body:
I'm working on a Vue 3 app and am trying to swap out a static image for a video and it's throwing a

[vite] Build errored out.
Error: Unexpected character '' (Note that you need plugins to import files that are not JavaScript) at error (/myapp/node_modules/rollup/dist/shared/rollup.js:5275:30)
...

This builds (not that you'd use an image but just to show):

<video class="w-2/3 xs:w-full" controls="controls" name="Video Name">
     <source src="/images/my_image.png">
</video>

This does not:

<video class="w-2/3 xs:w-full" controls="controls" name="Video Name">
     <source src="/images/my_movie.mov">
</video>

I'm new to Vite and am trying to understand why it seems to be wanting to import the video from the HTML tag.

Body:
Vite seem can not resolve .mov video files. Read the document, set assetsInclude , build successed.

export default defineConfig({
  assetsInclude: ['**/*.mov'],
  ...
})


问:
Python: FastAPI & Celery tasks class. NotImplementedError: No result backend is configured
I'm developping an API where users can send me POST requests.
When requests are received, I want a queue to process their.

When my data requests are pushed on the celery Queue, I want my workers (remote server) to handle their.

For this, I use:

celery version 5.1.0 for workers

RabbitMQ version 3.9 for messages

I want my code to follow Class Programming methods so I would like to use Celery.Task class.

My code belwo:

server.py: is my FASTAPI application & endpoints. It should handle my task called client

tasks.py: is my celery.Celery instance & celery.Task classes.

# server.py

# Module imports
from fastapi import (
    FastAPI,
    Request
)
from fastapi.responses import (
    JSONResponse
)
import uvicorn

# Own module
from tasks import (
    client,
    add
)

# Environment
app = FastAPI()

# Endpoints
@app.post('/post/{name}')
def get_post(request: Request, name: str):
    result_not_working = client.delay(1, 2) # Not working
    result_working = add.delay(1, 2) # Working
    return JSONResponse(status_code=200, content={"status": 200, "message": f"You post {result.get()}"})

if __name__ == "__main__":
    uvicorn.run(app, host='', port=)

# tasks.py
from celery import (
    Celery,
    Task
)

# Environment
app = Celery('test_celery',
             broker=f"amqp://RABBITMQ_USER:RABBITMQ_PWD@RABBITMQ_HOST:RABBITMQ_PORT/RABBITMQ_DB",
             backend='rpc://')

# Class
class Client(Task):
    name = "tasks.PandasClient"
    def run(self, x, y, **kwargs):
        return x + y

@app.task(name="add")
def add(x, y):
    return x + y

client = Client()
app.tasks.register(client)
```

There is my problem: When I called my client object in server.py (client is an instance of Client, which is registered into my Celery queue), i get the error:

NotImplementedError: No result backend is configured.

BUT when I import and call my add function in server.py, it works with no problems.

Strange thing, when I run my worker with the command celery -A tasks worker --loglevel=info,
I can see:

It tells me my broker url is correctly set, so why not my backend (which works when I call the function add not the class Client.run)

The documentation does not explain how to build Task class

答:
I found the solution,

instead of registering my task with:

app.tasks.register(client)
```
<p>I wrote:</p>
<pre class="lang-py prettyprint-override"><code>app.register_task(client)
</code>```

and it works.

Body:
I'm developping an API where users can send me POST requests.
When requests are received, I want a queue to process their.

When my data requests are pushed on the celery Queue, I want my workers (remote server) to handle their.

For this, I use:

celery version 5.1.0 for workers

RabbitMQ version 3.9 for messages

I want my code to follow Class Programming methods so I would like to use Celery.Task class.

My code belwo:

server.py: is my FASTAPI application & endpoints. It should handle my task called client

tasks.py: is my celery.Celery instance & celery.Task classes.

# server.py

# Module imports
from fastapi import (
    FastAPI,
    Request
)
from fastapi.responses import (
    JSONResponse
)
import uvicorn

# Own module
from tasks import (
    client,
    add
)

# Environment
app = FastAPI()

# Endpoints
@app.post('/post/{name}')
def get_post(request: Request, name: str):
    result_not_working = client.delay(1, 2) # Not working
    result_working = add.delay(1, 2) # Working
    return JSONResponse(status_code=200, content={"status": 200, "message": f"You post {result.get()}"})

if __name__ == "__main__":
    uvicorn.run(app, host='', port=)

# tasks.py
from celery import (
    Celery,
    Task
)

# Environment
app = Celery('test_celery',
             broker=f"amqp://RABBITMQ_USER:RABBITMQ_PWD@RABBITMQ_HOST:RABBITMQ_PORT/RABBITMQ_DB",
             backend='rpc://')

# Class
class Client(Task):
    name = "tasks.PandasClient"
    def run(self, x, y, **kwargs):
        return x + y

@app.task(name="add")
def add(x, y):
    return x + y

client = Client()
app.tasks.register(client)

There is my problem: When I called my client object in server.py (client is an instance of Client, which is registered into my Celery queue), i get the error:

NotImplementedError: No result backend is configured.

BUT when I import and call my add function in server.py, it works with no problems.

Strange thing, when I run my worker with the command celery -A tasks worker --loglevel=info,
I can see:

It tells me my broker url is correctly set, so why not my backend (which works when I call the function add not the class Client.run)

The documentation does not explain how to build Task class

Body:
I found the solution,

instead of registering my task with:

app.tasks.register(client)

I wrote:

app.register_task(client)

and it works.


问:
Ruby - Calling another Class method in super class
```<code>class A
  def self.a
    puts "self: #{self}; superclass: #{superclass}"
  end
end

class B < A
  class << self; undef_method(:a); end  # I'm not allowed to use B.a
  def self.b
    # here I want to call A.a with B as self.
  end
end

A.a  #=> self: A; superclass: Object
B.b  #=> self: B; superclass: A (expected)
</code>```

I don't want an alias_method solution. I'm looking for something like this.

UPDATE

The solution doesn't need to be any similar to the link above; it's only a suggestion. For example, I tried to do:

```<code>class B < A
  def self.b
    instance_eval(&A.method(:a).to_proc)
  end
end
</code>```

but this way I get an weird ArgumentError on Ruby 1.8.7.

答:
Only solution here is to use B.a.

```<code>class B < A
  def self.b
    a #=> self: B; superclass: A
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
class A
  def self.a
    puts "self: #{self}; superclass: #{superclass}"
  end
end

class B < A
  class << self; undef_method(:a); end  # I'm not allowed to use B.a
  def self.b
    # here I want to call A.a with B as self.
  end
end

A.a  #=> self: A; superclass: Object
B.b  #=> self: B; superclass: A (expected)

I don't want an alias_method solution. I'm looking for something like this.

UPDATE

The solution doesn't need to be any similar to the link above; it's only a suggestion. For example, I tried to do:

class B < A
  def self.b
    instance_eval(&A.method(:a).to_proc)
  end
end

but this way I get an weird ArgumentError on Ruby 1.8.7.

Body:
Only solution here is to use B.a.

class B < A
  def self.b
    a #=> self: B; superclass: A
  end
end


问:
Python2 and Python3 both in windows 10
I used Anaconda for python.

python2 is installed in
   D:\Python\Anaconda2

python3 is installed in
   D:\Python\Anaconda3

python3 is the default.

created two environmental variables with name: python2 and python2 and selected respective python.exe from different folder respectively.

my setup.py supports only python2.

when i run command from cmd python setup.py install it says it does not support.
If I rename D:\Python\Anaconda2\python.exe to D:\Python\Anaconda2\python2.exe and change the environment path file accordingly it works. But I dnt want to change the file name (as it may break other apps, like conda says unable to create process, etc).

Windows 10 Pro, 64 bit.
setup.py location:
E:\Program Files\IBM\ILOG\CPLEX_Studio1251\cplex\python\x64_win64

How to overcome this? Want python2 setup.py install for python2 compiler and python3 setup.py install for python3 compiler, without renaming.

How to install setup.py by running  D:\Python\Anaconda2\python.exe?

答:
Here is how you can use both python2 and python3 in windows 10

Install python2 from here https://www.python.org/downloads/

Install python3 from here https://www.python.org/downloads/

Enter windows keys and type "Edit the system environment variables"

Click on Path and enter Edit button.

Add path to both version of python. (Important) Here i have listed python3 and python2 in order because i want to see version 2 by python --version and version3 by python3 --version.

Go to C:\python310 in windows (or whatever the name is for python3) and update executable file to python3 instead of python.

Save and exit.

Now,

python --version // python 2

python3 --version // python 3

If you want it otherwise, update executable file of python2 to python2 instead of python. And update PATH variables to list python2 and python3 in order.

Title: Python2 and Python3 both in windows 10


问:
C# Or operator Issue
I am pretty sure someone of you can help me with this issue.
I do not find and do not understand the solution.

```<code>if (hero.IsAlive || creature.IsAlive == false)
        {
            if (hero.IsAlive == true)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                EnemyHitInterface();
                Console.ForegroundColor = ConsoleColor.White;
                Thread.Sleep(1500);
                hero.Exp += 150;
                baseSetting.YouWin();
                hero.UpdateLvL();
                hero.CharacterInterface(hero);
                hero.PrintStatsHero();
                Console.ReadKey();
                CheckForItem();
                hero.PrintStatsHero();
                Console.ReadKey();
            }
            else if (creature.IsAlive == true)
            {
                Console.Clear();
                CenterText("You are dead. See you next time...", 15);
                Console.ReadKey();
                Environment.Exit(0);
            }
        }
</code>```

Simple if Operation with asks in my opinion, as soon as the hero dies or the creature it will get triggered.
If the creature dies, everything is fine, but if the hero dies it wont be triggered.
What is the think i do not understand?

For me it is like:

When Hero or Creature dies, go in
If hero is alive do this
if creature is alive do this

But like I said, as for the creature it wont work

答:
This looks a simple logic mistake:

```<code>if (hero.IsAlive || creature.IsAlive == false)
</code>```

Is the same as:

```<code>if ((hero.IsAlive == true) || (creature.IsAlive == false))
</code>```

But then, inside the if block you're checking:

```<code>if (hero.IsAlive == true)
        {
         ...
        }
        else if (creature.IsAlive == true)
        {
         ...
        }
    }
</code>```

Which, if you combine them is:

```<code>if ((hero.isAlive == true && hero.IsAlive == true) || (creature.IsAlive == false && hero.IsAlive == true))
{
    ...
}
else if ((hero.IsAlive == true && creature.IsAlive == true) || (creature.IsAlive == false && creature.IsAlive == true))
{
    ...
}
</code>```

But (creature.IsAlive == false && creature.IsAlive == true) is always false, and (hero.isAlive == true && hero.IsAlive == true) is always true.

So, to rejig your logic:

```<code>if (hero.IsAlive != creature.IsAlive ) //Either the hero or creature is dead
{
    if (hero.IsAlive)
    {
        //Hero is alive, creature is dead
    }
    else
    {
       //Creature is alive, hero is dead.
    }
}
else if (hero.IsAlive)
{
    //Hero and creature are both alive
}
else
{
    //Hero and creature are both dead
}
</code>```

Should capture the behaviour you want.

Title: C# Or operator Issue

Body:
I am pretty sure someone of you can help me with this issue.
I do not find and do not understand the solution.

if (hero.IsAlive || creature.IsAlive == false)
        {
            if (hero.IsAlive == true)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                EnemyHitInterface();
                Console.ForegroundColor = ConsoleColor.White;
                Thread.Sleep(1500);
                hero.Exp += 150;
                baseSetting.YouWin();
                hero.UpdateLvL();
                hero.CharacterInterface(hero);
                hero.PrintStatsHero();
                Console.ReadKey();
                CheckForItem();
                hero.PrintStatsHero();
                Console.ReadKey();
            }
            else if (creature.IsAlive == true)
            {
                Console.Clear();
                CenterText("You are dead. See you next time...", 15);
                Console.ReadKey();
                Environment.Exit(0);
            }
        }

Simple if Operation with asks in my opinion, as soon as the hero dies or the creature it will get triggered.
If the creature dies, everything is fine, but if the hero dies it wont be triggered.
What is the think i do not understand?

For me it is like:

When Hero or Creature dies, go in
If hero is alive do this
if creature is alive do this

But like I said, as for the creature it wont work

Body:
This looks a simple logic mistake:

if (hero.IsAlive || creature.IsAlive == false)

Is the same as:

if ((hero.IsAlive == true) || (creature.IsAlive == false))

But then, inside the if block you're checking:

if (hero.IsAlive == true)
        {
         ...
        }
        else if (creature.IsAlive == true)
        {
         ...
        }
    }

Which, if you combine them is:

if ((hero.isAlive == true && hero.IsAlive == true) || (creature.IsAlive == false && hero.IsAlive == true))
{
    ...
}
else if ((hero.IsAlive == true && creature.IsAlive == true) || (creature.IsAlive == false && creature.IsAlive == true))
{
    ...
}

But (creature.IsAlive == false && creature.IsAlive == true) is always false, and (hero.isAlive == true && hero.IsAlive == true) is always true.

So, to rejig your logic:

if (hero.IsAlive != creature.IsAlive ) //Either the hero or creature is dead
{
    if (hero.IsAlive)
    {
        //Hero is alive, creature is dead
    }
    else
    {
       //Creature is alive, hero is dead.
    }
}
else if (hero.IsAlive)
{
    //Hero and creature are both alive
}
else
{
    //Hero and creature are both dead
}

Should capture the behaviour you want.


问:
how to print out something instead of geting an error when list.pop function is out of range?
My training course task is to make a shoppingcart, everything works as intented but I can't figure out the function pop out of range problem.

My code:

```<code># -*- coding: cp1252 -*-
class Cart:

    shoppingcart = []

    def addstuff(self):
        esine = input("What will be added?: ")
        self.shoppingcart.append(esine)

    def remove(self):
        esine2 = input("Which item is deleted?: ")
        self.shoppingcart.pop(int(esine2))

def main():
    customer = Cart()
    while True:
        selection = input("Would you like to \n"
                          "(1)Add or \n"
                          "(2)Remove items or \n"
                          "(3)Quit: ")

        if selection == "1":
            customer.addstuff()

        if selection == "2":
            print("There are", len(customer.shoppingcart), "items in the list.")
            customer.remove()

        if selection == "3":
            print("The following items remain in the list:")
            for i in \
                    customer.shoppingcart:
                print(i)

            break

        if selection > "3":
            print("Incorrect selection.")

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

Problem is while deleting(poping) an item that is out of range it gives an error but instead should print out "incorrect selection."
I tried adding if True and else argument into def remove part but that doesn't help.

答:
Use try except blocks.

emptylist = []
try:
    emptylist.pop()
except IndexError:
    print('pop failed')
```
<p>In your code:</p>
<pre class="lang-py prettyprint-override"><code>def remove(self):
    esine2 = input("Which item is deleted?: ")
    try:
        self.shoppingcart.pop(int(esine2))
    except IndexError:
        print('no item at index {}'.format(int(esine2))
</code>```

Do note that pop(i) removes the item in the list at place i, not the item with value i.

Body:
My training course task is to make a shoppingcart, everything works as intented but I can't figure out the function pop out of range problem.

My code:

# -*- coding: cp1252 -*-
class Cart:

    shoppingcart = []

    def addstuff(self):
        esine = input("What will be added?: ")
        self.shoppingcart.append(esine)

    def remove(self):
        esine2 = input("Which item is deleted?: ")
        self.shoppingcart.pop(int(esine2))

def main():
    customer = Cart()
    while True:
        selection = input("Would you like to \n"
                          "(1)Add or \n"
                          "(2)Remove items or \n"
                          "(3)Quit: ")

        if selection == "1":
            customer.addstuff()

        if selection == "2":
            print("There are", len(customer.shoppingcart), "items in the list.")
            customer.remove()

        if selection == "3":
            print("The following items remain in the list:")
            for i in \
                    customer.shoppingcart:
                print(i)

            break

        if selection > "3":
            print("Incorrect selection.")

if __name__ == "__main__":
    main()

Problem is while deleting(poping) an item that is out of range it gives an error but instead should print out "incorrect selection."
I tried adding if True and else argument into def remove part but that doesn't help.

Body:
Use try except blocks.

emptylist = []
try:
    emptylist.pop()
except IndexError:
    print('pop failed')

In your code:

def remove(self):
    esine2 = input("Which item is deleted?: ")
    try:
        self.shoppingcart.pop(int(esine2))
    except IndexError:
        print('no item at index {}'.format(int(esine2))

Do note that pop(i) removes the item in the list at place i, not the item with value i.


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答:
This answer is for Java and WebDriverManager users.

You can specify chrome driver version like this before start chrome.

```<code>WebDriverManager.chromedriver().browserVersion("97").setup();
</code>```

You can work around this problem.

Update

This ChromeDriver bug has fixed

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

Body:
This answer is for Java and WebDriverManager users.

You can specify chrome driver version like this before start chrome.

WebDriverManager.chromedriver().browserVersion("97").setup();

You can work around this problem.

Update

This ChromeDriver bug has fixed


问:
IntelIJ copy line without selection
I was wondering if there is a way to just remove the selection when I copy a line by doing ctrl + c on a line

before: I just have my cursor in a line:

after: I just press ctrl + c

I dont like how I have to do an extra step to unselect, there must be a way to just remove the select without removing any functionality. Vscode has it working perfectly but I would love to have the same experience in IntelIJ

答:
To just copy and paste the line, you don't need to select it at all.

Just use action Duplicate line or selection Ctrl + D
and Move Statement Up/Down Alt+Shift+Up or Alt+Shift+Down to the desired position with .

See JetBrains blog :

Like cut, we can copy a whole line with ⌘C, or Ctrl+C, without having to highlight it first, and paste this too. Sometimes it might be more useful to duplicate the line instead with ⌘D, or Ctrl+D.

When duplicating a line, the line will be copied directly as new line below and cursor is placed where it has been before.

Watch the youtube demo IntelliJ IDEA Tricks - Lecture 7: Duplicate and Delete Lines (0:41)

See also:

How to select/copy current line without using mouse in IntelliJ IDEA

JetBrains IDEA help: Write and edit source code, section Lines of Code

Dev.to blog: IntelliJ style line duplication in Visual Studio Code

Title: IntelIJ copy line without selection


问:
Oracle SQL Developer - SUBSTR and LIKE
I have a column NAME_SURNAME (made of names and surnames) from a table people:

```<code>John Smith
Tim Burton
Harry Potter
</code>```

I need to write a query to obtain only the names:

```<code>John
Tim
Harry
</code>```

I am trying in this way nad it doesn't work:

```<code>select NAME_SURNAME, substr(NAME_SURNAME, 1, LIKE '% %')
from PEOPLE
</code>```

I don't figure out how to use LIKE in this exercise.

Thank you really much

答:
Use INSTR with SUBSTR to take a substring up to the first space:

SELECT NAME_SURNAME, SUBSTR(NAME_SURNAME, 1, INSTR(NAME_SURNAME, ' ') - 1)
FROM PEOPLE;
```
<p><h2>Demo</h2></p>
<p>For a regex approach, we can use <code>REGEXP_SUBSTR</code>:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT NAME_SURNAME, REGEXP_SUBSTR(NAME_SURNAME, '^\S+') AS FIRST_NAME
FROM PEOPLE;
</code>```

Title: Oracle SQL Developer - SUBSTR and LIKE

Body:
I have a column NAME_SURNAME (made of names and surnames) from a table people:

John Smith
Tim Burton
Harry Potter

I need to write a query to obtain only the names:

John
Tim
Harry

I am trying in this way nad it doesn't work:

select NAME_SURNAME, substr(NAME_SURNAME, 1, LIKE '% %')
from PEOPLE

I don't figure out how to use LIKE in this exercise.

Thank you really much

Body:
Use INSTR with SUBSTR to take a substring up to the first space:

SELECT NAME_SURNAME, SUBSTR(NAME_SURNAME, 1, INSTR(NAME_SURNAME, ' ') - 1)
FROM PEOPLE;

Demo

For a regex approach, we can use REGEXP_SUBSTR:

SELECT NAME_SURNAME, REGEXP_SUBSTR(NAME_SURNAME, '^\S+') AS FIRST_NAME
FROM PEOPLE;


问:
Skipping errors in a loop? (PHP)
I have a loop where the code loops and in every loop it connects to different server and then makes MySQL query. However sometimes one of the loops/queries cannot reach to the end and all the code breaks. Is there a way where if the loop gives error then skip the processes / move to next loop?</p>

答:
Use "continue" to skip to the next item in hte loop:

continue

Title: Skipping errors in a loop? (PHP)


问:
How to give users a user role based on their email in Python?
I'm creating a registration page which contains 3 input fields: name, email, password. In my User model class, I've created a user_role method:

```<code>from models.base_model import BaseModel
from flask_login import UserMixin
import peewee as pw

class Users(BaseModel, UserMixin):
   name = pw.CharField(max_length=100, unique=True)
   email = pw.CharField(max_length=100, unique=True)
   password = pw.CharField()
   role = pw.CharField(max_length=50)

   def __init__(self, name, email, password):
       self.name = name
       self.email = email
       self.password = password

   def __repr__(self):
       return f"User: {self.name}, {self.email}, {self.role}"

   def user_roles(self):
       user_email = self.email
       self.roles = ["user","admin"]

    check_email = ["test@testing.com"]

    if user_email == check_email:
        return self.roles == "admin"
    else:
        return self.roles == "user"
</code>```

The check_email is use to check if the email that a user fill in the field is equal to the check_email value. If it does, the role should be assign as 'admin'. In my route file, this is what it look like when saving to the database:

```<code>if form.validate_on_submit():
     name = form.name.data
     email = form.email.data
     raw_password = form.password.data
     password = generate_password_hash(raw_password, method="sha256", salt_length=20)
     role = Users.user_roles(email)

     new_user = Users(name=name, email=email, password=password, role=role)
</code>```

Now when I tried to test out the registration form, this is the error it gave me:

I want to know is there a way to fix this error?

PS: I'm doing this for testing purposes to see if I could assign user role. I would probably add more user roles in the future, so I don't think Flask-Admin could help me

答:
You have your user_roles method defined as a class method when it can and should probably be a static method. Also you are calling user_roles with the email string but the try to access self.email in the method. Just change that and you are good to go.

def get_role(email):
       check_email = "test@testing.com"
       if email == check_email:
           return "admin"
       else:
           return "user"
```

Edit: Forgot to remove brackets as we don't want an array but just the string.

Body:
I'm creating a registration page which contains 3 input fields: name, email, password. In my User model class, I've created a user_role method:

from models.base_model import BaseModel
from flask_login import UserMixin
import peewee as pw

class Users(BaseModel, UserMixin):
   name = pw.CharField(max_length=100, unique=True)
   email = pw.CharField(max_length=100, unique=True)
   password = pw.CharField()
   role = pw.CharField(max_length=50)

   def __init__(self, name, email, password):
       self.name = name
       self.email = email
       self.password = password

   def __repr__(self):
       return f"User: {self.name}, {self.email}, {self.role}"

   def user_roles(self):
       user_email = self.email
       self.roles = ["user","admin"]

    check_email = ["test@testing.com"]

    if user_email == check_email:
        return self.roles == "admin"
    else:
        return self.roles == "user"

The check_email is use to check if the email that a user fill in the field is equal to the check_email value. If it does, the role should be assign as 'admin'. In my route file, this is what it look like when saving to the database:

if form.validate_on_submit():
     name = form.name.data
     email = form.email.data
     raw_password = form.password.data
     password = generate_password_hash(raw_password, method="sha256", salt_length=20)
     role = Users.user_roles(email)

     new_user = Users(name=name, email=email, password=password, role=role)

Now when I tried to test out the registration form, this is the error it gave me:

I want to know is there a way to fix this error?

PS: I'm doing this for testing purposes to see if I could assign user role. I would probably add more user roles in the future, so I don't think Flask-Admin could help me

Body:
You have your user_roles method defined as a class method when it can and should probably be a static method. Also you are calling user_roles with the email string but the try to access self.email in the method. Just change that and you are good to go.

def get_role(email):
       check_email = "test@testing.com"
       if email == check_email:
           return "admin"
       else:
           return "user"

Edit: Forgot to remove brackets as we don't want an array but just the string.


问:
Increment a counter inside a byte array
I have an array of 5 bytes (fixed length). First 21 bits represent a counter and the rest 19 some id. I need to increment the counter by one. How do I do that?</p>

答:
I'm not sure I solved your problem.

public class Main
{
    public static void main(String[] args)
    {
        //################
        //#  BIG ENDIAN  #
        //################

        //initial counter == 1 (b0000_0000_0000_0000_0000_1)
        //initial ids == 3 (b000_0000_0000_0000_0011)
        byte[] array = { 0, 0, 8, 0, 3 };
        int counter = ((array[0] & 0xFF) << 13)
            | ((array[1] & 0xFF) << 5)
            | ((array[2] & 0xF8) >> 3);
        System.out.println(counter); //1
        ++counter;
        System.out.println(counter); //2
        //Repack the counter into the array.
        array[0] = (byte)((counter & 0x1FE000) >> 13);
        array[1] = (byte)((counter & 0x1FE0) >> 5);
        array[2] = (byte)(((counter & 0x1F) << 3)| (array[2] & 0x7));
        System.out.println(Arrays.toString(array)); //[0, 0, 16, 0, 3]
        //Retry & Verify
        counter = ((array[0] & 0xFF) << 13) //Same as above. Nothing is changed.
            | ((array[1] & 0xFF) << 5)
            | ((array[2] & 0xF8) >> 3);
        System.out.println(counter); //2
        ++counter;
        System.out.println(counter); //3

        //###################
        //#  LITTLE ENDIAN  #
        //###################

        //initial ids == 3 (b0000_0000_0000_0000_011)
        //initial counter == 1 (b0_0000_0000_0000_0000_0001)
        byte[] arr = { 0, 0, 96, 0, 1 };
        counter = ((arr[2] & 0x1F) << 16)
            | ((arr[3] & 0xFF) << 8)
            | (arr[4] & 0xFF);
        System.out.println(counter); //1
        ++counter;
        System.out.println(counter); //2
        //Repack the counter into the array.
        arr[2] = (byte)((arr[2] & 0xE0)  | ((counter & 0x1F0000) >> 16));
        arr[3] = (byte)((counter & 0xFF00) >> 8);
        arr[4] = (byte)(counter & 0xFF);
        System.out.println(Arrays.toString(arr)); //[0, 0, 96, 0, 2]
        //Retry & Verify
        counter = ((arr[2] & 0x1F) << 16) //Same as above. Nothing is changed.
            | ((arr[3] & 0xFF) << 8)
            | (arr[4] & 0xFF);
        System.out.println(counter); //2
        ++counter;
        System.out.println(counter); //3
    }

}
```

Title: Increment a counter inside a byte array


问:
create-react-app --template typescript doesn't work
When I run the command

npx create-react-app my-app --template typescript
```

only a JS project is created, no .tsx file whatsoever.

According to the CRA's TS guide, the command needs react-scripts@2.1.0 or higher.

But the version listed in my-app's package.json is only 0.9.5.

And the globally installed version is react-scripts@5.0.0, which is latest.

My environment:

Node 16.13.2 (installed with this guide)

npm 8.4.1

npx 5.0.0

Xubuntu 21.10

答:
It sounds like you may have a very old copy of create-react-app installed globally, so npx is using that one rather than the latest. To remove it, use:

```<code>npm uninstall -g create-react-app
</code>```

Then npx create-react-app will pick up the latest one, which should handle that command line correctly.

(I tested this by installing an old version globally, then using npx and sure enough, it was the old version that ran. I installed v1.0.0 and indeed, it didn't do anything with the --template argument. But even it installed react-scripts v5.)

Body:
When I run the command

npx create-react-app my-app --template typescript

only a JS project is created, no .tsx file whatsoever.

According to the CRA's TS guide, the command needs react-scripts@2.1.0 or higher.

But the version listed in my-app's package.json is only 0.9.5.

And the globally installed version is react-scripts@5.0.0, which is latest.

My environment:

Node 16.13.2 (installed with this guide)

npm 8.4.1

npx 5.0.0

Xubuntu 21.10

Body:
It sounds like you may have a very old copy of create-react-app installed globally, so npx is using that one rather than the latest. To remove it, use:

npm uninstall -g create-react-app

Then npx create-react-app will pick up the latest one, which should handle that command line correctly.

(I tested this by installing an old version globally, then using npx and sure enough, it was the old version that ran. I installed v1.0.0 and indeed, it didn't do anything with the --template argument. But even it installed react-scripts v5.)


问:
Eject excess space from string in C
I need to write a function which will eject excess space from string in C.

Example:

```<code>char s[]="  abcde    abcde    ";
</code>```

OUTPUT:

```<code>"abcde abcde"
</code>```

Code:

```<code>#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
  int i, x;
  for (i = x = 0; str[i]; ++i)
    if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
      str[x++] = str[i];
  if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
  return str;
}

int main() {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"", eject(s));
  return 0;
}
</code>```

This code doesn't work for string "          "
If this string is found program should print:

```<code>""
</code>```

How to fix this?

答:
A slightly more advanced answer just for reference - suppose you were tasked in writing a professional library for the use in real world programs. Then one would first list all requirements that make sense:

It's good practice to treat strings as "immutable" - that is, build up a new string based on the old one rather than in-place replacement.

Take the destination string as parameter but also return a pointer to it (similar to strcpy etc functions).

In case of empty strings, set the destination string empty too.

Remove all "white space" not just the ' ' character.

Instead of always inserting a space character after each word, why not insert a variable delimiter? Might as well be something like , or ;.

No delimiter should be inserted after the last word.

The algorithm should only traverse the data once for performance reasons. That is, internal calls like strlen etc are unacceptable.

Byte by byte iteration is fine - we need not care about alignment.

Then we might come up with something like this:

```<code>#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>

char* trim_delimit (char* restrict dst, const char* restrict src, char delim)
{
  char* start = dst;
  *dst = '\0';

  bool remove_spaces = true;
  char* insert_delim_pos = NULL;

  for(; *src != '\0'; src++)
  {
    if(remove_spaces)
    {
      if(!isspace(*src))
      {
        remove_spaces = false;
        if(insert_delim_pos != NULL)
        {
          // we only get here if more words were found, not yet at the end of the string
          *insert_delim_pos = delim;
          insert_delim_pos = NULL;
        }
      }
    }

    if(!remove_spaces)
    {
      if(isspace(*src))
      {
        remove_spaces = true;
        insert_delim_pos = dst; // remember where to insert delimiter for later
      }
      else
      {
        *dst = *src;
      }
      dst++;
    }
  }

  return start;
}
</code>```

Test cases:

```<code>int main (void)
{
  char s[]="  abcde    abcde    ";
  char trimmed[100];

  puts(trim_delimit(trimmed, s, ' '));
  puts(trim_delimit(trimmed, "", ' '));
  puts(trim_delimit(trimmed, s, ';'));
}
</code>```

Output:

```<code>abcde abcde

abcde;abcde
</code>```

Title: Eject excess space from string in C

Body:
I need to write a function which will eject excess space from string in C.

Example:

char s[]="  abcde    abcde    ";

OUTPUT:

"abcde abcde"

Code:

#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
  int i, x;
  for (i = x = 0; str[i]; ++i)
    if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
      str[x++] = str[i];
  if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
  return str;
}

int main() {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"", eject(s));
  return 0;
}

This code doesn't work for string "          "
If this string is found program should print:

""

How to fix this?

Body:
A slightly more advanced answer just for reference - suppose you were tasked in writing a professional library for the use in real world programs. Then one would first list all requirements that make sense:

It's good practice to treat strings as "immutable" - that is, build up a new string based on the old one rather than in-place replacement.

Take the destination string as parameter but also return a pointer to it (similar to strcpy etc functions).

In case of empty strings, set the destination string empty too.

Remove all "white space" not just the ' ' character.

Instead of always inserting a space character after each word, why not insert a variable delimiter? Might as well be something like , or ;.

No delimiter should be inserted after the last word.

The algorithm should only traverse the data once for performance reasons. That is, internal calls like strlen etc are unacceptable.

Byte by byte iteration is fine - we need not care about alignment.

Then we might come up with something like this:

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>

char* trim_delimit (char* restrict dst, const char* restrict src, char delim)
{
  char* start = dst;
  *dst = '\0';

  bool remove_spaces = true;
  char* insert_delim_pos = NULL;

  for(; *src != '\0'; src++)
  {
    if(remove_spaces)
    {
      if(!isspace(*src))
      {
        remove_spaces = false;
        if(insert_delim_pos != NULL)
        {
          // we only get here if more words were found, not yet at the end of the string
          *insert_delim_pos = delim;
          insert_delim_pos = NULL;
        }
      }
    }

    if(!remove_spaces)
    {
      if(isspace(*src))
      {
        remove_spaces = true;
        insert_delim_pos = dst; // remember where to insert delimiter for later
      }
      else
      {
        *dst = *src;
      }
      dst++;
    }
  }

  return start;
}

Test cases:

int main (void)
{
  char s[]="  abcde    abcde    ";
  char trimmed[100];

  puts(trim_delimit(trimmed, s, ' '));
  puts(trim_delimit(trimmed, "", ' '));
  puts(trim_delimit(trimmed, s, ';'));
}

Output:

abcde abcde

abcde;abcde


问:
Autodesk Revit plugin crashing
I am working on a plugin for Autodesk Revit 2014 converting room geometry to conceptual masses.
But revit completely shuts down when i run the script.
I've isolated the code that's causing the crash:

```<code>Extrusion m_Extrusion = m_FamDoc.FamilyCreate.NewExtrusion(true, m_CurveArArray, m_SketchPlane, 8);
</code>```

And the revit logs show this error:

DBG_INFO: Detected unfrozen change of selection.: line 571 of
  n:\build\2014_ship_x64_inst_20130308_1515\source\revit\revitui\modscope\ModScope.cpp

Does anyone know if there is something wrong with my use of the extrusion command? Or is it something in Revit?

Thanks in advance.

答:
I had same problem in my code by define any kind of Array.
By huge search after several week I find nothing but I realized that I used dot net framework version 5.0, when I changed it to dot net framework 4.8 everything got OK.</p>

Title: Autodesk Revit plugin crashing

Body:
I am working on a plugin for Autodesk Revit 2014 converting room geometry to conceptual masses.
But revit completely shuts down when i run the script.
I've isolated the code that's causing the crash:

Extrusion m_Extrusion = m_FamDoc.FamilyCreate.NewExtrusion(true, m_CurveArArray, m_SketchPlane, 8);

And the revit logs show this error:

DBG_INFO: Detected unfrozen change of selection.: line 571 of
  n:\build\2014_ship_x64_inst_20130308_1515\source\revit\revitui\modscope\ModScope.cpp

Does anyone know if there is something wrong with my use of the extrusion command? Or is it something in Revit?

Thanks in advance.


问:
"The reply to this interaction has not been sent or deferred." Is an error I keep getting on discord.js v13
So I've just completed writing a ping.js, echo.js, guildMemberAdd.js, and guildMemberRemove.js and I'm moving on to writing a ban.js and kick.js and currently all slash commands work except the latest commands which is kick and ban. I keep getting the error that "The reply to this interaction has not been sent or deferred." and I have no idea how to find a solution to it. I originally had it written "return interaction.followUp" and I switched them all to "await interaction.followUp" hoping it'd be the solution the problem, but it seems like that wasn't it. I originally also had it written "run: async (interaction) => {" but then I get the error that "command.execute" is not a function so I switched it to "async execute (intereaction) {" I've also tried a couple of other things, but still can't seem to find a fix, does anyone have any idea on this? I'll leave my interactionCreate.js and kick.js below

interactionCreate.js

```<code>
    module.exports = {
        name: "interactionCreate",
        async execute(interaction) {
            if (!interaction.isCommand()) return;

            const command = interaction.client.commands.get(interaction.commandName);

            if (!command) return;

            try {
                await command.execute(interaction);
            } catch (err) {
                if (err) console.error(err);

                await interaction.reply({
                    content: "An error occured while executing that command.",
                    ephemeral: true
                });
            }

        }
    }

</code>```

kick.js

```<code>
    const { SlashCommandBuilder } = require('@discordjs/builders');
    const { MessageEmbed } = require("discord.js")

    module.exports = {
        data: new SlashCommandBuilder()
        .setName("kick")
        .setDescription("Allows the admin or owner to kick the member.")
        .addUserOption((option) => option.setName('user').setDescription('The person who you want to kick').setRequired(true))
        .addStringOption(option => option.setName('reason').setDescription('Reason to kick member').setRequired(true)),
        async execute (interaction) {

           if(!interaction.member.permissions.has("KICK_MEMBERS")) return interaction.followUp({ content: "You do not have the power to kick that member.", ephemeral: true })

            const user = interaction.options.getUser('user')
            const member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).catch(err => {})

            if(!member) return interaction.followUp({ content: " | Well this is awkward... I'm unable to get details related to given member.", ephemeral: true });
            const reason = interaction.options.getString('reason')

            if(!member.kickable || member.user.id === member.user.id)
            await interaction.followUp({ content: " | I am unable to kick this member", ephemeral: true });

            if(interaction.member.roles.highest.position <= member.roles.highest.position)
            await interaction.followUp({ content: 'This member has equal or higher power as you so I cannot kick them.', ephemeral: true })

            const embed = new MessageEmbed()
            .setDescription(`**${member.user.tag}** is kicked out from the cookout for \`${reason}\``)
            .setColor("#5104DB")
            .setFooter({ text: "Kick Member" })
            .setTimestamp()

            await interaction.reply(`You are kicked from **\`${interaction.guild.name}\`** for \`${reason}\``).catch(err => {})
            member.kick();

            await interaction.followUp({ embeds: [ embed ]})

        }
    }

</code>```

答:
The error comes from line 19 and 22

await interaction.followUp({ content: " | I am unable to kick this member", ephemeral: true });
```
<pre class="lang-js prettyprint-override"><code>await interaction.followUp({ content: 'This member has equal or higher power as you so I cannot kick them.', ephemeral: true })
</code>```

You attempt to followUp to an interaction, with no reply as the error message suggests. You can change this to reply as you do further down in the code, which will work.

Note: you will likely receive unexpected errors if you don't return or stop the code when the conditions above are met

Body:
So I've just completed writing a ping.js, echo.js, guildMemberAdd.js, and guildMemberRemove.js and I'm moving on to writing a ban.js and kick.js and currently all slash commands work except the latest commands which is kick and ban. I keep getting the error that "The reply to this interaction has not been sent or deferred." and I have no idea how to find a solution to it. I originally had it written "return interaction.followUp" and I switched them all to "await interaction.followUp" hoping it'd be the solution the problem, but it seems like that wasn't it. I originally also had it written "run: async (interaction) => {" but then I get the error that "command.execute" is not a function so I switched it to "async execute (intereaction) {" I've also tried a couple of other things, but still can't seem to find a fix, does anyone have any idea on this? I'll leave my interactionCreate.js and kick.js below

interactionCreate.js

    module.exports = {
        name: "interactionCreate",
        async execute(interaction) {
            if (!interaction.isCommand()) return;

            const command = interaction.client.commands.get(interaction.commandName);

            if (!command) return;

            try {
                await command.execute(interaction);
            } catch (err) {
                if (err) console.error(err);

                await interaction.reply({
                    content: "An error occured while executing that command.",
                    ephemeral: true
                });
            }

        }
    }

kick.js

    const { SlashCommandBuilder } = require('@discordjs/builders');
    const { MessageEmbed } = require("discord.js")

    module.exports = {
        data: new SlashCommandBuilder()
        .setName("kick")
        .setDescription("Allows the admin or owner to kick the member.")
        .addUserOption((option) => option.setName('user').setDescription('The person who you want to kick').setRequired(true))
        .addStringOption(option => option.setName('reason').setDescription('Reason to kick member').setRequired(true)),
        async execute (interaction) {

           if(!interaction.member.permissions.has("KICK_MEMBERS")) return interaction.followUp({ content: "You do not have the power to kick that member.", ephemeral: true })

            const user = interaction.options.getUser('user')
            const member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).catch(err => {})

            if(!member) return interaction.followUp({ content: " | Well this is awkward... I'm unable to get details related to given member.", ephemeral: true });
            const reason = interaction.options.getString('reason')

            if(!member.kickable || member.user.id === member.user.id)
            await interaction.followUp({ content: " | I am unable to kick this member", ephemeral: true });

            if(interaction.member.roles.highest.position <= member.roles.highest.position)
            await interaction.followUp({ content: 'This member has equal or higher power as you so I cannot kick them.', ephemeral: true })

            const embed = new MessageEmbed()
            .setDescription(`**${member.user.tag}** is kicked out from the cookout for \`${reason}\``)
            .setColor("#5104DB")
            .setFooter({ text: "Kick Member" })
            .setTimestamp()

            await interaction.reply(`You are kicked from **\`${interaction.guild.name}\`** for \`${reason}\``).catch(err => {})
            member.kick();

            await interaction.followUp({ embeds: [ embed ]})

        }
    }

Body:
The error comes from line 19 and 22

await interaction.followUp({ content: " | I am unable to kick this member", ephemeral: true });

await interaction.followUp({ content: 'This member has equal or higher power as you so I cannot kick them.', ephemeral: true })

You attempt to followUp to an interaction, with no reply as the error message suggests. You can change this to reply as you do further down in the code, which will work.

Note: you will likely receive unexpected errors if you don't return or stop the code when the conditions above are met


问:
ReactJS problem with
 element visibility
I have 3 input fields with Name, Address and Year. I pass the length of all the 3 variables as props to this Error component. The errorText should be hidden by default and turn visible if the name is less than 4 letters.

Problem is when I input a name that is less than 4 letters, it changes the errorText variable to the correct "Error in field: name", which I can see by the alert, but the P element still does not change and stays empty.

Also reason why the errorText is not already the one I need by default is, I have more If statements for every alternative instance. For example, if Address and Name are less than 4, then it needs to say "Error in field: address, name".

What could be the issue here? Thanks in advance.

```<code>const Error = (props) => {
    let errorText = '';
    let isVisible = false;

    if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        errorText = "Error in field: name"
        isVisible = true;
        alert("errorText: " + errorText); //This alert is only for testing
    }

    return (
    <div>
        <p style={{visibility: isVisible ? "visible" : "hidden"}}>{errorText}</p>
    </div>
    )
}
</code>```

Error is rendered by the following button inside a return:

```<code><button type="submit" onClick={() => Error({nameLength, addressLength, yearLength})}>Add</button>
</code>```

答:
In React you should think of components as functions (state and props) -> elements
Keeping this in mind, here is a simple implementation of your usecase.

Note that Error is always rendered and it reacts to the props values that are passed to it

```<code>import { useState } from "react";
import "./styles.css";

const Error = ({ nameLength, addressLength, yearLength }) => {
  let errorText = "";

  if (nameLength < 4 && addressLength >= 4 && yearLength >= 4) {
    errorText = "error in field name";
  }

  return errorText ? <div>{errorText}</div> : null;
};

export default function App() {
  const [nameValue, setNameValue] = useState("");
  const [addressValue, setAddressValue] = useState("");
  const [yearValue, setYearValue] = useState("");
  return (
    <div className="App">
      <div>
        <input
          name="name"
          placeholder="name"
          value={nameValue}
          onChange={(e) => setNameValue(e.currentTarget.value)}
        />
        <input
          name="address"
          placeholder="address"
          value={addressValue}
          onChange={(e) => setAddressValue(e.currentTarget.value)}
        />
        <input
          name="year"
          placeholder="year"
          value={yearValue}
          onChange={(e) => setYearValue(e.currentTarget.value)}
        />
      </div>
      <Error
        nameLength={nameValue.length}
        addressLength={addressValue.length}
        yearLength={yearValue.length}
      />
    </div>
  );
}

</code>```

Title: ReactJS problem with <p> element visibility

Body:
I have 3 input fields with Name, Address and Year. I pass the length of all the 3 variables as props to this Error component. The errorText should be hidden by default and turn visible if the name is less than 4 letters.

Problem is when I input a name that is less than 4 letters, it changes the errorText variable to the correct "Error in field: name", which I can see by the alert, but the P element still does not change and stays empty.

Also reason why the errorText is not already the one I need by default is, I have more If statements for every alternative instance. For example, if Address and Name are less than 4, then it needs to say "Error in field: address, name".

What could be the issue here? Thanks in advance.

const Error = (props) => {
    let errorText = '';
    let isVisible = false;

    if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        errorText = "Error in field: name"
        isVisible = true;
        alert("errorText: " + errorText); //This alert is only for testing
    }

    return (

{errorText}

    )
}

Error is rendered by the following button inside a return:

<button type="submit" onClick={() => Error({nameLength, addressLength, yearLength})}>Add</button>

Body:
In React you should think of components as functions (state and props) -> elements
Keeping this in mind, here is a simple implementation of your usecase.

Note that Error is always rendered and it reacts to the props values that are passed to it

import { useState } from "react";
import "./styles.css";

const Error = ({ nameLength, addressLength, yearLength }) => {
  let errorText = "";

  if (nameLength < 4 && addressLength >= 4 && yearLength >= 4) {
    errorText = "error in field name";
  }

  return errorText ? <div>{errorText}</div> : null;
};

export default function App() {
  const [nameValue, setNameValue] = useState("");
  const [addressValue, setAddressValue] = useState("");
  const [yearValue, setYearValue] = useState("");
  return (
    <div className="App">
      <div>
        <input
          name="name"
          placeholder="name"
          value={nameValue}
          onChange={(e) => setNameValue(e.currentTarget.value)}
        />
        <input
          name="address"
          placeholder="address"
          value={addressValue}
          onChange={(e) => setAddressValue(e.currentTarget.value)}
        />
        <input
          name="year"
          placeholder="year"
          value={yearValue}
          onChange={(e) => setYearValue(e.currentTarget.value)}
        />
      </div>
      <Error
        nameLength={nameValue.length}
        addressLength={addressValue.length}
        yearLength={yearValue.length}
      />
    </div>
  );
}


问:
Android internet speed test
I am developing a speed test app like OKLA app (http://www.speedtest.net/).

I've been trying to get bandwidth rate with the most common approach:

Get the time before downloading.

Download some file for some time X.

Get the time after downloading and the total size downloaded.

Calculate speed from TIME and BYTES RECEIVED.

Also, I execute this in two different threads at the same time because is required to saturate de connection to achieve good results.

This approach works very well on PC environment with this JAVA code:

```<code>import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class TestVelocidad {

static long totalBytesReceived = 0; //
static long startSample;
static long endSample ;
private static final long TIME_FOR_DOWNLOAD_MILISECONDS = (long) 10000.0;
private static final long MILI_TO_NANO = 1000000;

public static void main(String[] args) throws InterruptedException, ExecutionException {

    try{
        final ExecutorService service;
        String downloadFileUrl100MB = "http://cachefly.cachefly.net/100mb.test";

        startSample = System.nanoTime();

        service = Executors.newFixedThreadPool(6);
        FutureTask futureTask_1 = new FutureTask(new SpeedTestThread(downloadFileUrl100MB));
        service.execute(futureTask_1);
        FutureTask futureTask_2 = new FutureTask(new SpeedTestThread(downloadFileUrl100MB));
        service.execute(futureTask_2);

        service.shutdownNow();
        long result1 = (Long) futureTask_1.get();
        long result2 = (Long) futureTask_2.get();

        endSample = System.nanoTime();

       long timeSpent = (long) endSample-startSample;
            long totalBytesReceived = result1 + result2;
            System.out.println("Time of threads: " + timeSpent/1000000000.0   + " seconds " + "\nbytes received: " + (totalBytesReceived) );
            double calculatedSpeed;
//            long finalTimeSpent ;
//            finalTimeSpent = (long) ((TIME_FOR_DOWNLOAD_MILISECONDS * MILI_TO_NANO - diff));
            calculatedSpeed =  SpeedInfo.calculate(timeSpent, totalBytesReceived).megabits;
            System.out.println("Velocidad calculada: " + calculatedSpeed   + " mbps" );

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

}

}

class SpeedTestThread implements Callable<Long> {

private String url = new String("");
private static final long TIME_FOR_DOWNLOAD_NANOSECONDS = (long) 10000000000.0;
private static final long MILI_TO_NANO = 1000000;
private long bytesThread;

public SpeedTestThread(String urlToDownload){
    url = urlToDownload;
}

public void run() {

}

@Override
public Long call() throws Exception {

    System.out.println("FileDownload " +  " File to download: " + url );
    InputStream stream = null;
    long startCon = System.nanoTime();
    URL urlToDownload = null;
    try {
        urlToDownload = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    URLConnection con = null;
    try {
        con = urlToDownload.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    con.setUseCaches(false);
    //Tiempo de acceso al archivo.
    long connectionLatency = (System.nanoTime() - startCon)/MILI_TO_NANO;
    System.out.println("Connection latency = " + connectionLatency + "");

    con.setConnectTimeout(5000);

    try {
        stream = con.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    long startNano = System.nanoTime();

    int currentByte = 0;
    try {

        while ((currentByte = stream.read()) != -1 ) {
            bytesThread++;
            if ((System.nanoTime() - startNano) > TIME_FOR_DOWNLOAD_NANOSECONDS){
                System.out.println("Time");
                break;
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Thread bytes received:  " + bytesThread);
    return bytesThread;
}
}

class SpeedInfo {
public double kilobits = 0;
public double megabits = 0;
public double downspeed = 0;
private static final double BYTE_TO_KILOBIT = 0.008;
private static final double KILOBIT_TO_MEGABIT = 0.001;

/**
 * 1 byte = 0.0078125 kilobits
 * 1 kilobits = 0.0009765625 megabit
 *
 * @param downloadTime in miliseconds
 * @param bytesIn      number of bytes downloaded
 * @return SpeedInfo containing current testVelocidadThread
 */
public static SpeedInfo calculate(final long downloadTime, final long bytesIn) {
    SpeedInfo info = new SpeedInfo();
    //from mil to sec
    System.out.println("Bytes transferidos: " + bytesIn + "Tiempo de descarga: " + downloadTime/1000000000);
    double time = downloadTime;
    double byteIn1 = bytesIn;
    double division = (double)(byteIn1 / time);
    double bytespersecond = ((division) * 1000000000);
    double kilobits = bytespersecond * BYTE_TO_KILOBIT;
    double megabits = kilobits * KILOBIT_TO_MEGABIT;
    info.downspeed = bytespersecond;
    info.kilobits = kilobits;
    info.megabits = megabits;
    return info;
}
}
</code>```

The problem is when I run this on a Android application, I had good results on phones with more processing and memory capacity, but poor results on phones with lower capacity.

Any good ideas to achieve good results on most android's phones?.

答:
try to download the file with java nio rather than java io

java io transfer the file first to memory which make the performance poor on low end devices

while java nio using channels you can transfer the file to storage which will make the performance same on all devices approximately

use this code :

len = out.getChannel().transferFrom(readableByteChannel , seekPos , Long.MAX_VALUE);
```

Title: Android internet speed test

Body:
I am developing a speed test app like OKLA app (http://www.speedtest.net/).

I've been trying to get bandwidth rate with the most common approach:

Get the time before downloading.

Download some file for some time X.

Get the time after downloading and the total size downloaded.

Calculate speed from TIME and BYTES RECEIVED.

Also, I execute this in two different threads at the same time because is required to saturate de connection to achieve good results.

This approach works very well on PC environment with this JAVA code:

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class TestVelocidad {

static long totalBytesReceived = 0; //
static long startSample;
static long endSample ;
private static final long TIME_FOR_DOWNLOAD_MILISECONDS = (long) 10000.0;
private static final long MILI_TO_NANO = 1000000;

public static void main(String[] args) throws InterruptedException, ExecutionException {

    try{
        final ExecutorService service;
        String downloadFileUrl100MB = "http://cachefly.cachefly.net/100mb.test";

        startSample = System.nanoTime();

        service = Executors.newFixedThreadPool(6);
        FutureTask futureTask_1 = new FutureTask(new SpeedTestThread(downloadFileUrl100MB));
        service.execute(futureTask_1);
        FutureTask futureTask_2 = new FutureTask(new SpeedTestThread(downloadFileUrl100MB));
        service.execute(futureTask_2);

        service.shutdownNow();
        long result1 = (Long) futureTask_1.get();
        long result2 = (Long) futureTask_2.get();

        endSample = System.nanoTime();

       long timeSpent = (long) endSample-startSample;
            long totalBytesReceived = result1 + result2;
            System.out.println("Time of threads: " + timeSpent/1000000000.0   + " seconds " + "\nbytes received: " + (totalBytesReceived) );
            double calculatedSpeed;
//            long finalTimeSpent ;
//            finalTimeSpent = (long) ((TIME_FOR_DOWNLOAD_MILISECONDS * MILI_TO_NANO - diff));
            calculatedSpeed =  SpeedInfo.calculate(timeSpent, totalBytesReceived).megabits;
            System.out.println("Velocidad calculada: " + calculatedSpeed   + " mbps" );

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

}

}

class SpeedTestThread implements Callable<Long> {

private String url = new String("");
private static final long TIME_FOR_DOWNLOAD_NANOSECONDS = (long) 10000000000.0;
private static final long MILI_TO_NANO = 1000000;
private long bytesThread;

public SpeedTestThread(String urlToDownload){
    url = urlToDownload;
}

public void run() {

}

@Override
public Long call() throws Exception {

    System.out.println("FileDownload " +  " File to download: " + url );
    InputStream stream = null;
    long startCon = System.nanoTime();
    URL urlToDownload = null;
    try {
        urlToDownload = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    URLConnection con = null;
    try {
        con = urlToDownload.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    con.setUseCaches(false);
    //Tiempo de acceso al archivo.
    long connectionLatency = (System.nanoTime() - startCon)/MILI_TO_NANO;
    System.out.println("Connection latency = " + connectionLatency + "");

    con.setConnectTimeout(5000);

    try {
        stream = con.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    long startNano = System.nanoTime();

    int currentByte = 0;
    try {

        while ((currentByte = stream.read()) != -1 ) {
            bytesThread++;
            if ((System.nanoTime() - startNano) > TIME_FOR_DOWNLOAD_NANOSECONDS){
                System.out.println("Time");
                break;
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Thread bytes received:  " + bytesThread);
    return bytesThread;
}
}

class SpeedInfo {
public double kilobits = 0;
public double megabits = 0;
public double downspeed = 0;
private static final double BYTE_TO_KILOBIT = 0.008;
private static final double KILOBIT_TO_MEGABIT = 0.001;

/**
 * 1 byte = 0.0078125 kilobits
 * 1 kilobits = 0.0009765625 megabit
 *
 * @param downloadTime in miliseconds
 * @param bytesIn      number of bytes downloaded
 * @return SpeedInfo containing current testVelocidadThread
 */
public static SpeedInfo calculate(final long downloadTime, final long bytesIn) {
    SpeedInfo info = new SpeedInfo();
    //from mil to sec
    System.out.println("Bytes transferidos: " + bytesIn + "Tiempo de descarga: " + downloadTime/1000000000);
    double time = downloadTime;
    double byteIn1 = bytesIn;
    double division = (double)(byteIn1 / time);
    double bytespersecond = ((division) * 1000000000);
    double kilobits = bytespersecond * BYTE_TO_KILOBIT;
    double megabits = kilobits * KILOBIT_TO_MEGABIT;
    info.downspeed = bytespersecond;
    info.kilobits = kilobits;
    info.megabits = megabits;
    return info;
}
}

The problem is when I run this on a Android application, I had good results on phones with more processing and memory capacity, but poor results on phones with lower capacity.

Any good ideas to achieve good results on most android's phones?.


问:
R combine month names with strings
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))
```

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

答:
Looks like you want to have the cross product over two sets so you can use the function expand_grid from the R package tidyr:

library(tidyverse)

expand_grid(
  month = c("January", "February", "March"),
  value = c("min", "max", "mean")
) %>%
  unite(everything(), col = "combined") %>%
  pull(combined)
#> [1] "January_min"   "January_max"   "January_mean"  "February_min"
#> [5] "February_max"  "February_mean" "March_min"     "March_max"
#> [9] "March_mean"
```

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

paste just zips the elements together so that 2 lists of 3 elements will be combined into one list of 3 elements.

Title: R combine month names with strings

Body:
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

Body:
Looks like you want to have the cross product over two sets so you can use the function expand_grid from the R package tidyr:

library(tidyverse)

expand_grid(
  month = c("January", "February", "March"),
  value = c("min", "max", "mean")
) %>%
  unite(everything(), col = "combined") %>%
  pull(combined)
#> [1] "January_min"   "January_max"   "January_mean"  "February_min"
#> [5] "February_max"  "February_mean" "March_min"     "March_max"
#> [9] "March_mean"

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

paste just zips the elements together so that 2 lists of 3 elements will be combined into one list of 3 elements.


问:
How do I parse variables from ajax to a controller and return a bool
I want to parse 2 strings (Just testing with one atm( consiting of a date from a datepicker and hour and minute from 2 textfields. But I cant figure out how to parse data from my ajax call to the method I call, I know its called as I checked with a breakpoint, but its parameter is just null.

My ajax:

```<code>$('.datein').change(function () {
    alert("datein changed");
    //send servervalidering ajax
    var result = false;
    $.ajax({ url: "Resource/isDateValid/",
            data: ($('#resource_datein').val() + "-" + $('#resource_hourin').val() + "-" + $('#resource_minutein').val()),
        type: "POST",
        sucess: ajaxsuccess(result)
    }
    );
});
</code>```

My methodcall on success

```<code>function ajaxsuccess(result) {
    alert("ajax lykkes!" + result);
}
</code>```

And the controller method which is part of public class ResourceController : DataTablesController

```<code>    [HttpPost]
    public bool isDateValid(string dateIn)
    {

        return true;
    }
</code>```

string dateIn just returns null if I set a date

答:
try something like

```<code>//js

var data = $("myform").serialize(); //Might be serializeArray() not on dev machine sorry

$.post("Resource/isDateValid/", data, function(data){
   alert(data.Success);
}, "json");
</code>```

Controller (assuming Resource is a class because of the underscore in the ids...)

```<code>[HttpPost]
public JsonResult(Resource resource) //or (DateTime resource_datein, int resource_hourin)
{
    bool success = true;

    //Do something with posted data

    return Json(new { Success = success});
}
</code>```

EDIT (re comment)

take the () off the AjaxSuccess function call in the $.post

```<code>$('.datein').change(function () {
            //send servervalidering ajax
            var data = $(".datein").serialize();
            $.post("Resource/isDateValid", data, ajaxsuccess, "text");
        });
</code>```

with

```<code>function ajaxsuccess(data)
{
   alert(data.Success); // in your case alert(data); because it's "text"?
}
</code>```

also because you are not serializing the entire form your data should be:

```<code>var data = {dateIn : $(".datein").val()};
</code>```

Body:
I want to parse 2 strings (Just testing with one atm( consiting of a date from a datepicker and hour and minute from 2 textfields. But I cant figure out how to parse data from my ajax call to the method I call, I know its called as I checked with a breakpoint, but its parameter is just null.

My ajax:

$('.datein').change(function () {
    alert("datein changed");
    //send servervalidering ajax
    var result = false;
    $.ajax({ url: "Resource/isDateValid/",
            data: ($('#resource_datein').val() + "-" + $('#resource_hourin').val() + "-" + $('#resource_minutein').val()),
        type: "POST",
        sucess: ajaxsuccess(result)
    }
    );
});

My methodcall on success

function ajaxsuccess(result) {
    alert("ajax lykkes!" + result);
}

And the controller method which is part of public class ResourceController : DataTablesController

    [HttpPost]
    public bool isDateValid(string dateIn)
    {

        return true;
    }

string dateIn just returns null if I set a date

Body:
try something like

//js

var data = $("myform").serialize(); //Might be serializeArray() not on dev machine sorry

$.post("Resource/isDateValid/", data, function(data){
   alert(data.Success);
}, "json");

Controller (assuming Resource is a class because of the underscore in the ids...)

[HttpPost]
public JsonResult(Resource resource) //or (DateTime resource_datein, int resource_hourin)
{
    bool success = true;

    //Do something with posted data

    return Json(new { Success = success});
}

EDIT (re comment)

take the () off the AjaxSuccess function call in the $.post

$('.datein').change(function () {
            //send servervalidering ajax
            var data = $(".datein").serialize();
            $.post("Resource/isDateValid", data, ajaxsuccess, "text");
        });

with

function ajaxsuccess(data)
{
   alert(data.Success); // in your case alert(data); because it's "text"?
}

also because you are not serializing the entire form your data should be:

var data = {dateIn : $(".datein").val()};