问:
Add conditions on my ajax request (if and else)
How can add conditions on my ajax request?
When I add the code on below is active just for only one. </p>

<pre class="lang-js prettyprint-override"><code>$.ajax({
  type: 'GET',
  url: urlPost,
  success: function (data) {
    $.each(data, function (key, value) {
      createPostItem(value.name, value.image, value.size);
      if (value.size == 'post') {
        $('#img-size').addClass("img-post")
      } else {
        $('#img-size').addClass("img-story")
      }
    });
  }
});
</code>```

答:
It seems that you are manipulating the same element (with id img-size) for each data point received from the server. The result is that the element is affected by all data points, which may not be what you desire. I imagine that you may want to manipulate a different element for each data point, but this is not clear from the question.

UPDATE (after clarification):

I would suggest modifying the function createPostItem:

var urlPost = "assets/js/imgStock.json"
$.ajax({
    type: 'GET',
    url: urlPost,
    success: function (data) {
        $.each(data, function (key, value) {
            createPostItem(value.name, value.image, value.madeFor, value.size);
        });
    }
});

function createPostItem(name, image, madeFor, size) {
    var width, height;

    if (size == 'story') {
        height = '472px';
        width = '270px';
    }
    else {
        height = '270px';
        width = '270px';
    }

    var html = '
' +
        '
' +
        '
' +
        '<img class="rounded shadow-2xl" src="' + image + '" alt="' + name + '"' +
        '
' +
        '
' + name + '
' +
        '' + madeFor + '' +
        '
' +
        '
' +
        '
' +
        '
';

    $(".images-array").append(html);
}
```

Body:
How can add conditions on my ajax request?
When I add the code on below is active just for only one.

$.ajax({
  type: 'GET',
  url: urlPost,
  success: function (data) {
    $.each(data, function (key, value) {
      createPostItem(value.name, value.image, value.size);
      if (value.size == 'post') {
        $('#img-size').addClass("img-post")
      } else {
        $('#img-size').addClass("img-story")
      }
    });
  }
});

Body:
It seems that you are manipulating the same element (with id img-size) for each data point received from the server. The result is that the element is affected by all data points, which may not be what you desire. I imagine that you may want to manipulate a different element for each data point, but this is not clear from the question.

UPDATE (after clarification):

I would suggest modifying the function createPostItem:

var urlPost = "assets/js/imgStock.json"
$.ajax({
    type: 'GET',
    url: urlPost,
    success: function (data) {
        $.each(data, function (key, value) {
            createPostItem(value.name, value.image, value.madeFor, value.size);
        });
    }
});

function createPostItem(name, image, madeFor, size) {
    var width, height;

    if (size == 'story') {
        height = '472px';
        width = '270px';
    }
    else {
        height = '270px';
        width = '270px';
    }

    var html = '<div class="imgStock w-full border-4 my-auto border-blue-500 lg:mx-2 mt-4 mx-auto">' +
        '<div class="flex post text-gray-200 animate__animated animate__fadeIn">' +
        '<div class="img-size mx-auto relative transition duration-300 ease-in transform hover:-translate-y-2" style="width: ' + width + '; height: ' + height + ';">' +
        '<img class="rounded shadow-2xl" src="' + image + '" alt="' + name + '"' +
        '<div class="btn-i absolute ">' +
        '<div class="btn-i absolute text-center pt-2 animate__animated animate__fadeInLeft pl-2">' + name + '</div>' +
        '<span class="flex absolute font-semibold tracking-wide justify-center absolute-pill px-1 text-xxs bg-yellow-400 text-gray-900 rounded-full text-xs">' + madeFor + '</span>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $(".images-array").append(html);
}


来源: stackexchange

问:
Directing Audio to Air Play Speakers from a MacOS Swift Application Using AVPlayer
Im trying to direct audio from a MacOS application I've written in SWIFT directly to air play speakers.

I can direct audio to onboard sound outputs or say a USB DAC no problems. I can get audio device ids for say a connected USB DAC and direct audio specifically to that fine within my application but having trouble finding good samples/docs on doing it to airplay speakers with SWIFT/AVPLAYER.

Anyone seen any good docs / code samples on directing audio from a macOS (not ios) swift application to airplay speakers directly? i.e. how to get a list of airplay audio device ids and send output to them from avplayer?

For directing sound output to say a USB DAC I can get a list of playback audio device ids with this function -

func getOutputDevices()  -> [AudioDevice]  {

```<code>print_log ("")
print_log("+++ START AUDIO PLAYBACK DEVICES FOUND....")
print_log ("")

for device in AudioDevice.allOutputDevices() {
    print("DEVICE NAME: " + device.name + " ->  DEVICE ID: " + String(device.uid ?? "Empty Device"))

}

print_log ("")
print_log("+++ END AUDIO PLAYBACK DEVICES FOUND....")
print_log ("")

return AudioDevice.allOutputDevices()
</code>```

}

and then play audio to one of those returned audio devices like so using avplayer and setting the audio audioOutputDeviceUniqueID  -

```<code>print_log("Setting audio output device to " + String(playback_device.uid ?? "Empty"))

gbl_queue_player.audioOutputDeviceUniqueID=playback_device.uid

gbl_queue_player.addObserver(stage, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
gbl_queue_player.addObserver(stage, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
gbl_queue_player.addObserver(stage, forKeyPath:"currentItem", options:NSKeyValueObservingOptions.new, context:nil)

gbl_queue_player.play()
</code>```

I hope that all makes sense. Ive found some docs pertaining to IOS but not MacOS.

Thanks!

EDIT 01/07/2020

Gave this a try with the code below to instantiate a AVRoutePicker on button press.

GOOD NEWS: the picker appears and the builtin speakers are listed as an option.

BAD NEWS: No confirmed airplay devices, or USB DACs on my system show this way but they do in OS' sound picker.

@IBAction func airplay_button_clicked(_ sender: Any)

{

let frame = CGRect(x: 50, y: 50, width: 100, height: 50)

gbl_routePickerView = AVRoutePickerView(frame: frame)

view.addSubview(gbl_routePickerView) }

}

There's no sandboxing on this application.

*** EDIT SOLUTION 01/06/2020

As pointed out by Jon a player must be assigned to the route pickers player property

so the function for me became ....

@IBAction func airplay_button_clicked(_ sender: Any) {

```<code>    print_log("Airplay button clicked")

    let frame = CGRect(x: 50, y: 50, width: 100, height: 50)

    if #available(OSX 10.15, *) {
        gbl_routePickerView = AVRoutePickerView(frame: frame)
        gbl_routePickerView.player=gbl_queue_player
        view.addSubview(gbl_routePickerView)

    } else {
        // Fallback on earlier versions
        print_log("OS Does not support avroute picker.")
    }
</code>```

}

答: Instantiate an AVRoutePickerView in your view hierarchy then assign your AVPlayer instance to the AVRoutePickerView's player property. You'll then have a GUI for choosing the AirPlay route(s) for your AVPlayer.

ContentLicense: CC BY-SA 4.0

Body:
Im trying to direct audio from a MacOS application I've written in SWIFT directly to air play speakers.

I can direct audio to onboard sound outputs or say a USB DAC no problems. I can get audio device ids for say a connected USB DAC and direct audio specifically to that fine within my application but having trouble finding good samples/docs on doing it to airplay speakers with SWIFT/AVPLAYER.

Anyone seen any good docs / code samples on directing audio from a macOS (not ios) swift application to airplay speakers directly? i.e. how to get a list of airplay audio device ids and send output to them from avplayer?

For directing sound output to say a USB DAC I can get a list of playback audio device ids with this function -

func getOutputDevices()  -> [AudioDevice]  {

print_log ("")
print_log("+++ START AUDIO PLAYBACK DEVICES FOUND....")
print_log ("")

for device in AudioDevice.allOutputDevices() {
    print("DEVICE NAME: " + device.name + " ->  DEVICE ID: " + String(device.uid ?? "Empty Device"))

}

print_log ("")
print_log("+++ END AUDIO PLAYBACK DEVICES FOUND....")
print_log ("")

return AudioDevice.allOutputDevices()

}

and then play audio to one of those returned audio devices like so using avplayer and setting the audio audioOutputDeviceUniqueID  -

print_log("Setting audio output device to " + String(playback_device.uid ?? "Empty"))

gbl_queue_player.audioOutputDeviceUniqueID=playback_device.uid

gbl_queue_player.addObserver(stage, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
gbl_queue_player.addObserver(stage, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
gbl_queue_player.addObserver(stage, forKeyPath:"currentItem", options:NSKeyValueObservingOptions.new, context:nil)

gbl_queue_player.play()

I hope that all makes sense. Ive found some docs pertaining to IOS but not MacOS.

Thanks!

EDIT 01/07/2020

Gave this a try with the code below to instantiate a AVRoutePicker on button press.

GOOD NEWS: the picker appears and the builtin speakers are listed as an option.

BAD NEWS: No confirmed airplay devices, or USB DACs on my system show this way but they do in OS' sound picker.

@IBAction func airplay_button_clicked(_ sender: Any)

{

let frame = CGRect(x: 50, y: 50, width: 100, height: 50)

gbl_routePickerView = AVRoutePickerView(frame: frame)

view.addSubview(gbl_routePickerView) }

}

There's no sandboxing on this application.

*** EDIT SOLUTION 01/06/2020

As pointed out by Jon a player must be assigned to the route pickers player property

so the function for me became ....

@IBAction func airplay_button_clicked(_ sender: Any) {

    print_log("Airplay button clicked")

    let frame = CGRect(x: 50, y: 50, width: 100, height: 50)

    if #available(OSX 10.15, *) {
        gbl_routePickerView = AVRoutePickerView(frame: frame)
        gbl_routePickerView.player=gbl_queue_player
        view.addSubview(gbl_routePickerView)

    } else {
        // Fallback on earlier versions
        print_log("OS Does not support avroute picker.")
    }

}


问:
Check the type of all elements in a list of list in and that their numerical value falls within a range
I want to loop over each element and check if its type is int and if it lays within range of 12 <= i <= 20
if so return True

I use any to return if all elements are correct and isinstance to catch the type of each element.

The function gives me no output and no bug report so I don't know where the error is.

```<code>listoflist = [[14,13,13,14]]

def list_check(my_list):
    if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
        print("true")
        return True
</code>```

答:
Problem is that you use nested list. Also you do not get any output whatsoever because you are not calling the function.Following code prints True on console</p>

```<code>my_list = [14,13,13,14]

def list_check(my_list):

    if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
        print("true")
        return True
list_check(my_list)
</code>```

Body:
I want to loop over each element and check if its type is int and if it lays within range of 12 <= i <= 20
if so return True

I use any to return if all elements are correct and isinstance to catch the type of each element.

The function gives me no output and no bug report so I don't know where the error is.

listoflist = [[14,13,13,14]]

def list_check(my_list):
    if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
        print("true")
        return True

Body:
Problem is that you use nested list. Also you do not get any output whatsoever because you are not calling the function.Following code prints True on console

my_list = [14,13,13,14]

def list_check(my_list):

    if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
        print("true")
        return True
list_check(my_list)


问:
Show blog post excerpt with Laravel
I'm trying to show the excerpts from blog posts. I am able to do this with php and mysql. However, I am wondering if there is a more 'friendly' way of doing this within the Laravel framework.

Thanks!

答:
Some answers above mentioned Str class which is removed from laravel core and moved to new helpers package. As mentioned in Laravel v6.x upgrade guide.
https://laravel.com/docs/6.x/upgrade#helpers

"All str_ and array_ helpers have been moved to the new laravel/helpers Composer package and removed from the framework. If desired, you may update all calls to these helpers to use the Illuminate\Support\Str and Illuminate\Support\Arr classes. Alternatively, you can add the new laravel/helpers package to your application to continue using these helpers:"

```<code>composer require laravel/helpers
</code>```

Simply install it via Composer and it should work fine.

ContentLicense: CC BY-SA 3.0

Title: Show blog post excerpt with Laravel

Body:
Some answers above mentioned Str class which is removed from laravel core and moved to new helpers package. As mentioned in Laravel v6.x upgrade guide.
https://laravel.com/docs/6.x/upgrade#helpers

"All str_ and array_ helpers have been moved to the new laravel/helpers Composer package and removed from the framework. If desired, you may update all calls to these helpers to use the Illuminate\Support\Str and Illuminate\Support\Arr classes. Alternatively, you can add the new laravel/helpers package to your application to continue using these helpers:"

composer require laravel/helpers

Simply install it via Composer and it should work fine.


答:
This is because you're looping through a one element list, so basically the for i in my_list only has one resulting item: [14,13,13,14]

You will need to select list[0] to iterate through the inner elements. There are also more elegant solutions than using for loops to apply such simple operations on lists, for instance map() and lambda:

```<code>listoflist = [[14,13,13,14]]

def list_check(mylist):
    f = lambda x: isinstance(x, int) and 12 <= x <= 20
    return all(map(f, mylist[0]))
</code>```

```<code>list_check(listoflist)
</code>```

```<code>Out[55]: True
</code>```

lambda creates a "callable" function, and map applies this function to all elements of an iterable (e.g., list).

Title: Check the type of all elements in a list of list in and that their numerical value falls within a range

Body:
This is because you're looping through a one element list, so basically the for i in my_list only has one resulting item: [14,13,13,14]

You will need to select list[0] to iterate through the inner elements. There are also more elegant solutions than using for loops to apply such simple operations on lists, for instance map() and lambda:

listoflist = [[14,13,13,14]]

def list_check(mylist):
    f = lambda x: isinstance(x, int) and 12 <= x <= 20
    return all(map(f, mylist[0]))

list_check(listoflist)

Out[55]: True

lambda creates a "callable" function, and map applies this function to all elements of an iterable (e.g., list).


问:
Issue with Matplotlib rendering dates, image
I'm having an issue with Matplotlib v 3.1.3 from conda-forge with python 3.7.  I have all of the dependencies required for Matplotlib.  When I enter this code,  which should work. I get splatter art.  It's based on this youtube tutorial: https://www.youtube.com/watch?v=LWjaAiKaf8&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB&index=8

```<code>import matplotlib.pyplot as plt
import pandas as pd

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value )
plt.gcf().autofmt_xdate()
plt.show
</code>```

The rendering of the matplotlib chart based on this code looks like this:

I tried another approach using the matplotlib DateFormatter and Locator.  I got something resembling a line chart underneath a child's scribbling.  But it had dates:

```<code>df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

    # Visualize data
x_values = df_train['date']
y_values = df_train['col4']
ax = plt.gca()
plt.figure(figsize=(16, 8))
formatter = mpl_dates.DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(formatter)
locator = mpl_dates.DayLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)
plt.show()
</code>```

Finally, if I change the code to exclude the dates: I get a perfectly rendered chart with no dates:

```<code>import matplotlib.pyplot as plt
import pandas as pd

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot(df_train['col4']
plt.gcf().autofmt_xdate()
plt.show()
</code>```

I've tried closing the plots at the end to no avail.  I checked the Matplotlib docs and followed it to a 'T' including using the wheel build and creating the conda channel and installing the dependencies and setting the path and includes per the documentation.  I'm at my wits end.  Can someone more educated on the subject give me a hand?  Thanks in advance.

答:
It seems that the default setting in plot_date() is set to scatterplots (see (https://www.geeksforgeeks.org/matplotlib-pyplot-plot_date-in-python/) in the newer versions of matplotlib.

To achieve a continuous graph based on dates, you can define the interlining in the arguments plt.plot_date(x_value, y_value, '-').

This code works for me:

```<code>import matplotlib.pyplot as plt
import pandas as pd

df_train = pd.read_csv('test.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value, '-')
plt.gcf().autofmt_xdate()
plt.show()
</code>```

Output:

This functionality of not using the lineplot by default is indeed questionable given that the plot also automatically changes from scatterplot to lineplot when you just change the color: plt.plot_date(x_value, y_value, 'g').

This might just be a bug in the current versions of mpl.

Body:
I'm having an issue with Matplotlib v 3.1.3 from conda-forge with python 3.7.  I have all of the dependencies required for Matplotlib.  When I enter this code,  which should work. I get splatter art.  It's based on this youtube tutorial: https://www.youtube.com/watch?v=LWjaAiKaf8&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB&index=8

import matplotlib.pyplot as plt
import pandas as pd

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value )
plt.gcf().autofmt_xdate()
plt.show

The rendering of the matplotlib chart based on this code looks like this:

I tried another approach using the matplotlib DateFormatter and Locator.  I got something resembling a line chart underneath a child's scribbling.  But it had dates:

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

    # Visualize data
x_values = df_train['date']
y_values = df_train['col4']
ax = plt.gca()
plt.figure(figsize=(16, 8))
formatter = mpl_dates.DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(formatter)
locator = mpl_dates.DayLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)
plt.show()

Finally, if I change the code to exclude the dates: I get a perfectly rendered chart with no dates:

import matplotlib.pyplot as plt
import pandas as pd

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot(df_train['col4']
plt.gcf().autofmt_xdate()
plt.show()

I've tried closing the plots at the end to no avail.  I checked the Matplotlib docs and followed it to a 'T' including using the wheel build and creating the conda channel and installing the dependencies and setting the path and includes per the documentation.  I'm at my wits end.  Can someone more educated on the subject give me a hand?  Thanks in advance.

Body:
It seems that the default setting in plot_date() is set to scatterplots (see (https://www.geeksforgeeks.org/matplotlib-pyplot-plot_date-in-python/) in the newer versions of matplotlib.

To achieve a continuous graph based on dates, you can define the interlining in the arguments plt.plot_date(x_value, y_value, '-').

This code works for me:

import matplotlib.pyplot as plt
import pandas as pd

df_train = pd.read_csv('test.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value, '-')
plt.gcf().autofmt_xdate()
plt.show()

Output:

This functionality of not using the lineplot by default is indeed questionable given that the plot also automatically changes from scatterplot to lineplot when you just change the color: plt.plot_date(x_value, y_value, 'g').

This might just be a bug in the current versions of mpl.


问:
How to change condition from a while loop
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :

```<code>book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
</code>```

When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.

What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?

Appreciate any help.

Thanks and Regards

Sachin

答:
So the problem is with the option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :"). You are asking only one time for the option, what you need is an endless loop to continue asking for the new option. On your approach when the "user" chooses the "a" option he/she never gets asked again so the options still remains on "a" thus the add_books() function running endless!

You should change the last part to:

while True:
    option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    elif option == "q":
        quit()
    else:
        print("Invalid Option")

```

Body:
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :

book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.

What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?

Appreciate any help.

Thanks and Regards

Sachin


问:
Django - ModuleNotFoundError: No module named 'background-task'
Python 3.7.0, django 3.0.3, django-background-tasks 1.2.5 (Using Anaconda environment)

Trying to use django-background-tasks as explained here https://django-background-tasks.readthedocs.io/en/latest/, but as soon as I add 'background_task' to INSTALLED_APPS, when I run python manage.py migrate I get "ModuleNotFoundError: No module named 'background-task'"

答: My bad. The package is called "background_task" and not "background-task" </p>


问:
how to dynamically create multiple beans of same type then gather/autowire them
let's say that in my spring(boot) yaml config file I have a list of commands:

```<code>commands: [add,delete,copy,move]
</code>```

and the corresponding class in my spring(boot) project:

public class Command {

    private String name;

    public Command(String name) {
        this.name = name;
    }

    public void execute() {
        System.out.println(name);
    }

    public String getName() {
        return name;
    }

}
```

<p>How can I dynamically/adaptively generate the right number of command beans, then gather/autowire them in a separate class as below ? </p>

<pre class="lang-java prettyprint-override"><code>public class Menu {

   @Autowired
   List<Command> commands;

   public void display() {
       commands.forEach(cmd -> System.out.println(cmd.getName());
   }

}
</code>```

Thank you very much in advance for your time and your expertise.

Regards

答:
For dynamic bean registration, you can use ImportBeanDefinitionRegistrar.

The code will be like this:

import java.util.List;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

@Configuration
@Import(CommandsConfiguration.Registrar.class)
public class CommandsConfiguration {

    static class Registrar implements ImportBeanDefinitionRegistrar {

        @Override
        public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
            final List<String> commands = // read commands from environemnt/config
            for (String command : commands) {
                final String beanName = command + "Command";
                final BeanDefinition beanDefinition = BeanDefinitionBuilder
                    .genericBeanDefinition(Command.class, () -> new Command(command))
                    .getBeanDefinition();
                registry.registerBeanDefinition(beanName, beanDefinition);
            }
        }
    }
}
```

Body:
let's say that in my spring(boot) yaml config file I have a list of commands:

commands: [add,delete,copy,move]

and the corresponding class in my spring(boot) project:

public class Command {

    private String name;

    public Command(String name) {
        this.name = name;
    }

    public void execute() {
        System.out.println(name);
    }

    public String getName() {
        return name;
    }

}

How can I dynamically/adaptively generate the right number of command beans, then gather/autowire them in a separate class as below ?

public class Menu {

   @Autowired
   List<Command> commands;

   public void display() {
       commands.forEach(cmd -> System.out.println(cmd.getName());
   }

}

Thank you very much in advance for your time and your expertise.

Regards


问:
Delete 5 years old records from a table and its dependencies i.e. parent and child tables both in Oracle using query or procedure
How to 5 years old records from a table and its dependencies i.e. parent and child tables both in Oracle using query or procedure.

I tried using the dateadd command of oracle but it only delete records from main table and not from its child table.
Assume table A is main table and B&C are child tables. How can we delete records from A as well as B&C that are 5 yrs old.

答:
You need 3 separate DELETE and just need to use the query on A using ADD_MONTHS, take its PK and delete from B then C then A using that PKS as follows:

```<code>DELETE FROM B
WHERE A_FK IN (SELECT A_PK FROM A WHERE DATECOLUMN <= ADD_MONTHS(TRUNC(SYSDATE), -60));

DELETE FROM C
WHERE A_FK IN (SELECT A_PK FROM A WHERE DATECOLUMN <= ADD_MONTHS(TRUNC(SYSDATE), -60));

DELETE FROM A WHERE DATECOLUMN <= ADD_MONTHS(TRUNC(SYSDATE), -60);
</code>```

Body:
You need 3 separate DELETE and just need to use the query on A using ADD_MONTHS, take its PK and delete from B then C then A using that PKS as follows:

DELETE FROM B
WHERE A_FK IN (SELECT A_PK FROM A WHERE DATECOLUMN <= ADD_MONTHS(TRUNC(SYSDATE), -60));

DELETE FROM C
WHERE A_FK IN (SELECT A_PK FROM A WHERE DATECOLUMN <= ADD_MONTHS(TRUNC(SYSDATE), -60));

DELETE FROM A WHERE DATECOLUMN <= ADD_MONTHS(TRUNC(SYSDATE), -60);


问:
Writing a Build Script for a Play! Framework application
How are people writing builds for their Play applications?
I understand that you can run play auto-test on the command-line, however, I would like to do a bit more than just execute the tests.

So for example, if I wanted to add checkstyle and clover to my build, I could easily write an Ant script that would check those two things and fail if there are any checkstyle errors or the clover coverage is not 90%.

I was just wondering whether there already was a "Play" way of doing what I have just described.

答:
not, not as far as I know, although there are addons to use ant/maven in Play, you could try to integrate them. But users may skip then and use the normal play.

An idea would be to modify the Play python script to run these validations before any action, but that would require all developers to use that modified script.


问:
Convert string representation of list of dictionaries to list of dictionaries
This is string representation

```<code>Data = "[{'Date': '16-Sep-2019', 'Open': 10994.85, 'High': 11052.7, 'Low': 10968.2, 'Close': 11003.5, 'Shares Traded': 434449776, 'Turnover (Rs. Cr)': 15786.17}, {'Date': '17-Sep-2019', 'Open': 11000.1, 'High': 11000.1, 'Low': 10796.5, 'Close': 10817.6, 'Shares Traded': 482013044, 'Turnover (Rs. Cr)': 17721.93}]"
</code>```

i want it to be list representation

```<code>Data = [{'Date': '16-Sep-2019', 'Open': 10994.85, 'High': 11052.7, 'Low': 10968.2, 'Close': 11003.5, 'Shares Traded': 434449776, 'Turnover (Rs. Cr)': 15786.17}, {'Date': '17-Sep-2019', 'Open': 11000.1, 'High': 11000.1, 'Low': 10796.5, 'Close': 10817.6, 'Shares Traded': 482013044, 'Turnover (Rs. Cr)': 17721.93}]
</code>```

i tried every thing including json.loads(data),
Even after json.loads() it shows type as string.Please check in online compiler also.
Thankyou

答:
You could try this:</p>

```<code>L = Data.strip('][').split(', ')

print(L)
print(type(L))
</code>```

<h2> </h2>

```<code>res = '['+Data.strip('][')+']'

print(res)
print(type(res))
</code>```

Body:
This is string representation

Data = "[{'Date': '16-Sep-2019', 'Open': 10994.85, 'High': 11052.7, 'Low': 10968.2, 'Close': 11003.5, 'Shares Traded': 434449776, 'Turnover (Rs. Cr)': 15786.17}, {'Date': '17-Sep-2019', 'Open': 11000.1, 'High': 11000.1, 'Low': 10796.5, 'Close': 10817.6, 'Shares Traded': 482013044, 'Turnover (Rs. Cr)': 17721.93}]"

i want it to be list representation

Data = [{'Date': '16-Sep-2019', 'Open': 10994.85, 'High': 11052.7, 'Low': 10968.2, 'Close': 11003.5, 'Shares Traded': 434449776, 'Turnover (Rs. Cr)': 15786.17}, {'Date': '17-Sep-2019', 'Open': 11000.1, 'High': 11000.1, 'Low': 10796.5, 'Close': 10817.6, 'Shares Traded': 482013044, 'Turnover (Rs. Cr)': 17721.93}]

i tried every thing including json.loads(data),
Even after json.loads() it shows type as string.Please check in online compiler also.
Thankyou

Body:
You could try this:

L = Data.strip('][').split(', ')

print(L)
print(type(L))

res = '['+Data.strip('][')+']'

print(res)
print(type(res))


问:
Need to fix a problem with instantiated gameObjects
I have this problem and i don't know how to solve it,it's very confusing.I want that every time i instantiate the gameobject it gets a random color, but these clones get the same color from previous one.Like the first prefab spawn and gets random colors, now the next one spawn and olso gets random colors but the first one gets it's color,it's very confusing i know!
enter image description here

Here is the code of the gate :
public Material[] material;
    public Color[] colors;

```<code>public void ColorChange()
{
    colors = new[] {
    Color.blue,
    Color.black,
    Color.red,
    Color.green,
    Color.yellow,
    Color.white,
    Color.magenta,
    Color.cyan,
    Color.grey };

    var rnd = new System.Random();
    var randomColors = colors.OrderBy(x => rnd.Next()).ToArray();

    for (var i = 0; i < material.Length; i++)
    {
        material[i].color = randomColors[i];

    }

}
private void Start()
{

    ColorChange();
}
</code>```

And the script of the spawner:
public GameObject Gate; // the gameobject

```<code>private float timeBtwSpawn;
public float startTimeBtwSpawn;
public float decreaseTime;
public float minTime = 0.65f;

void Start()
{

}
void Update()
{
    if (timeBtwSpawn <= 0)
    {
        Instantiate(Gate, transform.position, Quaternion.identity);

        timeBtwSpawn = startTimeBtwSpawn;
        if (startTimeBtwSpawn > minTime)
        {
            startTimeBtwSpawn -= decreaseTime;
        }

    }
    else
    {
        timeBtwSpawn -= Time.deltaTime;
    }
}
</code>```

答:
Materials are shared between GameObjects, so if you change the color of a material - all objects using that material will get the new color.

Here's a few approaches (see the last one for my suggestion):

MaterialPropertyBlock

(Will not work in your case)

You could check out MaterialPropertyBlock:

Use it in situations where you want to draw multiple objects with the same material, but slightly different properties. For example, if you want to slightly change the color of each mesh drawn.

Will not work because you're re-using the materials.

Pre-created set of materials

Work around it by either creating a number of materials and chosing a random one.

(Which is what you have done, but will not work since you're reusing the materials)

New materials in runtime

Or you could create new materials in runtime.

(Should work, but next one is easier)

GameObject's Renderer.material

But I believe the easiest way should be to do:

```<code>mySpawnedGameObject.GetComponent<Renderer>().material.color = randomColor;
</code>```

as opposed to using material.sharedMaterial. This should only apply to the one GameObject you choose: Renderer.material

Body:
I have this problem and i don't know how to solve it,it's very confusing.I want that every time i instantiate the gameobject it gets a random color, but these clones get the same color from previous one.Like the first prefab spawn and gets random colors, now the next one spawn and olso gets random colors but the first one gets it's color,it's very confusing i know!
enter image description here

Here is the code of the gate :
public Material[] material;
    public Color[] colors;

public void ColorChange()
{
    colors = new[] {
    Color.blue,
    Color.black,
    Color.red,
    Color.green,
    Color.yellow,
    Color.white,
    Color.magenta,
    Color.cyan,
    Color.grey };

    var rnd = new System.Random();
    var randomColors = colors.OrderBy(x => rnd.Next()).ToArray();

    for (var i = 0; i < material.Length; i++)
    {
        material[i].color = randomColors[i];

    }

}
private void Start()
{

    ColorChange();
}

And the script of the spawner:
public GameObject Gate; // the gameobject

private float timeBtwSpawn;
public float startTimeBtwSpawn;
public float decreaseTime;
public float minTime = 0.65f;

void Start()
{

}
void Update()
{
    if (timeBtwSpawn <= 0)
    {
        Instantiate(Gate, transform.position, Quaternion.identity);

        timeBtwSpawn = startTimeBtwSpawn;
        if (startTimeBtwSpawn > minTime)
        {
            startTimeBtwSpawn -= decreaseTime;
        }

    }
    else
    {
        timeBtwSpawn -= Time.deltaTime;
    }
}

Body:
Materials are shared between GameObjects, so if you change the color of a material - all objects using that material will get the new color.

Here's a few approaches (see the last one for my suggestion):

MaterialPropertyBlock

(Will not work in your case)

You could check out MaterialPropertyBlock:

Use it in situations where you want to draw multiple objects with the same material, but slightly different properties. For example, if you want to slightly change the color of each mesh drawn.

Will not work because you're re-using the materials.

Pre-created set of materials

Work around it by either creating a number of materials and chosing a random one.

(Which is what you have done, but will not work since you're reusing the materials)

New materials in runtime

Or you could create new materials in runtime.

(Should work, but next one is easier)

GameObject's Renderer.material

But I believe the easiest way should be to do:

mySpawnedGameObject.GetComponent<Renderer>().material.color = randomColor;

as opposed to using material.sharedMaterial. This should only apply to the one GameObject you choose: Renderer.material


问:
core.js:6237 ERROR TypeError: Cannot set property 'area' of undefined
HTML: Here is my form. When I click the submit button I have got this error. I don't know Where I am getting wrong. Can you please help?

```<code><h3 class="page-header">Operator Form</h3>
<div class="outer-container">
   <form class="form-section" [formGroup]="operatorForm" (ngSubmit)="save()">
        <!-- <mat-form-field>
            <input matInput type="text" placeholder="Drone Type" formControlName="drone_type" required>
        </mat-form-field> -->
        <mat-form-field>
            <input matInput type="text" placeholder="Police Station" formControlName="police" readonly>
        </mat-form-field>
        <mat-form-field>
            <input matInput type="text" placeholder="Area" formControlName="area" required>
        </mat-form-field>
        <!-- <mat-form-field>
            <mat-label>Date and Time</mat-label>
             <input matInput [matDatepicker]="picker" formControlName="date" readonly/>
             <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
             <mat-datepicker #picker disabled="false"></mat-datepicker>
         </mat-form-field> -->
         <mat-form-field>
            <input matInput [ngxMatDatetimePicker]="picker" placeholder="Date and Time"
                formControlName="date"
                [disabled]="disabled">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <ngx-mat-datetime-picker #picker [showSpinners]="showSpinners" [showSeconds]="showSeconds"
               [stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond"
               [touchUi]="touchUi" [color]="color" [enableMeridian]="enableMeridian">
            </ngx-mat-datetime-picker>
         </mat-form-field>

        <div style="text-align: right">
            <button mat-raised-button type="submit" [disabled]="operatorForm.invalid" >Submit</button>
        </div>
    </form>
</div>
<div class="spinner" [style.display]="showSpinner ? 'flex' : 'none'">
    <mat-spinner [diameter]="30" ></mat-spinner>
</div>

</code>```

component.ts:(Here is my form.. when i click submit button I have got this error. dont know Where i am getting wrong.. can you please help? )

```<code>payload: any;
ngOnInit(){
   this.operatorForm = new FormGroup({
     'police': new FormControl(null, Validators.required),
     'area': new FormControl(null, Validators.required),
     'date': new FormControl(null, Validators.required),
    })
}
save() {
   this.payload.area = this.operatorForm.get('area').value
   this.payload.flightDateTimeStr = this.operatorForm.get('date').value,
   console.log(this.payload)
}
</code>```

答:
You can  not dynamically inject keys like that in save method to the payload.
Follow this code.

```<code>payload: any;

save(){
   this.payload = {
      area: this.operatorForm.get('area').value,
      flightDateTimeStr: this.operatorForm.get('date').value,
   }
}
</code>```

If you want to cast the object then exports interface and typecast the properties of the object like this.

```<code>export interface PayLoad {
   area: any;
   flightDateTimeStr: any;
}

payload: PayLoad;
</code>```

Body:
HTML: Here is my form. When I click the submit button I have got this error. I don't know Where I am getting wrong. Can you please help?

Operator Form

   <form class="form-section" [formGroup]="operatorForm" (ngSubmit)="save()">

        <mat-form-field>
            <input matInput type="text" placeholder="Police Station" formControlName="police" readonly>
        </mat-form-field>
        <mat-form-field>
            <input matInput type="text" placeholder="Area" formControlName="area" required>
        </mat-form-field>

         <mat-form-field>
            <input matInput [ngxMatDatetimePicker]="picker" placeholder="Date and Time"
                formControlName="date"
                [disabled]="disabled">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <ngx-mat-datetime-picker #picker [showSpinners]="showSpinners" [showSeconds]="showSeconds"
               [stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond"
               [touchUi]="touchUi" [color]="color" [enableMeridian]="enableMeridian">
            </ngx-mat-datetime-picker>
         </mat-form-field>

            <button mat-raised-button type="submit" [disabled]="operatorForm.invalid" >Submit</button>

    </form>

    <mat-spinner [diameter]="30" ></mat-spinner>

component.ts:(Here is my form.. when i click submit button I have got this error. dont know Where i am getting wrong.. can you please help? )

payload: any;
ngOnInit(){
   this.operatorForm = new FormGroup({
     'police': new FormControl(null, Validators.required),
     'area': new FormControl(null, Validators.required),
     'date': new FormControl(null, Validators.required),
    })
}
save() {
   this.payload.area = this.operatorForm.get('area').value
   this.payload.flightDateTimeStr = this.operatorForm.get('date').value,
   console.log(this.payload)
}

Body:
You can  not dynamically inject keys like that in save method to the payload.
Follow this code.

payload: any;

save(){
   this.payload = {
      area: this.operatorForm.get('area').value,
      flightDateTimeStr: this.operatorForm.get('date').value,
   }
}

If you want to cast the object then exports interface and typecast the properties of the object like this.

export interface PayLoad {
   area: any;
   flightDateTimeStr: any;
}

payload: PayLoad;


问:
Removing .h extension in user defined c++ header file
Can we remove .h extensions while we define our own header file in c++? like in case of standard header files in c++.

I have created a header file and named it add.h and tried including it using #include "add" but it didn't work.

after following up the comments and answers:
using codeblocks ide
i have created a "add" of type File and tried it including in my source file and it worked. attaching the snapshot below.
the aim of my question is to ask if userdefined header files can also omit .h extensions and how?
i am really trying to explore this fact and don't have a good understanding of how compilers stores standard header files.
A easy to understood conclusion is really appreciated
Thankyou.

答:
Can we remove .h extensions while we define our own header file in c++? like in case of standard header files in c++.

You've misunderstood how the files in the stardard library are named. The header file iostream is actually named iostream and not iostream.hpp or iostream.h (unless you use a very old compiler).

I have created a header file and named it add.h and tried including it using #include "add" but it didn't work.

The reason that doesn't work is because the pre-compiler tries to read the file add and you've named the file add.h.


问:
Jboss only works on localhost:8080 ,but doesnt reply when called by ip
I installed JBoss 5.0.1
and ran it , but when i called it from the same computer on localhost:8080 it works
but when i call it from other computer it doesnt work at all using the computer IP ... when i had tomcat it used to work on both.so Does anybody know the problem?</p>

答:
You have to edit the run.bat or run.sh  accordingly  including binding  -b 0.0.0.0 .

or you can run the jboss by command line by following command.

run -b 0.0.0.0


问:
Add a column to spark dataframe which contains list of all column names of the current row whose value is not null
Hi I want to add a new column to a dafaframe which contains the list of all column names(for that row) which are not null. How do I achieve this in Scala. Please help.

```<code>val baseDF = Seq(
(3, "California", "name1", 9846, null, "SFO"),
(1, "Oregon", "name2", 9847, null, null),
(2, null, null, null, null, null)
).toDF("emp_id", "emp_city", "emp_name", "emp_phone", "emp_sal", "emp_site")
</code>```

Expected output is new column named "NonNullColumns" with expected non null column names for each row:

```<code>NonNullColumns
==============
["emp_id", "emp_city", "emp_name", "emp_phone", "emp_site"]
["emp_id", "emp_city", "emp_name", "emp_phone"]
["emp_id"]
</code>```

答:
Slight alternative using withColumn and reduce and using your DF I made them all String so as to avoid Any type issues, df used as name, and only relevant parts of code shown:</p>

```<code>val nonNulls = df.columns.map(x => when(col(x).isNotNull, concat(lit(","), lit(x))).otherwise(",")).reduce(concat(_, _))
val df2 = df.withColumn("nonNulls", nonNulls)
val df3 = df2.withColumn("nonNullsCols", array_remove(split(col("nonNulls"),","), lit(""))).drop("nonNulls")
</code>```

Body:
Hi I want to add a new column to a dafaframe which contains the list of all column names(for that row) which are not null. How do I achieve this in Scala. Please help.

val baseDF = Seq(
(3, "California", "name1", 9846, null, "SFO"),
(1, "Oregon", "name2", 9847, null, null),
(2, null, null, null, null, null)
).toDF("emp_id", "emp_city", "emp_name", "emp_phone", "emp_sal", "emp_site")

Expected output is new column named "NonNullColumns" with expected non null column names for each row:

NonNullColumns
==============
["emp_id", "emp_city", "emp_name", "emp_phone", "emp_site"]
["emp_id", "emp_city", "emp_name", "emp_phone"]
["emp_id"]

Body:
Slight alternative using withColumn and reduce and using your DF I made them all String so as to avoid Any type issues, df used as name, and only relevant parts of code shown:

val nonNulls = df.columns.map(x => when(col(x).isNotNull, concat(lit(","), lit(x))).otherwise(",")).reduce(concat(_, _))
val df2 = df.withColumn("nonNulls", nonNulls)
val df3 = df2.withColumn("nonNullsCols", array_remove(split(col("nonNulls"),","), lit(""))).drop("nonNulls")


问:
Updating column value based on condition with substring
I need to change all values of a column that contain autor substring to author.

Example: My current row is role-autor and this needs to become role-author

Is it possible in liquibase?

答:
Something like this:

```<code><update tableName="your_table_name">
    <column name="role-autor" type="varchar(64)" valueComputed="REPLACE(role-autor, 'autor', 'author')" />
    <where>role-autor LIKE '%autor%'</where>
</update>
</code>```

Please do the research of the StackOverflow blog there are some examples that can help you...

You will need to put it in the changeset tag :

```<code><changeSet author="wiki" id="1.0.0-1">
    <update tableName="your_table_name">
        <column name="role-autor" type="varchar(64)" valueComputed="REPLACE(role-autor, 'autor', 'author')" />
        <where>role-autor LIKE '%autor%'</where>
    </update>
</changeset>
</code>```

Something to read for more details about the changeset tag: https://docs.liquibase.com/concepts/basic/changeset.html

Body:
Something like this:

<update tableName="your_table_name">
    <column name="role-autor" type="varchar(64)" valueComputed="REPLACE(role-autor, 'autor', 'author')" />
    <where>role-autor LIKE '%autor%'</where>
</update>

Please do the research of the StackOverflow blog there are some examples that can help you...

You will need to put it in the changeset tag :

<changeSet author="wiki" id="1.0.0-1">
    <update tableName="your_table_name">
        <column name="role-autor" type="varchar(64)" valueComputed="REPLACE(role-autor, 'autor', 'author')" />
        <where>role-autor LIKE '%autor%'</where>
    </update>
</changeset>

Something to read for more details about the changeset tag: https://docs.liquibase.com/concepts/basic/changeset.html


问:
grouping continuous data with specific pattern
I have a data frame with a column like this (I am not posting other columns)

```<code>Value
1
1
1
0
0
1
0
0
1
1
2
2
0
0
1
0
0
1
1
1
0
0
2
2
1
1
2
0
0
1
0
</code>```

I am trying to group it based on a specific condition. Grouping has to be done when I have 1 and 2. But conditions like these are one group :

```<code>1 1 0 0 1 1 0 0
</code>```

Basically I need to group occurrences of 1 but in between 0s are allowed

Expected output:

```<code>Value   Group
    1   1
    1   1
    1   1
    0   1
    0   1
    1   1
    0   1
    0   1
    1   1
    1   1
    2   2
    2   2
    0   2
    0   2
    1   3
    0   3
    0   3
    1   3
    1   3
    1   3
    0   3
    0   3
    2   4
    2   4
    1   5
    1   5
    2   6
    0   6
    0   6
    1   7
    0   7
    2   8
    0   8
    2   8
    1   9
</code>```

答:
Another solution that avoids loops, that works similar to Limey's solution but uses cumsum to create the groups.

```<code>df$Group <- dplyr::na_if(df$Value, 0)
df <- tidyr::fill(df, Group, .direction = "down")
df$Group <- cumsum(df$Group != dplyr::lag(df$Group, default = -1))

> df

   Value Group
1      1     1
2      1     1
3      1     1
4      0     1
5      0     1
6      1     1
7      0     1
8      0     1
9      1     1
10     1     1
11     2     2
12     2     2
13     0     2
14     0     2
15     1     3
16     0     3
17     0     3
18     1     3
19     1     3
20     1     3
21     0     3
22     0     3
23     2     4
24     2     4
25     1     5
26     1     5
27     2     6
28     0     6
29     0     6
30     1     7
31     0     7
</code>```

Body:
I have a data frame with a column like this (I am not posting other columns)

Value
1
1
1
0
0
1
0
0
1
1
2
2
0
0
1
0
0
1
1
1
0
0
2
2
1
1
2
0
0
1
0

I am trying to group it based on a specific condition. Grouping has to be done when I have 1 and 2. But conditions like these are one group :

1 1 0 0 1 1 0 0

Basically I need to group occurrences of 1 but in between 0s are allowed

Expected output:

Value   Group
    1   1
    1   1
    1   1
    0   1
    0   1
    1   1
    0   1
    0   1
    1   1
    1   1
    2   2
    2   2
    0   2
    0   2
    1   3
    0   3
    0   3
    1   3
    1   3
    1   3
    0   3
    0   3
    2   4
    2   4
    1   5
    1   5
    2   6
    0   6
    0   6
    1   7
    0   7
    2   8
    0   8
    2   8
    1   9

Body:
Another solution that avoids loops, that works similar to Limey's solution but uses cumsum to create the groups.

df$Group <- dplyr::na_if(df$Value, 0)
df <- tidyr::fill(df, Group, .direction = "down")
df$Group <- cumsum(df$Group != dplyr::lag(df$Group, default = -1))

> df

   Value Group
1      1     1
2      1     1
3      1     1
4      0     1
5      0     1
6      1     1
7      0     1
8      0     1
9      1     1
10     1     1
11     2     2
12     2     2
13     0     2
14     0     2
15     1     3
16     0     3
17     0     3
18     1     3
19     1     3
20     1     3
21     0     3
22     0     3
23     2     4
24     2     4
25     1     5
26     1     5
27     2     6
28     0     6
29     0     6
30     1     7
31     0     7


问:
How can I re order only part of a collection in swift?
I have an array of Item. The order is never guaranteed as the collection is served from an API based on a number of user actions elsewhere.

However I need to order this collection by a type field so I can iterate over it elsewhere correctly.

In the case of the example playground below, I need a reordered collection that would follow this logic:

```<code>[
  Item(type: .foo),
  Item(type: .bar),

  Item(type: .boo),
  Item(type: .baz),

  Item(type: .boom),
  Item(type: .bang)

]
</code>```

Specifically .foo and .bar should be the first 2 items, .boom and bang will be the last 2 items.

These fixed items are unique, no duplicates will exist in the response.

Everything left over should be between these 2 groups, in the same order as they are in the original collection.

I have tried to split the item into 2 collections within var output: [Item] and insert the second collection at an index, however the ordering is still off.

How can I achieve this?

import UIKit

enum ItemType: String {
  case foo
  case bar
  case boo
  case baz
  case boom
  case bang
}

struct Item {
  let type: ItemType
}

let props = [
  Item(type: .bang),
  Item(type: .bar),
  Item(type: .baz),
  Item(type: .boo),
  Item(type: .boom),
  Item(type: .foo)
]

/*
 case foo
 case bar
 > ----------- should be ordered in same order as in `props`
 case boom
 case bang
*/

var output: [Item] {
  var fixedPosition: [Item] = []
  var dynamicPosition: [Item] = []

  props.forEach { item in
    if (item.type == .foo || item.type == .bar || item.type == .boom || item.type == .bang ){
      fixedPosition.append(item)
    } else {
      dynamicPosition.append(item)
    }
  }

  var result: [Item] = fixedPosition
  result.insert(contentsOf: dynamicPosition, at: 1)

  return result
}

print(output.map { $0.type })
```

答:
Variation with ItemType implementing Comparable protocol:

```<code>extension ItemType: Comparable {
    static func < (lhs: ItemType, rhs: ItemType) -> Bool {
        // function returns `true` iff lhs is smaller than res

        // order of cases matters here, switch matches them left-to-right, top-to-bottom
        switch (lhs, rhs) {
        case (.foo, _): // .foo is before everyone else
            return true
        case (_, .foo): // nothing is "smaller" than .foo
            return false
        case (.bar, _):  // .bar can be preceded only by .foo (previous 2 cases handle it)
            return true
        case (_, .bang): // .bang is always last
            return true
        case (.bang, _): // nothing is "bigger" than .bang
            return false
        case (_, .boom): // .boom can be only before .bang (previous 2 cases handle it)
            return true
        default: // otherwise we don't care about comparing items, neither item is "smaller" than other
            return false
        }
    }
}
</code>```

Body:
I have an array of Item. The order is never guaranteed as the collection is served from an API based on a number of user actions elsewhere.

However I need to order this collection by a type field so I can iterate over it elsewhere correctly.

In the case of the example playground below, I need a reordered collection that would follow this logic:

[
  Item(type: .foo),
  Item(type: .bar),

  Item(type: .boo),
  Item(type: .baz),

  Item(type: .boom),
  Item(type: .bang)

]

Specifically .foo and .bar should be the first 2 items, .boom and bang will be the last 2 items.

These fixed items are unique, no duplicates will exist in the response.

Everything left over should be between these 2 groups, in the same order as they are in the original collection.

I have tried to split the item into 2 collections within var output: [Item] and insert the second collection at an index, however the ordering is still off.

How can I achieve this?

import UIKit

enum ItemType: String {
  case foo
  case bar
  case boo
  case baz
  case boom
  case bang
}

struct Item {
  let type: ItemType
}

let props = [
  Item(type: .bang),
  Item(type: .bar),
  Item(type: .baz),
  Item(type: .boo),
  Item(type: .boom),
  Item(type: .foo)
]

/*
 case foo
 case bar
 > ----------- should be ordered in same order as in `props`
 case boom
 case bang
*/

var output: [Item] {
  var fixedPosition: [Item] = []
  var dynamicPosition: [Item] = []

  props.forEach { item in
    if (item.type == .foo || item.type == .bar || item.type == .boom || item.type == .bang ){
      fixedPosition.append(item)
    } else {
      dynamicPosition.append(item)
    }
  }

  var result: [Item] = fixedPosition
  result.insert(contentsOf: dynamicPosition, at: 1)

  return result
}

print(output.map { $0.type })

Body:
Variation with ItemType implementing Comparable protocol:

extension ItemType: Comparable {
    static func < (lhs: ItemType, rhs: ItemType) -> Bool {
        // function returns `true` iff lhs is smaller than res

        // order of cases matters here, switch matches them left-to-right, top-to-bottom
        switch (lhs, rhs) {
        case (.foo, _): // .foo is before everyone else
            return true
        case (_, .foo): // nothing is "smaller" than .foo
            return false
        case (.bar, _):  // .bar can be preceded only by .foo (previous 2 cases handle it)
            return true
        case (_, .bang): // .bang is always last
            return true
        case (.bang, _): // nothing is "bigger" than .bang
            return false
        case (_, .boom): // .boom can be only before .bang (previous 2 cases handle it)
            return true
        default: // otherwise we don't care about comparing items, neither item is "smaller" than other
            return false
        }
    }
}


问:
405 (Method Not Allowed) Laravel
I am getting a 405 (Method Not Allowed) in Laravel while trying to delete an item using ajax. Someone please help.

Here is my route

```<code>Route::get('/home', 'HomeController@index')->name('home');
Route::post('/destroy', 'PagesController@destroy');
Auth::routes();
</code>```

Here is my ajax code

```<code>        function confirmDelete(id){
        //alert('Delete post id-'+id);
        $.ajax({
            type: 'post',
            url: 'blogs/destroy',
            data: {'id' : id},
            dataType: 'json',
            cache: false,
            success: function(res){
                console.log("worked");
                    alert(res);
            }
        })
    }
</code>```

Here is my controller

```<code>public function destroy (Request $request){
    $id = $request->id;
    echo json_encode ($id);
//        $blog = Blog::findorFail ( $id );
//        $blog->delete ();
//        return response(['msg'=>'Post deleted',
'status'=>'success']);
//        return redirect::to ( '/blogs' )->with ( 'success', 'Post
successfully deleted!' );
}
</code>```

答: Got the answer just login to my server and disable the ModSecurity and its works, so, later on, I configure the ModSecurity to not get the 405 methods not allowed error on live server.</p>

Title: 405 (Method Not Allowed) Laravel

Body:
I am getting a 405 (Method Not Allowed) in Laravel while trying to delete an item using ajax. Someone please help.

Here is my route

Route::get('/home', 'HomeController@index')->name('home');
Route::post('/destroy', 'PagesController@destroy');
Auth::routes();

Here is my ajax code

        function confirmDelete(id){
        //alert('Delete post id-'+id);
        $.ajax({
            type: 'post',
            url: 'blogs/destroy',
            data: {'id' : id},
            dataType: 'json',
            cache: false,
            success: function(res){
                console.log("worked");
                    alert(res);
            }
        })
    }

Here is my controller

public function destroy (Request $request){
    $id = $request->id;
    echo json_encode ($id);
//        $blog = Blog::findorFail ( $id );
//        $blog->delete ();
//        return response(['msg'=>'Post deleted',
'status'=>'success']);
//        return redirect::to ( '/blogs' )->with ( 'success', 'Post
successfully deleted!' );
}


问:
Textbox onKeyPress in Firefox not working
```<code><html>
<head>
    <script>
        function handleKeyPress(evt) {
            var nbr;
            var nbr = (window.event) ? event.keyCode : evt.which;
            alert(nbr);
            return true;
        }
    </script>
</head>
<body>
    <form>
        <input type=text name="txt" onkeypress="handleKeyPress();">
    </form>
</body>
</html>
</code>```

This is working perfectly with IE but not in Firefox. I'm using IE8 and Firefox 3

答:
You missed to pass event object to handleKeyPress() call.

```<code><input type="text" name="txt" onkeypress="handleKeyPress(event);">
</code>```

Body:
    <form>
        <input type=text name="txt" onkeypress="handleKeyPress();">
    </form>

This is working perfectly with IE but not in Firefox. I'm using IE8 and Firefox 3

Body:
You missed to pass event object to handleKeyPress() call.

<input type="text" name="txt" onkeypress="handleKeyPress(event);">


问:
Deserialize with dynamic object JSON by following type of content - C#
I have JSON string with different object depends on type of message. Example :

Text

```<code>{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "text",
    "text": {
        "body": "Hi"
    }
}
</code>```

Image

```<code>{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "image",
    "image": {
        "mime_type": "image/jpeg",
        "link": "http://lala.com/Files/image.jpeg",
        "caption": "your image caption"
    }
}
</code>```

And many more. The key such name, from, id and others is still same.

So what I do in code, I have to create objects for each type :

Object for Text

```<code>public class InboundMessageText
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public TextMessage Text { get; set; }
}

public class TextMessage
{
    public string Body { get; set; }
}
</code>```

Object for Image

```<code>public class InboundMessageImage
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public ImageMessage Image{ get; set; }
}

public class ImageMessage
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}
</code>```

This how I deserialize

```<code>var inboundMessage = JsonConvert.DeserializeObject <InboundMessageText> ("json string");

var addInboundMessage = new Data.Domain.InboundMessage {
    From = inboundMessage.Message.From,
    Name = inboundMessage.Message.Name,
    MessageId = inboundMessage.Message.Id,
    MessageTimestamp = DateTimeOffset.FromUnixTimeSeconds(inboundMessage.Message.Timestamp).LocalDateTime,
};

if (inboundMessage.Message.Type == "text") {

    addInboundMessage.InboundType = InboundType.Text;
    addInboundMessage.Text = inboundMessage.Message.TextMessage.Body;

}
else if (inboundMessage.Message.Type == "image") {
    //So here I have to deserialize again for image object

    var inboundMessageImage = JsonConvert.DeserializeObject <InboundMessageImage>("json string");

    addInboundMessage.InboundType = InboundType.Image;

    //Business logic
}
//and many type more...
</code>```

The code is working, but I have more than 7 types of message so make it my code is to long.

It's that possible to simplify the code?

答:
you can combine to super object and check is item is null or not </p>

```<code>public class InboundMessageText
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public TextMessage Text { get; set; }
    public ImageMessage Image{ get; set; }
}

public class ImageMessage
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}

public class TextMessage
{
    public string Body { get; set; }
}

var inboundMessage = JsonConvert.DeserializeObject <InboundMessageText> ("json string");

if (inboundMessage.Message.Type == "text") {
//InboundType.Text ;
 }

if (inboundMessage.Message.Type == "image") {
//  InboundType.Image;
 }
</code>```

Body:
I have JSON string with different object depends on type of message. Example :

Text

{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "text",
    "text": {
        "body": "Hi"
    }
}

Image

{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "image",
    "image": {
        "mime_type": "image/jpeg",
        "link": "http://lala.com/Files/image.jpeg",
        "caption": "your image caption"
    }
}

And many more. The key such name, from, id and others is still same.

So what I do in code, I have to create objects for each type :

Object for Text

public class InboundMessageText
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public TextMessage Text { get; set; }
}

public class TextMessage
{
    public string Body { get; set; }
}

Object for Image

public class InboundMessageImage
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public ImageMessage Image{ get; set; }
}

public class ImageMessage
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}

This how I deserialize

var inboundMessage = JsonConvert.DeserializeObject <InboundMessageText> ("json string");

var addInboundMessage = new Data.Domain.InboundMessage {
    From = inboundMessage.Message.From,
    Name = inboundMessage.Message.Name,
    MessageId = inboundMessage.Message.Id,
    MessageTimestamp = DateTimeOffset.FromUnixTimeSeconds(inboundMessage.Message.Timestamp).LocalDateTime,
};

if (inboundMessage.Message.Type == "text") {

    addInboundMessage.InboundType = InboundType.Text;
    addInboundMessage.Text = inboundMessage.Message.TextMessage.Body;

}
else if (inboundMessage.Message.Type == "image") {
    //So here I have to deserialize again for image object

    var inboundMessageImage = JsonConvert.DeserializeObject <InboundMessageImage>("json string");

    addInboundMessage.InboundType = InboundType.Image;

    //Business logic
}
//and many type more...

The code is working, but I have more than 7 types of message so make it my code is to long.

It's that possible to simplify the code?

Body:
you can combine to super object and check is item is null or not

public class InboundMessageText
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public TextMessage Text { get; set; }
    public ImageMessage Image{ get; set; }
}

public class ImageMessage
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}

public class TextMessage
{
    public string Body { get; set; }
}

var inboundMessage = JsonConvert.DeserializeObject <InboundMessageText> ("json string");

if (inboundMessage.Message.Type == "text") {
//InboundType.Text ;
 }

if (inboundMessage.Message.Type == "image") {
//  InboundType.Image;
 }


问:
Flattening data in SQL server by joining multiple tables
I want to flatten parent-child tables for data analysis purposes.
I have Service order table tssoc210 as

```<code>orno|acln
1   |10
1   |20
2   |20
.
.
</code>```

it's activities(labour,material,other) are maintained in 3 other tables as
tssoc220 (for labour)

```<code>orno|acln|lino|invn|eqan|asto
1   |10  |A   |600 |2   |120
1   |10  |B   |607 |1   |100
.
.
</code>```

tssoc230 (for materials)

```<code>orno|acln|lino|invn|eqan|asto
1   |10  |L1  |700 |1   |110
1   |10  |L2  |704 |3   |200
1   |10  |L3  |407 |4   |100
1   |20  |L1  |708 |1   |100
2   |20  |L1  |790 |1   |200
.
.
</code>```

tssoc240(for other)

```<code>orno|acln|lino|invn|eqan|asto
1   |10  |M1  |400 |2   |500
2   |20  |M1  |490 |1   |100
.
.
</code>```

I want to join these tables as

```<code>orno|acln|l_lino|l_invn|l_eqan|l_asto|m_lino|m_invn|m_eqan|m_asto|o_lino|o_invn|o_eqan|o_asto
1   |10  |A     |600   |2     |120   |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL
1   |10  |B     |607   |1     |100   |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L1    |700   |1     |110   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L2    |704   |3     |200   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L3    |407   |4     |100   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |M1    |400   |2     |500
1   |20  | NULL |NULL  |NULL  |NULL  |L1    |708   |1     |100   |NULL  |NULL  |NULL  |NULL
2   |20  | NULL |NULL  |NULL  |NULL  |L1    |790   |1     |200   |NULL  |NULL  |NULL  |NULL
2   |20  | NULL |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |M1    |490   |1     |100
.
.
</code>```

If I left join tssoc220,tssoc230, tssoc240 with tssoc210(tssoc210 as a left table), it duplicates the row.

```<code>left join tssoc220 ON  tssoc210.orno = tssoc220.orno and tssoc210.acln = tssoc220.acln
left join tssoc230 ON  tssoc210.orno = tssoc230.orno and tssoc210.acln = tssoc230.acln
left join tssoc240 ON  tssoc210.orno = tssoc240.orno and tssoc210.acln = tssoc240.acln
</code>```

Where am I going wrong?

答:
You will need to write 3 queries that join only 1 table and union them.</p>

```<code>SELECT tssoc210.orno,tssoc210.acln,tssoc220.l_lino,tssoc220.l_invn,tssoc220.l_eqan,tssoc220.l_asto,NULL as m_lino,NULL as m_invn,NULL as m_eqan,NULL as m_asto,NULL as o_lino,NULL as o_invn,NULL as o_eqan,NULL as o_asto
FROM tssoc210
left join tssoc220 ON  tssoc210.orno = tssoc220.orno and tssoc210.acln = tssoc220.acln
UNION ALL
SELECT  tssoc210.orno,tssoc210.acln,NULL as l_lino,NULL as l_invn,NULL as l_eqan,NULL as l_asto,tssoc230.m_lino,tssoc230.m_invn,tssoc230.m_eqan,tssoc230.m_asto,NULL as o_lino,NULL as o_invn,NULL as o_eqan,NULL as o_asto
FROM tssoc210
left join tssoc230 ON  tssoc210.orno = tssoc230.orno and tssoc210.acln = tssoc230.acln
UNION ALL
SELECT  tssoc210.orno,tssoc210.acln,NULL as l_lino,NULL as l_invn,NULL as l_eqan,NULL as l_asto,,NULL as m_lino,NULL as m_invn,NULL as m_eqan,NULL as m_asto,tssoc240.o_lino,tssoc240.o_invn,tssoc240.o_eqan,tssoc240.o_asto
FROM tssoc210
left join tssoc240 ON  tssoc210.orno = tssoc240.orno and tssoc210.acln = tssoc240.acln
</code>```

Body:
I want to flatten parent-child tables for data analysis purposes.
I have Service order table tssoc210 as

orno|acln
1   |10
1   |20
2   |20
.
.

it's activities(labour,material,other) are maintained in 3 other tables as
tssoc220 (for labour)

orno|acln|lino|invn|eqan|asto
1   |10  |A   |600 |2   |120
1   |10  |B   |607 |1   |100
.
.

tssoc230 (for materials)

orno|acln|lino|invn|eqan|asto
1   |10  |L1  |700 |1   |110
1   |10  |L2  |704 |3   |200
1   |10  |L3  |407 |4   |100
1   |20  |L1  |708 |1   |100
2   |20  |L1  |790 |1   |200
.
.

tssoc240(for other)

orno|acln|lino|invn|eqan|asto
1   |10  |M1  |400 |2   |500
2   |20  |M1  |490 |1   |100
.
.

I want to join these tables as

orno|acln|l_lino|l_invn|l_eqan|l_asto|m_lino|m_invn|m_eqan|m_asto|o_lino|o_invn|o_eqan|o_asto
1   |10  |A     |600   |2     |120   |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL
1   |10  |B     |607   |1     |100   |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L1    |700   |1     |110   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L2    |704   |3     |200   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L3    |407   |4     |100   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |M1    |400   |2     |500
1   |20  | NULL |NULL  |NULL  |NULL  |L1    |708   |1     |100   |NULL  |NULL  |NULL  |NULL
2   |20  | NULL |NULL  |NULL  |NULL  |L1    |790   |1     |200   |NULL  |NULL  |NULL  |NULL
2   |20  | NULL |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |M1    |490   |1     |100
.
.

If I left join tssoc220,tssoc230, tssoc240 with tssoc210(tssoc210 as a left table), it duplicates the row.

left join tssoc220 ON  tssoc210.orno = tssoc220.orno and tssoc210.acln = tssoc220.acln
left join tssoc230 ON  tssoc210.orno = tssoc230.orno and tssoc210.acln = tssoc230.acln
left join tssoc240 ON  tssoc210.orno = tssoc240.orno and tssoc210.acln = tssoc240.acln

Where am I going wrong?

Body:
You will need to write 3 queries that join only 1 table and union them.

SELECT tssoc210.orno,tssoc210.acln,tssoc220.l_lino,tssoc220.l_invn,tssoc220.l_eqan,tssoc220.l_asto,NULL as m_lino,NULL as m_invn,NULL as m_eqan,NULL as m_asto,NULL as o_lino,NULL as o_invn,NULL as o_eqan,NULL as o_asto
FROM tssoc210
left join tssoc220 ON  tssoc210.orno = tssoc220.orno and tssoc210.acln = tssoc220.acln
UNION ALL
SELECT  tssoc210.orno,tssoc210.acln,NULL as l_lino,NULL as l_invn,NULL as l_eqan,NULL as l_asto,tssoc230.m_lino,tssoc230.m_invn,tssoc230.m_eqan,tssoc230.m_asto,NULL as o_lino,NULL as o_invn,NULL as o_eqan,NULL as o_asto
FROM tssoc210
left join tssoc230 ON  tssoc210.orno = tssoc230.orno and tssoc210.acln = tssoc230.acln
UNION ALL
SELECT  tssoc210.orno,tssoc210.acln,NULL as l_lino,NULL as l_invn,NULL as l_eqan,NULL as l_asto,,NULL as m_lino,NULL as m_invn,NULL as m_eqan,NULL as m_asto,tssoc240.o_lino,tssoc240.o_invn,tssoc240.o_eqan,tssoc240.o_asto
FROM tssoc210
left join tssoc240 ON  tssoc210.orno = tssoc240.orno and tssoc210.acln = tssoc240.acln


问:
make site available only from given ip
Is it possible to set my entaire web application available only from given ip address ? Can I use global.asax or something to place the code only in one place and be able to remove this freely ?

Thanks for any hints

答:
Best solution for me is to filter IPs in IIS.

I've done it and it works properly ... and you do not have to change a single line of code.

If you do not have access to IIS, then you can follow Scott Hanselman's suggestion and create a custom HttpModule:

```<code>namespace YourModuleNameHere
{
    public class IPBlackList : IHttpModule
    {
        private EventHandler onBeginRequest;

        public IPBlackList()
        {
            onBeginRequest = new EventHandler(this.HandleBeginRequest);
        }

        void IHttpModule.Dispose()
        {
        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += onBeginRequest;
        }

        const string BLOCKEDIPSKEY = "blockedips";
        const string BLOCKEDIPSFILE = "SiteConfig/blockedips.config";

        public static StringDictionary GetBlockedIPs(HttpContext context)
        {
            StringDictionary ips = (StringDictionary)context.Cache[BLOCKEDIPSKEY];
            if (ips == null)
            {
                ips = GetBlockedIPs(GetBlockedIPsFilePathFromCurrentContext(context));
                context.Cache.Insert(BLOCKEDIPSKEY, ips, new CacheDependency(GetBlockedIPsFilePathFromCurrentContext(context)));
            }
            return ips;
        }

        private static string BlockedIPFileName = null;
        private static object blockedIPFileNameObject = new object();
        public static string GetBlockedIPsFilePathFromCurrentContext(HttpContext context)
        {
            if (BlockedIPFileName != null)
                return BlockedIPFileName;
            lock (blockedIPFileNameObject)
            {
                if (BlockedIPFileName == null)
                {
                    BlockedIPFileName = context.Server.MapPath(BLOCKEDIPSFILE);
                }
            }
            return BlockedIPFileName;
        }

        public static StringDictionary GetBlockedIPs(string configPath)
        {
            StringDictionary retval = new StringDictionary();
            using (StreamReader sr = new StreamReader(configPath))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.Length != 0)
                    {
                        retval.Add(line, null);
                    }
                }
            }
            return retval;
        }

        private void HandleBeginRequest(object sender, EventArgs evargs)
        {
            HttpApplication app = sender as HttpApplication;

            if (app != null)
            {
                string IPAddr = app.Context.Request.ServerVariables["REMOTE_ADDR"];
                if (IPAddr == null || IPAddr.Length == 0)
                {
                    return;
                }

                StringDictionary badIPs = GetBlockedIPs(app.Context);
                if (badIPs != null && badIPs.ContainsKey(IPAddr))
                {
                    app.Context.Response.StatusCode = 404;
                    app.Context.Response.SuppressContent = true;
                    app.Context.Response.End();
                    return;
                }
            }
        }
    }
}
</code>```

and use it in your web.config:

```<code><system.web>
    <httpModules>
        <add type = "YourModuleNameHere.IPBlackList, YourAssemblyNameHere" name="IPBlackList" />
   </httpModules>
</system.web>
</code>```

Title: make site available only from given ip

Body:
Best solution for me is to filter IPs in IIS.

I've done it and it works properly ... and you do not have to change a single line of code.

If you do not have access to IIS, then you can follow Scott Hanselman's suggestion and create a custom HttpModule:

namespace YourModuleNameHere
{
    public class IPBlackList : IHttpModule
    {
        private EventHandler onBeginRequest;

        public IPBlackList()
        {
            onBeginRequest = new EventHandler(this.HandleBeginRequest);
        }

        void IHttpModule.Dispose()
        {
        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += onBeginRequest;
        }

        const string BLOCKEDIPSKEY = "blockedips";
        const string BLOCKEDIPSFILE = "SiteConfig/blockedips.config";

        public static StringDictionary GetBlockedIPs(HttpContext context)
        {
            StringDictionary ips = (StringDictionary)context.Cache[BLOCKEDIPSKEY];
            if (ips == null)
            {
                ips = GetBlockedIPs(GetBlockedIPsFilePathFromCurrentContext(context));
                context.Cache.Insert(BLOCKEDIPSKEY, ips, new CacheDependency(GetBlockedIPsFilePathFromCurrentContext(context)));
            }
            return ips;
        }

        private static string BlockedIPFileName = null;
        private static object blockedIPFileNameObject = new object();
        public static string GetBlockedIPsFilePathFromCurrentContext(HttpContext context)
        {
            if (BlockedIPFileName != null)
                return BlockedIPFileName;
            lock (blockedIPFileNameObject)
            {
                if (BlockedIPFileName == null)
                {
                    BlockedIPFileName = context.Server.MapPath(BLOCKEDIPSFILE);
                }
            }
            return BlockedIPFileName;
        }

        public static StringDictionary GetBlockedIPs(string configPath)
        {
            StringDictionary retval = new StringDictionary();
            using (StreamReader sr = new StreamReader(configPath))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.Length != 0)
                    {
                        retval.Add(line, null);
                    }
                }
            }
            return retval;
        }

        private void HandleBeginRequest(object sender, EventArgs evargs)
        {
            HttpApplication app = sender as HttpApplication;

            if (app != null)
            {
                string IPAddr = app.Context.Request.ServerVariables["REMOTE_ADDR"];
                if (IPAddr == null || IPAddr.Length == 0)
                {
                    return;
                }

                StringDictionary badIPs = GetBlockedIPs(app.Context);
                if (badIPs != null && badIPs.ContainsKey(IPAddr))
                {
                    app.Context.Response.StatusCode = 404;
                    app.Context.Response.SuppressContent = true;
                    app.Context.Response.End();
                    return;
                }
            }
        }
    }
}

and use it in your web.config:

<system.web>
    <httpModules>
        <add type = "YourModuleNameHere.IPBlackList, YourAssemblyNameHere" name="IPBlackList" />
   </httpModules>
</system.web>


问:
How to move blazor components to a different assembly
I have a blazor server project, and I wanted to move some of the shared components to a different assembly to see if it would make a difference in the compilation times (bonus for letting me know if this would work...), but this isn't going so well.

In VS2019 the razor.cs parts of the components are at the same level as the .razor parts (rather than being 'under' them as they are in the blazor project), and other components can't find them. Oddly the project builds and runs, but the components are just drawn blank. I've cleaned, rebuilt, deleted the bin and obj folders, restarted VS etc, and no changes.

I have updated the _Imports.razor file, and everything should be as it needs to be, but this just isn't working.

Any help appreciated!

EDIT: This is 'Under':

And this is how it's displaying:

答:
How to move blazor components to a different assembly ?

You can change the namespace using @namespace Your.Name.Space


问:
Refreshing 3rd Party API Within a VBA Loop
I'm trying to run a loop in VBA that will refresh the third party data, copy/paste the output as values, change the API period to an earlier date and run this on a loop. My issue, I think, is that VBA doesn't wait for the third party data to refresh before copy/pasting the next set of values. I'm using FactSet as the API and pulling some pretty simple data.

i = my relative date range. I start with -1 (equal to last month) and I want the loop to continue moving this month field back by one before restarting the refresh and copy/paste.

ExecuteExcel4Macro refreshes FDS codes for the whole workbook - this works fine.

The third group of code is supposed to wait until the FDS codes refresh, no longer throw errors, and copy/paste the output.

The i variable isn't changing, the FDS codes get refreshed too often, and the loop just copy/pastes the same data over and over.

Any help is much appreciated.

```<code>Dim i As Long
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
ws.Activate

i = ws.Range("E3")

Do While i > -5
    ws.Range("E3").Value = i - 1

ExecuteExcel4Macro "FDSFORCERECALC(FALSE)"

Sheets("Sheet2").Select
    If Application.WorksheetFunction.CountIfs(Range("4:4"), "#DIV/0!") > 0 Then
    'Check every 3 seconds
        Application.OnTime Now + TimeValue("00:00:03"), "Check_API"
    Else
        With Sheets("Sheet2")
        lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
        End With

        Sheets("Sheet2").Select
        Rows("4:4").Select
        Selection.Copy
        Rows(lastRow).Select
        Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
             xlNone, SkipBlanks:=False, Transpose:=False

   End If
Loop

End Sub
</code>```

答:
What do you want to do?

```<code>i = ws.Range("E3")

Do While i > -5
    ws.Range("E3").Value = i - 1
</code>```

It seems like your loop is never ending loop because your i variable is always the same

If you want decreasing counter, try to use:

```<code>i = ws.Range("E3")

Do While i > -5
  i = i - 1
    ws.Range("E3").Value = i
</code>```

Body:
I'm trying to run a loop in VBA that will refresh the third party data, copy/paste the output as values, change the API period to an earlier date and run this on a loop. My issue, I think, is that VBA doesn't wait for the third party data to refresh before copy/pasting the next set of values. I'm using FactSet as the API and pulling some pretty simple data.

i = my relative date range. I start with -1 (equal to last month) and I want the loop to continue moving this month field back by one before restarting the refresh and copy/paste.

ExecuteExcel4Macro refreshes FDS codes for the whole workbook - this works fine.

The third group of code is supposed to wait until the FDS codes refresh, no longer throw errors, and copy/paste the output.

The i variable isn't changing, the FDS codes get refreshed too often, and the loop just copy/pastes the same data over and over.

Any help is much appreciated.

Dim i As Long
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
ws.Activate

i = ws.Range("E3")

Do While i > -5
    ws.Range("E3").Value = i - 1

ExecuteExcel4Macro "FDSFORCERECALC(FALSE)"

Sheets("Sheet2").Select
    If Application.WorksheetFunction.CountIfs(Range("4:4"), "#DIV/0!") > 0 Then
    'Check every 3 seconds
        Application.OnTime Now + TimeValue("00:00:03"), "Check_API"
    Else
        With Sheets("Sheet2")
        lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
        End With

        Sheets("Sheet2").Select
        Rows("4:4").Select
        Selection.Copy
        Rows(lastRow).Select
        Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
             xlNone, SkipBlanks:=False, Transpose:=False

   End If
Loop

End Sub

Body:
What do you want to do?

i = ws.Range("E3")

Do While i > -5
    ws.Range("E3").Value = i - 1

It seems like your loop is never ending loop because your i variable is always the same

If you want decreasing counter, try to use:

i = ws.Range("E3")

Do While i > -5
  i = i - 1
    ws.Range("E3").Value = i


问:
How to find minimum sum of elements in a matrix python
How do I compute the minimum sum of elements in a matrix python?
for example:

```<code>z =
np.array([[1, 2, 3],

 [3, 2, 5],

 [2, 4, 4]])
</code>```

The minimum sum of the element is : 1+2+2 = 5

I tried:

```<code>def calculate(a):
    sum = 0
    for i in range(len(a)):
        sum += np.sum(a[i])

    return sum
</code>```

but it gives me 26 instead of 5

答:
You are adding the sum of the entire row to the sum, when you should be adding the minimum value. So just replace sum with min:

```<code>z = np.array([[1, 2, 3], [3, 2, 5], [2, 4, 4]])

def calculate(a):
    sum = 0
    for row in a:
        sum += np.min(row)
    return sum

print(calculate(z))

>>> 5
</code>```

I also optimized your loop method to be clearer.

Body:
How do I compute the minimum sum of elements in a matrix python?
for example:

z =
np.array([[1, 2, 3],

 [3, 2, 5],

 [2, 4, 4]])

The minimum sum of the element is : 1+2+2 = 5

I tried:

def calculate(a):
    sum = 0
    for i in range(len(a)):
        sum += np.sum(a[i])

    return sum

but it gives me 26 instead of 5

Body:
You are adding the sum of the entire row to the sum, when you should be adding the minimum value. So just replace sum with min:

z = np.array([[1, 2, 3], [3, 2, 5], [2, 4, 4]])

def calculate(a):
    sum = 0
    for row in a:
        sum += np.min(row)
    return sum

print(calculate(z))

>>> 5

I also optimized your loop method to be clearer.


问:
determining the staff's title when a certain transaction is done
I have a transaction table with relevant data and username. and also, there is a another table that stores staff's title history by date. However, title history table doesnt have log of every single day.

Here is an example of my transaction table:

```<code>username    tran_date   amount
--------    ----------  ------
anderson    16/02/2019  1200
julie       17/02/2019  54000
williams    20/02/2019  32650
</code>```

and staff's title log table:

```<code>username    date        title
--------    ----        ------
anderson    01/01/2019  assistant
anderson    06/04/2019  chief
williams    07/03/2019  chief
julie       15/02/2019  technician
julie       27/05/2019  chief technician
</code>```

I would like to join with the title of staff on the closest day. as in;

```<code>username    tran_date   amount    title
--------    ----------  ------    ------
anderson    16/02/2019  1200      assistant
julie       17/02/2019  54000     technician
williams    20/02/2019  32650     chief
</code>```

I have tried something blindly but nothing seems to logical :)

thanks for help!

答:
In SQL Server, you would express this using outer apply:

```<code>select t.username, t.tran_date, l.title
from transactions t outer apply
     (select top (1) l.*
      from log_table l
      where l.username = t.username and l.date <= t.tran_date
      order by l.date desc
     ) l ;
</code>```

outer apply is SQL Servers equivalent to left join lateral.

Body:
I have a transaction table with relevant data and username. and also, there is a another table that stores staff's title history by date. However, title history table doesnt have log of every single day.

Here is an example of my transaction table:

username    tran_date   amount
--------    ----------  ------
anderson    16/02/2019  1200
julie       17/02/2019  54000
williams    20/02/2019  32650

and staff's title log table:

username    date        title
--------    ----        ------
anderson    01/01/2019  assistant
anderson    06/04/2019  chief
williams    07/03/2019  chief
julie       15/02/2019  technician
julie       27/05/2019  chief technician

I would like to join with the title of staff on the closest day. as in;

username    tran_date   amount    title
--------    ----------  ------    ------
anderson    16/02/2019  1200      assistant
julie       17/02/2019  54000     technician
williams    20/02/2019  32650     chief

I have tried something blindly but nothing seems to logical :)

thanks for help!

Body:
In SQL Server, you would express this using outer apply:

select t.username, t.tran_date, l.title
from transactions t outer apply
     (select top (1) l.*
      from log_table l
      where l.username = t.username and l.date <= t.tran_date
      order by l.date desc
     ) l ;

outer apply is SQL Servers equivalent to left join lateral.