问:
Amplify Datastore reachability false in Android
Working on a React Native Expo project, I am fetching data using DataStore.query to my amplify backend.

```<code>const fetchRestaurants = async () => {
        const results = await DataStore.query(Restaurant)
        setRestaurants(results)
    }

    useEffect(() => {
        fetchRestaurants()
    }, [])
</code>```

For iOS, I get:

```<code>iOS Bundling complete 53ms
 LOG  [INFO] 49:57.609 Reachability - subscribing to reachability in React Native
 LOG  [INFO] 50:58.504 Reachability - Notifying reachability change true
</code>```

However for Android, I get:

```<code>Android Bundling complete 73ms
 LOG  [INFO] 50:58.358 Reachability - subscribing to reachability in React Native
 LOG  [INFO] 51:58.380 Reachability - Notifying reachability change false
</code>```

The Notifying reachability for android is false, as a result it fails to fetch any data from the backend. For iOS it works.

Body:
Working on a React Native Expo project, I am fetching data using DataStore.query to my amplify backend.

const fetchRestaurants = async () => {
        const results = await DataStore.query(Restaurant)
        setRestaurants(results)
    }

    useEffect(() => {
        fetchRestaurants()
    }, [])

For iOS, I get:

iOS Bundling complete 53ms
 LOG  [INFO] 49:57.609 Reachability - subscribing to reachability in React Native
 LOG  [INFO] 50:58.504 Reachability - Notifying reachability change true

However for Android, I get:

Android Bundling complete 73ms
 LOG  [INFO] 50:58.358 Reachability - subscribing to reachability in React Native
 LOG  [INFO] 51:58.380 Reachability - Notifying reachability change false

The Notifying reachability for android is false, as a result it fails to fetch any data from the backend. For iOS it works.


来源: stackexchange

问:
Resume stepping on an invoked method when using DebuggerStepThrough on the enclosing method
I've got a method that I'd like to automatically step though. The problem is that it is a dispatcher for an command bus and would like to not step over the method that it invokes as well. There is a lot that I mostly never need to step through in that dispatch method.  Using [DebuggerStepThrough] just steps through everything. Is there a way for the debugger to resume stepping on certain line, say, like right before the particular method is invoked? Or an attribute to put on the invokable methods that breaks only when stepping, but not when running? I could put breakpoints on them, but then I'd have to disable every single one anytime I run. Some code bones for context:</p>
```<code>        public Dictionary<Type, Action> _handlers = new() { { typeof(Command), Handler } };

        [DebuggerStepThrough]
        public void Handle(Command command)
        {
            //junk
            _handlers[command.GetType()]();
            //junk
        }

        public static void Handler()
        {
            //Start stepping again here
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got a method that I'd like to automatically step though. The problem is that it is a dispatcher for an command bus and would like to not step over the method that it invokes as well. There is a lot that I mostly never need to step through in that dispatch method.  Using [DebuggerStepThrough] just steps through everything. Is there a way for the debugger to resume stepping on certain line, say, like right before the particular method is invoked? Or an attribute to put on the invokable methods that breaks only when stepping, but not when running? I could put breakpoints on them, but then I'd have to disable every single one anytime I run. Some code bones for context:

        public Dictionary<Type, Action> _handlers = new() { { typeof(Command), Handler } };

        [DebuggerStepThrough]
        public void Handle(Command command)
        {
            //junk
            _handlers[command.GetType()]();
            //junk
        }

        public static void Handler()
        {
            //Start stepping again here
        }


问:
BLE shows connected even when 'didDisconnectPeripheral' is already called
I am trying to disconnect from a BLE device (raspberry-pi3), the delegates for disconnection are being triggered and upon checking explicitly if the peripheral is disconnected it shows that the peripheral is indeed disconnected. But, when I see in the settings app, I still see the device is connected.

Following is what I am trying:

Setup CBCentralManager as I come to the page.

```<code>func setupBLE() {
    lblStatus.text = "Establising connection to the Scrubport"
    self.manager = CBCentralManager(delegate: self, queue: .main)
}
</code>```

Handle any state change if any

```<code>func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        self.dismissAlert()
        self.showLoader()
        self.timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: false, block: { _ in
          // No device found. Stop scanning.
        })
        self.manager?.scanForPeripherals(withServices: [SERVICE_UUID])
        return
    }

    else if central.state == .unauthorized {
        // Permission handlers here:
        return
    }

    // Handle all other cases.
}
</code>```

Upon find the device try connecting

```<code>func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    self.peripheral = peripheral
    connect()
}
</code>```
```<code>func connect() {
    guard let peripheral = peripheral else {
        // Making sure we got the peripheral.
        return
    }
    lblStatus.text = "Connecting..."
    self.manager?.connect(peripheral)
}
</code>```

Upon connection discover the service

```<code>func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    lblStatus.text = "Connected, preparing device for transfer..."
    self.timer.invalidate()
    central.stopScan()
    peripheral.delegate = self
    peripheral.discoverServices([SERVICE_UUID])
}
</code>```

Find the characteristics next

```<code>func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if let services = peripheral.services {
        for service in services {
            if service.uuid == SERVICE_UUID {
              peripheral.discoverCharacteristics([CHARACTERISTICS_UUID], for: service)
            }
        }
    }
}
</code>```

Request notification

```<code>func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    if let characteristics = service.characteristics {
        for characteristic in characteristics {
            if characteristic.uuid == self.CHARACTERISTICS_UUID {
                self.characteristic = characteristic
                peripheral.setNotifyValue(true, for: characteristic)
            }
        }
    }
}
</code>```

Upon getting an update for notification change I do the write and it is all successful.

```<code>func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.isNotifying {
        self.stopLoader()
        lblStatus.text = "Notifying now.."
    } else {
        print("Un-notified")
        print("Trying disconnection")
        manager?.cancelPeripheralConnection(peripheral)
    }
}
</code>```

At the end I want to disconnect, or handle if app is closed or pressed back mid way

Trying clean up using following code:

```<code>fileprivate func cleanup() {
    print("CLEANING")
    guard let manager = manager else {
        return
    }

    print("Check scan.")
    if manager.isScanning {
        print("Stopping scan.")
        manager.stopScan()
    }

    // Don't do anything if we're not connected
    // self.discoveredPeripheral.isConnected is deprecated
    print("Checking peripheral connection")
    guard peripheral?.state == .connected else {
        print("No peripheral connected.")
        return
    }

    // See if we are subscribed to a characteristic on the peripheral
    print("Checking services")
    guard let services = peripheral?.services else {
        print("No services connection found.")
        cancelPeripheralConnection()
        return
    }

    print("Looping services")
    for service in services {
        print("Checking characteristics")
        guard let characteristics = service.characteristics else {
            print("No characteristics")
            continue
        }
        print("Looping characteristics")
        for characteristic in characteristics {
            print("Comparing characteristics UUID is notifying")
            if characteristic.uuid.isEqual(CHARACTERISTICS_UUID) && characteristic.isNotifying {
                print("Un-notifying")
                peripheral?.setNotifyValue(false, for: characteristic)
            } else {
                print("Nope not the one.", characteristic.isNotifying)
            }
        }
    }
}
</code>```
```<code>fileprivate func cancelPeripheralConnection() {
    print("Remove peripheral connection")
    guard let manager = manager, let peripheral = peripheral else {
        print("Manager or peripheral not found!")
        return
    }
    print("Cancelling peripheral connection.")
    // If we've got this far, we're connected, but we're not subscribed, so we just disconnect
    manager.cancelPeripheralConnection(peripheral)
}
</code>```
```<code>func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        self.dismissAlert()
        self.showLoader()
        self.timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: false, block: { _ in
          // No device found. Stop scanning.
        })
        self.manager?.scanForPeripherals(withServices: [SERVICE_UUID])
        return
    }

    else if central.state == .unauthorized {
        // Permission handlers here:
        return
    }

    // Handle all other cases.
}
</code>```0

Following are the logs that get printed on cleanup():

```<code>func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        self.dismissAlert()
        self.showLoader()
        self.timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: false, block: { _ in
          // No device found. Stop scanning.
        })
        self.manager?.scanForPeripherals(withServices: [SERVICE_UUID])
        return
    }

    else if central.state == .unauthorized {
        // Permission handlers here:
        return
    }

    // Handle all other cases.
}
</code>```1

But this what I see in the settings app after clean up.

Body:
I am trying to disconnect from a BLE device (raspberry-pi3), the delegates for disconnection are being triggered and upon checking explicitly if the peripheral is disconnected it shows that the peripheral is indeed disconnected. But, when I see in the settings app, I still see the device is connected.

Following is what I am trying:

Setup CBCentralManager as I come to the page.

func setupBLE() {
    lblStatus.text = "Establising connection to the Scrubport"
    self.manager = CBCentralManager(delegate: self, queue: .main)
}

Handle any state change if any

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        self.dismissAlert()
        self.showLoader()
        self.timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: false, block: { _ in
          // No device found. Stop scanning.
        })
        self.manager?.scanForPeripherals(withServices: [SERVICE_UUID])
        return
    }

    else if central.state == .unauthorized {
        // Permission handlers here:
        return
    }

    // Handle all other cases.
}

Upon find the device try connecting

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    self.peripheral = peripheral
    connect()
}

func connect() {
    guard let peripheral = peripheral else {
        // Making sure we got the peripheral.
        return
    }
    lblStatus.text = "Connecting..."
    self.manager?.connect(peripheral)
}

Upon connection discover the service

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    lblStatus.text = "Connected, preparing device for transfer..."
    self.timer.invalidate()
    central.stopScan()
    peripheral.delegate = self
    peripheral.discoverServices([SERVICE_UUID])
}

Find the characteristics next

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if let services = peripheral.services {
        for service in services {
            if service.uuid == SERVICE_UUID {
              peripheral.discoverCharacteristics([CHARACTERISTICS_UUID], for: service)
            }
        }
    }
}

Request notification

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    if let characteristics = service.characteristics {
        for characteristic in characteristics {
            if characteristic.uuid == self.CHARACTERISTICS_UUID {
                self.characteristic = characteristic
                peripheral.setNotifyValue(true, for: characteristic)
            }
        }
    }
}

Upon getting an update for notification change I do the write and it is all successful.

func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.isNotifying {
        self.stopLoader()
        lblStatus.text = "Notifying now.."
    } else {
        print("Un-notified")
        print("Trying disconnection")
        manager?.cancelPeripheralConnection(peripheral)
    }
}

At the end I want to disconnect, or handle if app is closed or pressed back mid way

Trying clean up using following code:

fileprivate func cleanup() {
    print("CLEANING")
    guard let manager = manager else {
        return
    }

    print("Check scan.")
    if manager.isScanning {
        print("Stopping scan.")
        manager.stopScan()
    }

    // Don't do anything if we're not connected
    // self.discoveredPeripheral.isConnected is deprecated
    print("Checking peripheral connection")
    guard peripheral?.state == .connected else {
        print("No peripheral connected.")
        return
    }

    // See if we are subscribed to a characteristic on the peripheral
    print("Checking services")
    guard let services = peripheral?.services else {
        print("No services connection found.")
        cancelPeripheralConnection()
        return
    }

    print("Looping services")
    for service in services {
        print("Checking characteristics")
        guard let characteristics = service.characteristics else {
            print("No characteristics")
            continue
        }
        print("Looping characteristics")
        for characteristic in characteristics {
            print("Comparing characteristics UUID is notifying")
            if characteristic.uuid.isEqual(CHARACTERISTICS_UUID) && characteristic.isNotifying {
                print("Un-notifying")
                peripheral?.setNotifyValue(false, for: characteristic)
            } else {
                print("Nope not the one.", characteristic.isNotifying)
            }
        }
    }
}

fileprivate func cancelPeripheralConnection() {
    print("Remove peripheral connection")
    guard let manager = manager, let peripheral = peripheral else {
        print("Manager or peripheral not found!")
        return
    }
    print("Cancelling peripheral connection.")
    // If we've got this far, we're connected, but we're not subscribed, so we just disconnect
    manager.cancelPeripheralConnection(peripheral)
}

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    print("SERVICE INFO: didDisconnectPeripheral", peripheral.name ?? "Unknown")
    print("Was there an error?", error ?? "No error")

    self.peripheral = nil

    let peripherals = central.retrieveConnectedPeripherals(withServices: [])
    let _peri = central.retrievePeripherals(withIdentifiers: [peripheral.identifier])

    _peri.forEach { per in
        print(per.state == .connected, "connected")
        print(per.state == .connecting, "connecting")
        print(per.state == .disconnected, "disconnected")
        print(per.state == .disconnecting, "disconnecting")
    }

    print(peripherals)
}

Following are the logs that get printed on cleanup():

CLEANING
Check scan.
Checking peripheral connection
Checking services
Looping services
Checking characteristics
Looping characteristics
Comparing characteristics UUID is notifying
Un-notifying
Un-notified
Trying disconnection
SERVICE INFO: didDisconnectPeripheral raspberrypi-cm3
Was there an error? No error
false connected
false connecting
true disconnected
false disconnecting
[]

But this what I see in the settings app after clean up.


问:
Embed the output of a single Jupyter Notebook cell (using e.g. iframe)
How can I embed the output of a single Jupyter Notebook cell using, for example, the HTML iframe tag?

My goal is to share the output of certain cells of a Jupyter Notebook, that is publicly accessible on the internet, on a website or a blog post instead of sharing the entire Notebook.


问:
How do I allow an empty style in OWASP Java HTML Sanitizer?
Specifically I want to allow:

```<code><td style="">something</td>
</code>```

My code (as I'm trying every permutation at this point I'm adding anything with styles) is:

```<code>PolicyFactory POLICY_DEFINITION = new HtmlPolicyBuilder()
    ...
    .allowElements("style")
    .allowStyling()
    .allowTextIn("style")
    .toFactory();
</code>```

It works great for something	 but fails for something

Body:
Specifically I want to allow:

something

My code (as I'm trying every permutation at this point I'm adding anything with styles) is:

PolicyFactory POLICY_DEFINITION = new HtmlPolicyBuilder()
    ...
    .allowElements("style")
    .allowStyling()
    .allowTextIn("style")
    .toFactory();

It works great for something	 but fails for something


问:
Using react hook forms with dynamically added components
I have some components with the same set of input fields. User could add them or remove them.

```<code>    const [sectionItems, setActionItems] = useState<ISectionItems[]>([
    {id: Date.now(), number: 1}
])

    {sectionItems.map((sectionItem) =>
    <SectionItem
        key={sectionItem.id}
        number={sectionItem.number}
        addSectionItem={addSectionItem}
        removeSectionItem={removeSectionItem}
        isOnlySection={isOnlySection}
    />)}
</code>```

So the fiels are inside each SectionItem component.

I use react-hook-forms to get the data from the form, but I have no idea how to deal with that in the situation when we have dynamically changing list of components

```<code>const SectionItem: FC<SectionItemProps> = (SectionItemProps) => {

const addClickHandler = (e: React.MouseEvent) => {
    SectionItemProps.addSectionItem()
}

const removeClickHandler = (e: React.MouseEvent) => {
    SectionItemProps.removeSectionItem(SectionItemProps.number)
}

return (
    <React.Fragment>
  <Typography variant="h6" gutterBottom sx={{marginTop: 3}}>
            {`Участок № ${SectionItemProps.number}`}
  </Typography>
        <Grid container spacing={3} sx={{marginTop: 1}}>
            <Grid item xs={12} sm={6}>
                <TextField
                    required
                    id="insideDiameter"
                    name="insideDiameter"
                    fullWidth
                    variant="standard"
                />
            </Grid>
            <Grid item xs={12} sm={6}>
                <TextField
                    required
                    id="outsideDiameter"
                    name="outsideDiameter"
                    fullWidth
                    variant="standard"
                />
            </Grid>
        <Grid container spacing={3} sx={{marginTop: 1}}>
            <Grid item xs={12} sm={12} style={{textAlign: "center"}}>
                <Fab size="small" aria-label="add" >
                    <AddIcon color = 'primary' onClick={addClickHandler}/>
                </Fab>
                {SectionItemProps.isOnlySection
                    ?   <></>
                    : <Fab size="small" aria-label="add" sx={{marginLeft: 1}}>
                            <RemoveIcon color='primary' onClick={removeClickHandler} />
                        </Fab>
                }
            </Grid>
        </Grid>
    </React.Fragment>
);
</code>```

Body:
I have some components with the same set of input fields. User could add them or remove them.

    const [sectionItems, setActionItems] = useState<ISectionItems[]>([
    {id: Date.now(), number: 1}
])

    {sectionItems.map((sectionItem) =>
    <SectionItem
        key={sectionItem.id}
        number={sectionItem.number}
        addSectionItem={addSectionItem}
        removeSectionItem={removeSectionItem}
        isOnlySection={isOnlySection}
    />)}

So the fiels are inside each SectionItem component.

I use react-hook-forms to get the data from the form, but I have no idea how to deal with that in the situation when we have dynamically changing list of components

const SectionItem: FC<SectionItemProps> = (SectionItemProps) => {

const addClickHandler = (e: React.MouseEvent) => {
    SectionItemProps.addSectionItem()
}

const removeClickHandler = (e: React.MouseEvent) => {
    SectionItemProps.removeSectionItem(SectionItemProps.number)
}

return (
    <React.Fragment>
  <Typography variant="h6" gutterBottom sx={{marginTop: 3}}>
            {`Участок № ${SectionItemProps.number}`}
  </Typography>
        <Grid container spacing={3} sx={{marginTop: 1}}>
            <Grid item xs={12} sm={6}>
                <TextField
                    required
                    id="insideDiameter"
                    name="insideDiameter"
                    fullWidth
                    variant="standard"
                />
            </Grid>
            <Grid item xs={12} sm={6}>
                <TextField
                    required
                    id="outsideDiameter"
                    name="outsideDiameter"
                    fullWidth
                    variant="standard"
                />
            </Grid>
        <Grid container spacing={3} sx={{marginTop: 1}}>
            <Grid item xs={12} sm={12} style={{textAlign: "center"}}>
                <Fab size="small" aria-label="add" >
                    <AddIcon color = 'primary' onClick={addClickHandler}/>
                </Fab>
                {SectionItemProps.isOnlySection
                    ?   <></>
                    : <Fab size="small" aria-label="add" sx={{marginLeft: 1}}>
                            <RemoveIcon color='primary' onClick={removeClickHandler} />
                        </Fab>
                }
            </Grid>
        </Grid>
    </React.Fragment>
);


问:
Generate modifiers for a keyword using dependency parsing, NLP
I have a dataframe containing reviews of a particular product with the columns month and review. I want perform a type of text analysis on the review column, whereby you can query the for a particular keyword and it will return a list of modifiers for that keyword.

```<code>df = pd.DataFrame({'month': ['Jan', 'Feb', 'Mar', 'Apr', 'Apr'],
                   'review': ['there should be 'share' button on each item. right now when my wife wants me to buy her something, she has to dictate the item id which is horrendous.', 'always nice but high prices', 'this app currently needs more than 3 gigs of space on my phone. that is ridiculous. guess it has to go. /edit cool, trying again, thanks for the answer.', 'impossible to login in the app, is there any way to get the barcode of the card? if i click the link in the email for the card print thingy it just shows a broken image.', 'i cannot change my location and language preference'],
                   'sentiment': ["positive", "negative", "positive", "negative", "neutral"]})
</code>```

For example, say the reviews dataset is from the hospitality industry, and performed sentiment analysis. Upon checking the most frequent words in the positive and negative reviews, you got this.

Positive: hotel, location, staff, view, room, breakfast

Negative: hotel, staff, room, breakfast, window, bed, Wi-Fi

You wanted to go deeper into the analysis and uncover exactly what it was about these objects that were – or were not – working as expected by customers. For example, why were windows such a prominent aspect of negative reviews?

So, you  set out to create a syntactic dependency tree, which connects all terms in the input text according to their syntactic relation. Then, you queried this tree to pinpoint precisely what it was about a given keyword (for example, "room" or "location") that customers did or did not especially like (this is where I need help, I don't know how to implement this in code)

I want a resulting list of modifiers so I can create word clouds to visualize the frequency of each modifier for the given keyword, such as the word cloud below, for the keyword "room":

enter image description here

Honestly I don't even know where to start, I'm currently working with spaCy's dependency parsing to see how it works and what it returns. So while I do that, I also seek help from here.

Body:
I have a dataframe containing reviews of a particular product with the columns month and review. I want perform a type of text analysis on the review column, whereby you can query the for a particular keyword and it will return a list of modifiers for that keyword.

df = pd.DataFrame({'month': ['Jan', 'Feb', 'Mar', 'Apr', 'Apr'],
                   'review': ['there should be 'share' button on each item. right now when my wife wants me to buy her something, she has to dictate the item id which is horrendous.', 'always nice but high prices', 'this app currently needs more than 3 gigs of space on my phone. that is ridiculous. guess it has to go. /edit cool, trying again, thanks for the answer.', 'impossible to login in the app, is there any way to get the barcode of the card? if i click the link in the email for the card print thingy it just shows a broken image.', 'i cannot change my location and language preference'],
                   'sentiment': ["positive", "negative", "positive", "negative", "neutral"]})

For example, say the reviews dataset is from the hospitality industry, and performed sentiment analysis. Upon checking the most frequent words in the positive and negative reviews, you got this.

Positive: hotel, location, staff, view, room, breakfast

Negative: hotel, staff, room, breakfast, window, bed, Wi-Fi

You wanted to go deeper into the analysis and uncover exactly what it was about these objects that were – or were not – working as expected by customers. For example, why were windows such a prominent aspect of negative reviews?

So, you  set out to create a syntactic dependency tree, which connects all terms in the input text according to their syntactic relation. Then, you queried this tree to pinpoint precisely what it was about a given keyword (for example, "room" or "location") that customers did or did not especially like (this is where I need help, I don't know how to implement this in code)

I want a resulting list of modifiers so I can create word clouds to visualize the frequency of each modifier for the given keyword, such as the word cloud below, for the keyword "room":

enter image description here

Honestly I don't even know where to start, I'm currently working with spaCy's dependency parsing to see how it works and what it returns. So while I do that, I also seek help from here.


问:
Python3 How do I make randomized multiple choice questions/answers?
Basically I'm doing a multiple choice question president quiz on who served before the others in said multiple choice question. I've gotten it down fully looped with out the randomness but now I've incorporated arrays and random questions, basically I need to figure out how to make multiple choice questions and then define the logic so that when a person inputs 1,2, or 3 the game will look at all three listed options and know which one is the lowest on the presidents list to identify the correct answer.</p>
```<code>lives = True
import array
import random

print("Welcome to Ahmed's U.S Presidential Quiz!")
print("Please enter your name!")
userName = input()

def answer():
if response == presidents

def lifeCount():

    if livesRemaining == 0:
        print("You're out of lives! Good luck trying again!")
        quit()

    if livesRemaining == 0:
            quit()

while lives:

    presidents = ["George Washington","John Adams","Thomas Jefferson","James Maddison","James Monroe","John Quincy Adams",
    "Andrew Jackson","Martin Van Buren","William Henry Harrison","James K. Polk","Zachary Taylor","Franklin Pierce","James Buchanan","Abraham Lincoln",
    "Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield ","Grover Cleveland","Herbert Hoover","Calvin Coolidge","Franklin D. Roosevelt","Harry S. Truman",
    "Dwight D. Eisenhower","John F. Kennedy","Richard Nixon","Jimmy Carter","Ronald Reagan","Bill Clinton","George W. Bush","Lyndon B. Johnson"]

    livesRemaining = 3

    print("Nice to meet you", userName,)
    print("Today you'll be taking a quiz on which U.S President served first out of three options!")
    print("You'll have only three chances to mess up! Let's get started!")
    print("Choose either number 1 2 or 3 on your keyboard!")
    print(random.choice(presidents)); print(random.choice(presidents)); print(random.choice(presidents))

    response = input()

    if response == "1":
        print("Correct! 1/10!")
    else:
        livesRemaining -= 1
        print("Incorrect!")
        lifeCount() ```
</code>```

Body:
Basically I'm doing a multiple choice question president quiz on who served before the others in said multiple choice question. I've gotten it down fully looped with out the randomness but now I've incorporated arrays and random questions, basically I need to figure out how to make multiple choice questions and then define the logic so that when a person inputs 1,2, or 3 the game will look at all three listed options and know which one is the lowest on the presidents list to identify the correct answer.

lives = True
import array
import random

print("Welcome to Ahmed's U.S Presidential Quiz!")
print("Please enter your name!")
userName = input()

def answer():
if response == presidents

def lifeCount():

    if livesRemaining == 0:
        print("You're out of lives! Good luck trying again!")
        quit()

    if livesRemaining == 0:
            quit()

while lives:

    presidents = ["George Washington","John Adams","Thomas Jefferson","James Maddison","James Monroe","John Quincy Adams",
    "Andrew Jackson","Martin Van Buren","William Henry Harrison","James K. Polk","Zachary Taylor","Franklin Pierce","James Buchanan","Abraham Lincoln",
    "Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield ","Grover Cleveland","Herbert Hoover","Calvin Coolidge","Franklin D. Roosevelt","Harry S. Truman",
    "Dwight D. Eisenhower","John F. Kennedy","Richard Nixon","Jimmy Carter","Ronald Reagan","Bill Clinton","George W. Bush","Lyndon B. Johnson"]

    livesRemaining = 3

    print("Nice to meet you", userName,)
    print("Today you'll be taking a quiz on which U.S President served first out of three options!")
    print("You'll have only three chances to mess up! Let's get started!")
    print("Choose either number 1 2 or 3 on your keyboard!")
    print(random.choice(presidents)); print(random.choice(presidents)); print(random.choice(presidents))

    response = input()

    if response == "1":
        print("Correct! 1/10!")
    else:
        livesRemaining -= 1
        print("Incorrect!")
        lifeCount() ```


问:
why my JobService is not working in some devices?
i'm creating and app which notify the user in some specific period of time, i used JobService to let it working automatically and with the app closed, my problem is... there are some devices that my Job simply does not start, i dont know what is happing, because in my cellphone it works nice, but in some of my friends' devices, it doesn't.

I'm sending my JobService's class

```<code>package com.medicina.mednews;

public class JobServiceNotification extends JobService {
    private static final String TAG = "JobServiceNotification ";
    private boolean jobCancelled = false;
    String android_id;
    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference reference, refJob;

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "Job started");
        doBackgroundWork(params);

        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                        Settings.Secure.ANDROID_ID);
                reference= db.getReference().child("Usuarios").child(android_id).child("NoticiasDoPython");
                refJob = db.getReference().child("Usuarios").child(android_id).child("JobServiceFinished");

                reference.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                    }

                    @Override
                    public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                    }

                    @Override
                    public void onChildRemoved(@NonNull DataSnapshot snapshot) {
                        PrincipalModel principalModell3=snapshot.getValue(PrincipalModel.class);
                        Log.i("G3",""+principalModell3);
                        Log.i("GT",snapshot.getKey());
                        String aa = principalModell3.getData();
                        String[] aaS = aa.split(" ");
                        String idNotification = aaS[4];
                        idNotification = idNotification.replace(":","");
                        Log.i("IdNotification",idNotification);

                        addNotification(principalModell3.getTitulo(),principalModell3.getDescrição(),idNotification);
                    }

                    @Override
                    public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
                for (int i = 0; i < 10; i++) {
                   copyFirebaseData();
                   Log.i("Execução","Executei = "+i);
                    if (jobCancelled) {
                        return;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "Job finished");
                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = new Date();
                Date currentTime = Calendar.getInstance().getTime();
                refJob.child(dateFormat.format(date)).setValue(""+currentTime);
                jobFinished(params, false);

            }
        }).start();
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");

        jobCancelled = true;
        return true;
    }

    public void copyFirebaseData() {
        android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);

        DatabaseReference questionNodes = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(android_id).child("NoticiasDoPython");
        final DatabaseReference toUsersQuestions = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(android_id).child("NoticiasMovidasPeloAndroid");

        questionNodes.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
                    String KeyChild = questionCode.getKey();
                  Log.i("KEYYY",KeyChild);
                    String DateAntiga = questionCode.child("Data").getValue(String.class);
                    String DescricaoAntiga = questionCode.child("Descrição").getValue(String.class);
                    String TituloAntiga = questionCode.child("Titulo").getValue(String.class);
                    String LinkAntiga = questionCode.child("Link").getValue(String.class);
                    String ImagemAntiga = questionCode.child("Imagem").getValue(String.class);
                    String Id = questionCode.child("IdNoticia").getValue(String.class);

                    toUsersQuestions.child(KeyChild).child("Id").setValue(Id);
                    toUsersQuestions.child(KeyChild).child("Imagem").setValue(ImagemAntiga);
                    toUsersQuestions.child(KeyChild).child("Data").setValue(DateAntiga);
                    toUsersQuestions.child(KeyChild).child("Descrição").setValue(DescricaoAntiga);
                    toUsersQuestions.child(KeyChild).child("Link").setValue(LinkAntiga);
                    toUsersQuestions.child(KeyChild).child("Titulo").setValue(TituloAntiga);

                    questionNodes.child(KeyChild).removeValue();

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void addNotification(String titleNot,String DescriptNot, String idNotification) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("default", "Channel name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel description");
            notificationManager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
                .setSmallIcon(R.drawable.ic_baseline_nuvem_deletar)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentTitle(titleNot)
                .setPriority(Notification.PRIORITY_HIGH)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(DescriptNot))

                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setContentText(DescriptNot);
        builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //ESTAMOS DEFININDO UM ID ALEATÓRIO PARA GERAR MÚLTIPLAS NOTIFICAÇÕES
        Calendar cal = Calendar.getInstance();
        long millisecondOfDay =
                TimeUnit.HOURS.toMillis(cal.get(Calendar.HOUR_OF_DAY)) +
                        TimeUnit.MINUTES.toMillis(cal.get(Calendar.MINUTE)) +
                        TimeUnit.SECONDS.toMillis(cal.get(Calendar.SECOND)) +
                        cal.get(Calendar.MILLISECOND);

        manager.notify(Integer.parseInt(idNotification), builder.build()); //IREMOS DEFINIR UM ID COM UUID, MAS DEPOIS TEREMOS QUE MUDAR POIS ISSO NÃO ESTÁ CERTO !!! POSSIVELMENTE TEREMOS QUE IR PRO JSON
        //ESTAMOS DEFININDO UM ID ALEATÓRIO PARA GERAR MÚLTIPLAS NOTIFICAÇÕES
    }
}
</code>```

Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.QUICKBOOT_POWERON" />

    <application
        android:name=".FirebaseHandler"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/Theme.Mednews"
        tools:targetApi="31">

        <receiver
            android:name=".StartReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>

        <service
            android:name=".JobServiceNotification"
            android:permission="android.permission.BIND_JOB_SERVICE" />

        <activity
            android:name=".MedMenu.activity.MainActivity"
            android:exported="true"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
    </application>

</manifest>
</code>```

I tried to use the normal JobService class, but it simply doesn't work in some specific devices, the result is that my notifications don't start

Body:
i'm creating and app which notify the user in some specific period of time, i used JobService to let it working automatically and with the app closed, my problem is... there are some devices that my Job simply does not start, i dont know what is happing, because in my cellphone it works nice, but in some of my friends' devices, it doesn't.

I'm sending my JobService's class

package com.medicina.mednews;

public class JobServiceNotification extends JobService {
    private static final String TAG = "JobServiceNotification ";
    private boolean jobCancelled = false;
    String android_id;
    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference reference, refJob;

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "Job started");
        doBackgroundWork(params);

        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                        Settings.Secure.ANDROID_ID);
                reference= db.getReference().child("Usuarios").child(android_id).child("NoticiasDoPython");
                refJob = db.getReference().child("Usuarios").child(android_id).child("JobServiceFinished");

                reference.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                    }

                    @Override
                    public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                    }

                    @Override
                    public void onChildRemoved(@NonNull DataSnapshot snapshot) {
                        PrincipalModel principalModell3=snapshot.getValue(PrincipalModel.class);
                        Log.i("G3",""+principalModell3);
                        Log.i("GT",snapshot.getKey());
                        String aa = principalModell3.getData();
                        String[] aaS = aa.split(" ");
                        String idNotification = aaS[4];
                        idNotification = idNotification.replace(":","");
                        Log.i("IdNotification",idNotification);

                        addNotification(principalModell3.getTitulo(),principalModell3.getDescrição(),idNotification);
                    }

                    @Override
                    public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
                for (int i = 0; i < 10; i++) {
                   copyFirebaseData();
                   Log.i("Execução","Executei = "+i);
                    if (jobCancelled) {
                        return;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "Job finished");
                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = new Date();
                Date currentTime = Calendar.getInstance().getTime();
                refJob.child(dateFormat.format(date)).setValue(""+currentTime);
                jobFinished(params, false);

            }
        }).start();
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");

        jobCancelled = true;
        return true;
    }

    public void copyFirebaseData() {
        android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);

        DatabaseReference questionNodes = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(android_id).child("NoticiasDoPython");
        final DatabaseReference toUsersQuestions = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(android_id).child("NoticiasMovidasPeloAndroid");

        questionNodes.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
                    String KeyChild = questionCode.getKey();
                  Log.i("KEYYY",KeyChild);
                    String DateAntiga = questionCode.child("Data").getValue(String.class);
                    String DescricaoAntiga = questionCode.child("Descrição").getValue(String.class);
                    String TituloAntiga = questionCode.child("Titulo").getValue(String.class);
                    String LinkAntiga = questionCode.child("Link").getValue(String.class);
                    String ImagemAntiga = questionCode.child("Imagem").getValue(String.class);
                    String Id = questionCode.child("IdNoticia").getValue(String.class);

                    toUsersQuestions.child(KeyChild).child("Id").setValue(Id);
                    toUsersQuestions.child(KeyChild).child("Imagem").setValue(ImagemAntiga);
                    toUsersQuestions.child(KeyChild).child("Data").setValue(DateAntiga);
                    toUsersQuestions.child(KeyChild).child("Descrição").setValue(DescricaoAntiga);
                    toUsersQuestions.child(KeyChild).child("Link").setValue(LinkAntiga);
                    toUsersQuestions.child(KeyChild).child("Titulo").setValue(TituloAntiga);

                    questionNodes.child(KeyChild).removeValue();

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void addNotification(String titleNot,String DescriptNot, String idNotification) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("default", "Channel name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel description");
            notificationManager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
                .setSmallIcon(R.drawable.ic_baseline_nuvem_deletar)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentTitle(titleNot)
                .setPriority(Notification.PRIORITY_HIGH)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(DescriptNot))

                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setContentText(DescriptNot);
        builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //ESTAMOS DEFININDO UM ID ALEATÓRIO PARA GERAR MÚLTIPLAS NOTIFICAÇÕES
        Calendar cal = Calendar.getInstance();
        long millisecondOfDay =
                TimeUnit.HOURS.toMillis(cal.get(Calendar.HOUR_OF_DAY)) +
                        TimeUnit.MINUTES.toMillis(cal.get(Calendar.MINUTE)) +
                        TimeUnit.SECONDS.toMillis(cal.get(Calendar.SECOND)) +
                        cal.get(Calendar.MILLISECOND);

        manager.notify(Integer.parseInt(idNotification), builder.build()); //IREMOS DEFINIR UM ID COM UUID, MAS DEPOIS TEREMOS QUE MUDAR POIS ISSO NÃO ESTÁ CERTO !!! POSSIVELMENTE TEREMOS QUE IR PRO JSON
        //ESTAMOS DEFININDO UM ID ALEATÓRIO PARA GERAR MÚLTIPLAS NOTIFICAÇÕES
    }
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.QUICKBOOT_POWERON" />

    <application
        android:name=".FirebaseHandler"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/Theme.Mednews"
        tools:targetApi="31">

        <receiver
            android:name=".StartReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>

        <service
            android:name=".JobServiceNotification"
            android:permission="android.permission.BIND_JOB_SERVICE" />

        <activity
            android:name=".MedMenu.activity.MainActivity"
            android:exported="true"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
    </application>

</manifest>

I tried to use the normal JobService class, but it simply doesn't work in some specific devices, the result is that my notifications don't start


问:
Isotope JS Range Slider with grid-item attr min-max
I'm using the Isotope.js jquery library. I can't modify it to my needs, I need help.

https://codepen.io/lifeonlars/pen/yaaOey

```<code>// External js: jquery, isotope.pkgd.js, bootstrap.min.js, bootstrap-slider.js
$(document).ready( function() {

  // Create object to store filter for each group
  var buttonFilters = {};
  var buttonFilter = '*';
  // Create new object for the range filters and set default values,
  // The default values should correspond to the default values from the slider
  var rangeFilters = {
      'height': {'min':150, 'max': 185},
      'weight': {'min':50, 'max': 90}
    };

  // Initialise Isotope
  // Set the item selector
  var $grid = $('.grid').isotope({
    itemSelector: '.item',
    layout: 'masonry',
    // use filter function
    filter: function() {
      var $this = $(this);
      var height = $this.attr('data-height');
      var weight = $this.attr('data-weight');
      var isInHeightRange = (rangeFilters['height'].min <= height && rangeFilters['height'].max >= height);
      var isInWeightRange = (rangeFilters['weight'].min <= weight && rangeFilters['weight'].max >= weight);
      //console.log(rangeFilters['height']);
      //console.log(rangeFilters['weight']);
      // Debug to check whether an item is within the height weight range
      //console.log('isInHeightRange:' +isInHeightRange + '\nisInWeightRange: ' + isInWeightRange );
      return $this.is( buttonFilter ) && (isInHeightRange && isInWeightRange);
    }
  });

  // Initialise Sliders
  // Set min/max range on sliders as well as default values
  var $heightSlider = $('#filter-height').slider({ tooltip_split: true, min: 130,  max: 220, range: true, value: [150, 180] });
  var $weightSlider = $('#filter-weight').slider({ tooltip_split: true, min: 40,  max: 150, range: true, value: [50, 90] });

  function updateRangeSlider(slider, slideEvt) {
    console.log('Current slider:' + slider);
    var sldmin = +slideEvt.value[0],
        sldmax = +slideEvt.value[1],
        // Find which filter group this slider is in (in this case it will be either height or weight)
        // This can be changed by modifying the data-filter-group="age" attribute on the slider HTML
        filterGroup = slider.attr('data-filter-group'),
        // Set current selection in variable that can be pass to the label
        currentSelection = sldmin + ' - ' + sldmax;

      // Update filter label with new range selection
      slider.siblings('.filter-label').find('.filter-selection').text(currentSelection);

      // Set min and max values for current selection to current selection
      // If no values are found set min to 0 and max to 100000
      // Store min/max values in rangeFilters array in the relevant filter group
      // E.g. rangeFilters['height'].min and rangeFilters['height'].max
      console.log('Filtergroup: '+ filterGroup);
      rangeFilters[filterGroup] = {
        min: sldmin || 0,
        max: sldmax || 100000
      };
      // Trigger isotope again to refresh layout
      $grid.isotope();

  }

  // Trigger Isotope Filter when slider drag has stopped
  $heightSlider.on('slideStop', function(slideEvt){
    var $this =$(this);
    updateRangeSlider($this, slideEvt);
  });
  $weightSlider.on('slideStop', function(slideEvt){
    var $this =$(this);
    updateRangeSlider($this, slideEvt);
  });

  // Look inside element with .filters class for any clicks on elements with .btn
  $('.filters').on( 'click', '.btn', function() {
    var $this = $(this);
    // Get group key from parent btn-group (e.g. data-filter-group="color")
    var $buttonGroup = $this.parents('.btn-group');
    var filterGroup = $buttonGroup.attr('data-filter-group');
    // set filter for group
    buttonFilters[ filterGroup ] = $this.attr('data-filter');
    // Combine filters or set the value to * if buttonFilters
    buttonFilter = concatValues( buttonFilters ) || '*';
    // Log out current filter to check that it's working when clicked
    console.log( buttonFilter )
    // Trigger isotope again to refresh layout
    $grid.isotope();
  });

  // change is-checked class on btn-filter to toggle which one is active
  $('.btn-group').each( function( i, buttonGroup ) {
      var $buttonGroup = $( buttonGroup );
      $buttonGroup.on( 'click', '.btn-filter', function() {
          $buttonGroup.find('.is-checked').removeClass('is-checked');
          $(this).addClass('is-checked');
      });
  });

});

// Flatten object by concatting values
function concatValues( obj ) {
  var value = '';
  for ( var prop in obj ) {
    value += obj[ prop ];
  }
  return value;
}

</code>```

Here is good code written for filtering with Bootstrap Slider.

Let's take for example attr data-weight="" .

There is only one value specified here. And range filters by it. I need to write min-data-weight or max-data-weight to each item and then filter between those values.

Or maybe there is another library that can do this?

This is needed for Wordpress Woocommece price.

I tried to add conditions that would count between min and max. But it did not work. That's why I'm writing here.

Body:
I'm using the Isotope.js jquery library. I can't modify it to my needs, I need help.

https://codepen.io/lifeonlars/pen/yaaOey

// External js: jquery, isotope.pkgd.js, bootstrap.min.js, bootstrap-slider.js
$(document).ready( function() {

  // Create object to store filter for each group
  var buttonFilters = {};
  var buttonFilter = '*';
  // Create new object for the range filters and set default values,
  // The default values should correspond to the default values from the slider
  var rangeFilters = {
      'height': {'min':150, 'max': 185},
      'weight': {'min':50, 'max': 90}
    };

  // Initialise Isotope
  // Set the item selector
  var $grid = $('.grid').isotope({
    itemSelector: '.item',
    layout: 'masonry',
    // use filter function
    filter: function() {
      var $this = $(this);
      var height = $this.attr('data-height');
      var weight = $this.attr('data-weight');
      var isInHeightRange = (rangeFilters['height'].min <= height && rangeFilters['height'].max >= height);
      var isInWeightRange = (rangeFilters['weight'].min <= weight && rangeFilters['weight'].max >= weight);
      //console.log(rangeFilters['height']);
      //console.log(rangeFilters['weight']);
      // Debug to check whether an item is within the height weight range
      //console.log('isInHeightRange:' +isInHeightRange + '\nisInWeightRange: ' + isInWeightRange );
      return $this.is( buttonFilter ) && (isInHeightRange && isInWeightRange);
    }
  });

  // Initialise Sliders
  // Set min/max range on sliders as well as default values
  var $heightSlider = $('#filter-height').slider({ tooltip_split: true, min: 130,  max: 220, range: true, value: [150, 180] });
  var $weightSlider = $('#filter-weight').slider({ tooltip_split: true, min: 40,  max: 150, range: true, value: [50, 90] });

  function updateRangeSlider(slider, slideEvt) {
    console.log('Current slider:' + slider);
    var sldmin = +slideEvt.value[0],
        sldmax = +slideEvt.value[1],
        // Find which filter group this slider is in (in this case it will be either height or weight)
        // This can be changed by modifying the data-filter-group="age" attribute on the slider HTML
        filterGroup = slider.attr('data-filter-group'),
        // Set current selection in variable that can be pass to the label
        currentSelection = sldmin + ' - ' + sldmax;

      // Update filter label with new range selection
      slider.siblings('.filter-label').find('.filter-selection').text(currentSelection);

      // Set min and max values for current selection to current selection
      // If no values are found set min to 0 and max to 100000
      // Store min/max values in rangeFilters array in the relevant filter group
      // E.g. rangeFilters['height'].min and rangeFilters['height'].max
      console.log('Filtergroup: '+ filterGroup);
      rangeFilters[filterGroup] = {
        min: sldmin || 0,
        max: sldmax || 100000
      };
      // Trigger isotope again to refresh layout
      $grid.isotope();

  }

  // Trigger Isotope Filter when slider drag has stopped
  $heightSlider.on('slideStop', function(slideEvt){
    var $this =$(this);
    updateRangeSlider($this, slideEvt);
  });
  $weightSlider.on('slideStop', function(slideEvt){
    var $this =$(this);
    updateRangeSlider($this, slideEvt);
  });

  // Look inside element with .filters class for any clicks on elements with .btn
  $('.filters').on( 'click', '.btn', function() {
    var $this = $(this);
    // Get group key from parent btn-group (e.g. data-filter-group="color")
    var $buttonGroup = $this.parents('.btn-group');
    var filterGroup = $buttonGroup.attr('data-filter-group');
    // set filter for group
    buttonFilters[ filterGroup ] = $this.attr('data-filter');
    // Combine filters or set the value to * if buttonFilters
    buttonFilter = concatValues( buttonFilters ) || '*';
    // Log out current filter to check that it's working when clicked
    console.log( buttonFilter )
    // Trigger isotope again to refresh layout
    $grid.isotope();
  });

  // change is-checked class on btn-filter to toggle which one is active
  $('.btn-group').each( function( i, buttonGroup ) {
      var $buttonGroup = $( buttonGroup );
      $buttonGroup.on( 'click', '.btn-filter', function() {
          $buttonGroup.find('.is-checked').removeClass('is-checked');
          $(this).addClass('is-checked');
      });
  });

});

// Flatten object by concatting values
function concatValues( obj ) {
  var value = '';
  for ( var prop in obj ) {
    value += obj[ prop ];
  }
  return value;
}

Here is good code written for filtering with Bootstrap Slider.

Let's take for example attr data-weight="" .

There is only one value specified here. And range filters by it. I need to write min-data-weight or max-data-weight to each item and then filter between those values.

Or maybe there is another library that can do this?

This is needed for Wordpress Woocommece price.

I tried to add conditions that would count between min and max. But it did not work. That's why I'm writing here.


问:
how to hide Server Version of Phusion Passenger(R) 6.0.10
I want to delete the "Phusion Passenger(R) 6.0.10" so it won't show in headers
How can I do it, please

thank you

X-Powered-By    Phusion Passenger(R) 6.0.10, cloud66


问:
Plotting Neural Network as a Function in 3D
I have a neural network that I am representing as the appropriate product/sum with activation functions

sigmoid(w3.T @ ReLU(w2.T @ ReLU(w1.T @ ReLU(x @ w0 + b1) + b2) + b3)).

The input vector x is a vector of two real numbers, and the output is one real number. I want to plot this neural network as a surface in R^3. To that end, I have defined

```<code>def fct(x,y):
  return neural_net([x,y])
</code>```

that takes in a vector in R^2 but outputs a real scalar value. But when I use the standard syntax for plotting in 3D with MatPlotLib (as follows)

```<code># Generate data for the surface plot
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = fct(X, Y)

# Create a figure and a 3D axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the surface
ax.plot_surface(X, Y, Z)

# Show the plot
plt.show()
</code>```

I get the following error

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 50 is different from 10)

I believe the error is in the fact that the more complicated function cannot handle the input X,Y.

Body:
I have a neural network that I am representing as the appropriate product/sum with activation functions

sigmoid(w3.T @ ReLU(w2.T @ ReLU(w1.T @ ReLU(x @ w0 + b1) + b2) + b3)).

The input vector x is a vector of two real numbers, and the output is one real number. I want to plot this neural network as a surface in R^3. To that end, I have defined

def fct(x,y):
  return neural_net([x,y])

that takes in a vector in R^2 but outputs a real scalar value. But when I use the standard syntax for plotting in 3D with MatPlotLib (as follows)

# Generate data for the surface plot
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = fct(X, Y)

# Create a figure and a 3D axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the surface
ax.plot_surface(X, Y, Z)

# Show the plot
plt.show()

I get the following error

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 50 is different from 10)

I believe the error is in the fact that the more complicated function cannot handle the input X,Y.


问:
Inquirer horizontal select
is it possible to display select prompt horizontally with Inquirer? I'd like to implement button bar with keyboard support (arrows).

```<code>[Yes] [No] [Abort]
</code>```

I reviewed all examples and source code of select package but I didn't found any trace of such a component.

Title: Inquirer horizontal select

Body:
is it possible to display select prompt horizontally with Inquirer? I'd like to implement button bar with keyboard support (arrows).

[Yes] [No] [Abort]

I reviewed all examples and source code of select package but I didn't found any trace of such a component.


问:
Mongoose transactions not rolling back
The following code create 2 documents in 2 different collections.  Unless I'm misunderstanding, 2 things aren't happening properly.  The saves are happening serially when I thought it should only happen after the transaction completes.  And nothing rolls back upon error.  I see the documents in mongo still.  What am I doing wrong?</p>
```<code>const session = await dbConn.startSession();
let issue;
 await dbConn.transaction(async () => {
                issue = await IssueModel.create([req.body], { session: session });
                await IssueHistoryModel.create([req.body], { session: session });
                console.log("test");
                throw new Error("oops");
            });
</code>```

Title: Mongoose transactions not rolling back

Body:
The following code create 2 documents in 2 different collections.  Unless I'm misunderstanding, 2 things aren't happening properly.  The saves are happening serially when I thought it should only happen after the transaction completes.  And nothing rolls back upon error.  I see the documents in mongo still.  What am I doing wrong?

const session = await dbConn.startSession();
let issue;
 await dbConn.transaction(async () => {
                issue = await IssueModel.create([req.body], { session: session });
                await IssueHistoryModel.create([req.body], { session: session });
                console.log("test");
                throw new Error("oops");
            });


问:
Component changes on page refresh
No matter what component I'm currently on if I hit the refresh button in the browser it forces the page back to AddPositionComponent. I navigate between pages using the menu component. If I'm on the active-trades/:asset page then when I hit refresh, I wanna still be on that page.

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AddPositionComponent } from './add-position/add-position.component';

import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
import { ViewPositionsComponent } from './view-positions/view-positions.component';
import { ViewTradesTableComponent } from './view-trades/view-trades.component';

const routes: Routes = [
    { path: 'add-stock-trade', component: AddPositionComponent },
    { path: 'add-crypto-trade', component: AddPositionComponent },
    {
        path: 'view-positions/:asset/:ticker',
        component: ViewPositionsComponent
    },
    { path: 'active-trades/:asset', component: ViewTradesTableComponent },
    {
        path: 'unauthorized',
        component: UnauthorizedComponent
    },
    {
        path: '',
        component: UnauthorizedComponent
    }
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            useHash: true
        })
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

Am I doing something wrong with the router-outlet? I appreciate any help!

app.component.html

```<code><app-header id="header"></app-header>
<app-menu id="menu"></app-menu>
<router-outlet id="routerOutlet"></router-outlet>
</code>```

Title: Component changes on page refresh

Body:
No matter what component I'm currently on if I hit the refresh button in the browser it forces the page back to AddPositionComponent. I navigate between pages using the menu component. If I'm on the active-trades/:asset page then when I hit refresh, I wanna still be on that page.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AddPositionComponent } from './add-position/add-position.component';

import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
import { ViewPositionsComponent } from './view-positions/view-positions.component';
import { ViewTradesTableComponent } from './view-trades/view-trades.component';

const routes: Routes = [
    { path: 'add-stock-trade', component: AddPositionComponent },
    { path: 'add-crypto-trade', component: AddPositionComponent },
    {
        path: 'view-positions/:asset/:ticker',
        component: ViewPositionsComponent
    },
    { path: 'active-trades/:asset', component: ViewTradesTableComponent },
    {
        path: 'unauthorized',
        component: UnauthorizedComponent
    },
    {
        path: '',
        component: UnauthorizedComponent
    }
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            useHash: true
        })
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {}

Am I doing something wrong with the router-outlet? I appreciate any help!

app.component.html

<app-header id="header"></app-header>
<app-menu id="menu"></app-menu>
<router-outlet id="routerOutlet"></router-outlet>


问:
Python/Excel: How to freeze the top line of a generated sheet (or sheets)
This isn't actually a question -- it's more of an FYI.  It took me a while to figure this out, since my searching with Google turned up bits and pieces (including some related questions here on StackOverflow), but no article or blurb gave me the whole answer all in one place.  I was finally able to figure it out by recording a macro in Excel and looking at its source code and combining what I found there with what I found on the web.

Anyway, the following code snippets show two helper functions, plus a sample main() type of function (which I always use, even in Perl and Python apps, since I have a C/C++/Java background).

The first helper method will auto-fit every used column on the given sheet.  Since the auto-fit logic depends on the data in the cells, as well as the font(s) in use, you shouldn't call this method until the entire sheet has been completely populated with your data.  Also, I'm pretty new to VBA, so I'm not so sure that this line:

```<code>        sheet.Cells(1, i).EntireColumn.AutoFit()
</code>```

is correct, but it does seem to work just fine.  If it's not entirely correct, maybe you can post a correction.

```<code>def autoFitSheet(sheet):
    """Auto-fits all the used columns on the given sheet.  Obviously, this
    method should only be called _after_ the sheet has been populated."""

    firstCol    = sheet.UsedRange.Column
    numCols     = sheet.UsedRange.Columns.Count

    for i in range(firstCol, (firstCol + numCols)):
        sheet.Cells(1, i).EntireColumn.AutoFit()
</code>```

The second helper is a "freeze the top line" method.  All it does is freeze the top line of the sheet that you pass it.  A side effect of this method is that the sheet becomes the active sheet in the spreadsheet, so you might need/want to activate some other sheet once all your sheets' top lines have been frozen.

```<code>def freezeTopLine(window, sheet):
    """Freezes the top line of the given sheet."""

    sheet.Activate()

    window.SplitColumn  = 0
    window.SplitRow     = 1
    window.FreezePanes  = True
</code>```

The last snippet is a sample main() function, which just shows how to call the two helper methods.  I'm actually using code very similar to this to populate a spreadsheet with mutliple tabs/sheets, and it works perfectly (on Windows 7 -- can't guarantee how well it will work on your system).

```<code>def main(...):
    #
    # (whatever...)
    #

    excel       = win32.gencache.EnsureDispatch('Excel.Application')
    workbook    = excel.Workbooks.Add()
    sheets      = workbook.Sheets
    window      = workbook.Windows(1)

    sheet1 = workbook.Worksheets('Sheet1')
    straddles.Name = 'My First Sheet'
    straddles.Tab.ColorIndex = 6 # yellow

    sheet2 = workbook.Worksheets('Sheet2')
    cashSummary.Name = 'Some Other Sheet'
    cashSummary.Tab.ColorIndex = 4 # bright green

    #
    # Populate sheets...
    #

    for sheet in sheets:
        autoFitSheet(sheet)
        freezeTopLine(sheet)

    #
    # (whatever...)
    #
</code>```

Like I said, it took me a while to figure this out, and I was hoping that maybe I could save someone some of the headache that I went through.  Good luck.

ContentLicense: CC BY-SA 3.0

Body:
This isn't actually a question -- it's more of an FYI.  It took me a while to figure this out, since my searching with Google turned up bits and pieces (including some related questions here on StackOverflow), but no article or blurb gave me the whole answer all in one place.  I was finally able to figure it out by recording a macro in Excel and looking at its source code and combining what I found there with what I found on the web.

Anyway, the following code snippets show two helper functions, plus a sample main() type of function (which I always use, even in Perl and Python apps, since I have a C/C++/Java background).

The first helper method will auto-fit every used column on the given sheet.  Since the auto-fit logic depends on the data in the cells, as well as the font(s) in use, you shouldn't call this method until the entire sheet has been completely populated with your data.  Also, I'm pretty new to VBA, so I'm not so sure that this line:

        sheet.Cells(1, i).EntireColumn.AutoFit()

is correct, but it does seem to work just fine.  If it's not entirely correct, maybe you can post a correction.

def autoFitSheet(sheet):
    """Auto-fits all the used columns on the given sheet.  Obviously, this
    method should only be called _after_ the sheet has been populated."""

    firstCol    = sheet.UsedRange.Column
    numCols     = sheet.UsedRange.Columns.Count

    for i in range(firstCol, (firstCol + numCols)):
        sheet.Cells(1, i).EntireColumn.AutoFit()

The second helper is a "freeze the top line" method.  All it does is freeze the top line of the sheet that you pass it.  A side effect of this method is that the sheet becomes the active sheet in the spreadsheet, so you might need/want to activate some other sheet once all your sheets' top lines have been frozen.

def freezeTopLine(window, sheet):
    """Freezes the top line of the given sheet."""

    sheet.Activate()

    window.SplitColumn  = 0
    window.SplitRow     = 1
    window.FreezePanes  = True

The last snippet is a sample main() function, which just shows how to call the two helper methods.  I'm actually using code very similar to this to populate a spreadsheet with mutliple tabs/sheets, and it works perfectly (on Windows 7 -- can't guarantee how well it will work on your system).

def main(...):
    #
    # (whatever...)
    #

    excel       = win32.gencache.EnsureDispatch('Excel.Application')
    workbook    = excel.Workbooks.Add()
    sheets      = workbook.Sheets
    window      = workbook.Windows(1)

    sheet1 = workbook.Worksheets('Sheet1')
    straddles.Name = 'My First Sheet'
    straddles.Tab.ColorIndex = 6 # yellow

    sheet2 = workbook.Worksheets('Sheet2')
    cashSummary.Name = 'Some Other Sheet'
    cashSummary.Tab.ColorIndex = 4 # bright green

    #
    # Populate sheets...
    #

    for sheet in sheets:
        autoFitSheet(sheet)
        freezeTopLine(sheet)

    #
    # (whatever...)
    #

Like I said, it took me a while to figure this out, and I was hoping that maybe I could save someone some of the headache that I went through.  Good luck.


问:
Webpack: the dependency (Select2 module) is loaded after the caller
I've created a webpack.config.js that seems to correctly understand Select2 as a dependency of my script but fails to load it before the usage inside my script (app.ts).

I've tried to add an import at the beginning of my script but it didn't work

```<code>import {Select2} from "select2";
import select2 from "select2";

app.ts:404 Uncaught TypeError: $(...).select2 is not a function
    at MyClass.CreateWikiArticleUi (app.ts:404:27)
    at Object.success (app.ts:393:25)
    at fire (jquery.js?7e265:3500:31)
    at Object.fireWith [as resolveWith] (jquery.js?7e265:3630:7)
    at done (jquery.js?7e265:9822:14)
    at XMLHttpRequest.<anonymous> (jquery.js?7e265:10083:9)
</code>```

Body:
I've created a webpack.config.js that seems to correctly understand Select2 as a dependency of my script but fails to load it before the usage inside my script (app.ts).

I've tried to add an import at the beginning of my script but it didn't work

import {Select2} from "select2";
import select2 from "select2";

app.ts:404 Uncaught TypeError: $(...).select2 is not a function
    at MyClass.CreateWikiArticleUi (app.ts:404:27)
    at Object.success (app.ts:393:25)
    at fire (jquery.js?7e265:3500:31)
    at Object.fireWith [as resolveWith] (jquery.js?7e265:3630:7)
    at done (jquery.js?7e265:9822:14)
    at XMLHttpRequest.<anonymous> (jquery.js?7e265:10083:9)


问:
ggiraph Hover "Misaligned" in Latest Version?
Since updating my packages, I've been getting strange behavior when hovering over lines created by geom_line_interactive(). Lines get the hover effect even when the mouse is far from the line, and sometimes the line won't get the hover effect when the mouse is directly over it. This seems to only be a problem for line geoms; bars, points, etc. work fine.

See example below:

```<code>library(tidyverse)
library(ggiraph)

df = tibble(
  x = rep(1:5, 4),
  y = c(1:5, (1:5)^2, 4,2,1,2,4, 5,7,8,7,5),
  group = as.character(sort(rep(1:4, 5))),
  color = as.character(sort(c(rep(1, 15), rep(2, 5))))
)

gg = ggplot(df, aes(x, y, color = color, group = group, data_id = group, tooltip = group))

girafe(ggobj = gg + geom_line_interactive() + geom_point_interactive()) # Causes a problem
girafe(ggobj = gg + geom_line_interactive()) # Still causes a problem
girafe(ggobj = gg + geom_point_interactive()) # No problem
</code>```

Version numbers:

tidyverse - 1.3.2 (includes ggplot2 - 3.4.0)

ggiraph - 0.8.5

R - 4.2.2

Body:
Since updating my packages, I've been getting strange behavior when hovering over lines created by geom_line_interactive(). Lines get the hover effect even when the mouse is far from the line, and sometimes the line won't get the hover effect when the mouse is directly over it. This seems to only be a problem for line geoms; bars, points, etc. work fine.

See example below:

library(tidyverse)
library(ggiraph)

df = tibble(
  x = rep(1:5, 4),
  y = c(1:5, (1:5)^2, 4,2,1,2,4, 5,7,8,7,5),
  group = as.character(sort(rep(1:4, 5))),
  color = as.character(sort(c(rep(1, 15), rep(2, 5))))
)

gg = ggplot(df, aes(x, y, color = color, group = group, data_id = group, tooltip = group))

girafe(ggobj = gg + geom_line_interactive() + geom_point_interactive()) # Causes a problem
girafe(ggobj = gg + geom_line_interactive()) # Still causes a problem
girafe(ggobj = gg + geom_point_interactive()) # No problem

Version numbers:

tidyverse - 1.3.2 (includes ggplot2 - 3.4.0)

ggiraph - 0.8.5

R - 4.2.2


问:
Java SocketException after trying to send and receive data on the same socket connection
I am working on a project in Java and I am trying to send an object from the client to the server and then waiting for a String response, but I get SocketException with the message "Socket is closed" on server at the line where I'm creating the DataOutputStream and SocketException with the message "Socket closed" on client at the line where I called the readUTF method.

Client error:

```<code>java.net.SocketException: Socket closed
    at java.base/sun.nio.ch.NioSocketImpl.ensureOpenAndConnected(NioSocketImpl.java:165)
    at java.base/sun.nio.ch.NioSocketImpl.beginRead(NioSocketImpl.java:231)
    at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:299)
    at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
    at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
    at java.base/java.net.Socket$SocketInputStream.read(Socket.java:976)
    at java.base/java.net.Socket$SocketInputStream.read(Socket.java:971)
    at java.base/java.io.DataInputStream.readUnsignedShort(DataInputStream.java:343)
    at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:595)
    at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:570)
    at client.Client.main(Client.java:26)
</code>```

Server error:

```<code>java.net.SocketException: Socket is closed
    at java.base/java.net.Socket.getOutputStream(Socket.java:1008)
    at server.Server.handleRequest(Server.java:83)
    at server.Server.run(Server.java:74)
    at server.Server.main(Server.java:63)
</code>```

Client code:

```<code>public class Client {
    public static void main(String[] args) {
        try {
            Socket soc = new Socket("localhost", 8080);

            ObjectOutputStream out = new ObjectOutputStream(soc.getOutputStream());
            DataInputStream in = new DataInputStream(soc.getInputStream());

            Planification p = new Planification(0, "Alex", "5070921647382", LocalDate.now(), 2, 1, LocalDate.of(2023, 1, 15), LocalTime.of(12, 0, 0));
            out.writeObject(p);
            out.flush();
            out.close();

            System.out.println(in.readUTF()); //ERROR HERE
            in.close();

            soc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Server code:

```<code>private void run() throws IOException, ExecutionException, InterruptedException {
    ServerSocket socket = new ServerSocket(8080);
    System.out.println("Server started on port 8080");
    while (true) {
        final Socket connection = socket.accept();
        this.handleRequest(connection);
        connection.close();
    }
}

private void handleRequest(Socket connection) throws IOException, ExecutionException, InterruptedException {
    Future<String> result = executorService.submit(new ServiceCallable(this.locationsRepository, this.paymentsRepository, this.planificationsRepository, this.treatmentsRepository, connection));
    String res = result.get();
    System.out.println(res);
    DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //ERROR HERE
    out.writeUTF(res);
    out.flush();
    out.close();
}
</code>```

Call method from the ServiceCallable class:

```<code>public synchronized String call() throws Exception {
    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

    Object object = objectInputStream.readObject();
    objectInputStream.close();

    ...
    Some verifications and return of the String message
    ...
}
</code>```

Any help is appreciated...

Edit:
I changed the handleRequest method so that I dont give the connection to ServiceCallable but instead give the object read and changed the call method too (because i dont have the connection anymore) and I still have the same errors.

```<code>private void handleRequest(Socket connection) throws ... {
    ObjectInputStream objectInputStream = new ObjectInputStream(connection.getInputStream());
    Object command = objectInputStream.readObject();
    objectInputStream.close();

    Future<String> result = executorService.submit(new ServiceCallable(command, ...));
    String res = result.get();
    System.out.println(res);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeUTF(res);
    out.flush();
    out.close();
}
</code>```
```<code>public synchronized String call() throws Exception {
    ...
    Some verifications and return of the String message
    ...
}
</code>```

Body:
I am working on a project in Java and I am trying to send an object from the client to the server and then waiting for a String response, but I get SocketException with the message "Socket is closed" on server at the line where I'm creating the DataOutputStream and SocketException with the message "Socket closed" on client at the line where I called the readUTF method.

Client error:

java.net.SocketException: Socket closed
    at java.base/sun.nio.ch.NioSocketImpl.ensureOpenAndConnected(NioSocketImpl.java:165)
    at java.base/sun.nio.ch.NioSocketImpl.beginRead(NioSocketImpl.java:231)
    at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:299)
    at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
    at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
    at java.base/java.net.Socket$SocketInputStream.read(Socket.java:976)
    at java.base/java.net.Socket$SocketInputStream.read(Socket.java:971)
    at java.base/java.io.DataInputStream.readUnsignedShort(DataInputStream.java:343)
    at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:595)
    at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:570)
    at client.Client.main(Client.java:26)

Server error:

java.net.SocketException: Socket is closed
    at java.base/java.net.Socket.getOutputStream(Socket.java:1008)
    at server.Server.handleRequest(Server.java:83)
    at server.Server.run(Server.java:74)
    at server.Server.main(Server.java:63)

Client code:

public class Client {
    public static void main(String[] args) {
        try {
            Socket soc = new Socket("localhost", 8080);

            ObjectOutputStream out = new ObjectOutputStream(soc.getOutputStream());
            DataInputStream in = new DataInputStream(soc.getInputStream());

            Planification p = new Planification(0, "Alex", "5070921647382", LocalDate.now(), 2, 1, LocalDate.of(2023, 1, 15), LocalTime.of(12, 0, 0));
            out.writeObject(p);
            out.flush();
            out.close();

            System.out.println(in.readUTF()); //ERROR HERE
            in.close();

            soc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server code:

private void run() throws IOException, ExecutionException, InterruptedException {
    ServerSocket socket = new ServerSocket(8080);
    System.out.println("Server started on port 8080");
    while (true) {
        final Socket connection = socket.accept();
        this.handleRequest(connection);
        connection.close();
    }
}

private void handleRequest(Socket connection) throws IOException, ExecutionException, InterruptedException {
    Future<String> result = executorService.submit(new ServiceCallable(this.locationsRepository, this.paymentsRepository, this.planificationsRepository, this.treatmentsRepository, connection));
    String res = result.get();
    System.out.println(res);
    DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //ERROR HERE
    out.writeUTF(res);
    out.flush();
    out.close();
}

Call method from the ServiceCallable class:

public synchronized String call() throws Exception {
    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

    Object object = objectInputStream.readObject();
    objectInputStream.close();

    ...
    Some verifications and return of the String message
    ...
}

Any help is appreciated...

Edit:
I changed the handleRequest method so that I dont give the connection to ServiceCallable but instead give the object read and changed the call method too (because i dont have the connection anymore) and I still have the same errors.

private void handleRequest(Socket connection) throws ... {
    ObjectInputStream objectInputStream = new ObjectInputStream(connection.getInputStream());
    Object command = objectInputStream.readObject();
    objectInputStream.close();

    Future<String> result = executorService.submit(new ServiceCallable(command, ...));
    String res = result.get();
    System.out.println(res);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeUTF(res);
    out.flush();
    out.close();
}

public synchronized String call() throws Exception {
    ...
    Some verifications and return of the String message
    ...
}


问:
Parallel for is less efficient than serial?
I´ve been working on a small project for my college, with C and Openmp. To make it short, when trying to parallelize a for loop using the #pragma omp parallel for constructor, it ends up being way slower than the serial version, just by adding that, is a parallel version of odd-even sort that works with an array of integers

I found it has something to do with the threads accessing the memory location of the whole array each time they compare numbers and updating its own copy of it on the cache memory. But I don´t know how to fix it, so rather than updating the whole array, they just check the exact location of the integers they are comparing, I´m kinda new using Openmp so idk if there´s a clause of constructor for this kind of situation.

```<code>//version without parallel for
void bubbleSortParalelo(int array[], int size) {
    int i,j,first;
    for (i = 0; i < size; i++){
        first = i % 2;
        for (j = first; j < size-1 ; j+= 2){
            if (array[j] > array[j+1]){
                int temp = array[j+1];
                array[j+1]=array[j];
                array[j]= temp;
            }
        }
    }
}

//Version with parallel for, takes longer somehow

void bubbleSortParalelo2(int array[], int size) {
    int i,j,first;
    for (i = 0; i < size; i++){
        first = i % 2;
        #pragma omp parallel for
        for (j = first; j < size-1 ; j+= 2){
            if (array[j] > array[j+1]){
                int temp = array[j+1];
                array[j+1]=array[j];
                array[j]= temp;

        }
    }
}
</code>```

I want to make the parallel version at least as efficient as the serial one, because right now it takes like 10 times more, becoming worse with the more threads I use.

Body:
I´ve been working on a small project for my college, with C and Openmp. To make it short, when trying to parallelize a for loop using the #pragma omp parallel for constructor, it ends up being way slower than the serial version, just by adding that, is a parallel version of odd-even sort that works with an array of integers

I found it has something to do with the threads accessing the memory location of the whole array each time they compare numbers and updating its own copy of it on the cache memory. But I don´t know how to fix it, so rather than updating the whole array, they just check the exact location of the integers they are comparing, I´m kinda new using Openmp so idk if there´s a clause of constructor for this kind of situation.

//version without parallel for
void bubbleSortParalelo(int array[], int size) {
    int i,j,first;
    for (i = 0; i < size; i++){
        first = i % 2;
        for (j = first; j < size-1 ; j+= 2){
            if (array[j] > array[j+1]){
                int temp = array[j+1];
                array[j+1]=array[j];
                array[j]= temp;
            }
        }
    }
}

//Version with parallel for, takes longer somehow

void bubbleSortParalelo2(int array[], int size) {
    int i,j,first;
    for (i = 0; i < size; i++){
        first = i % 2;
        #pragma omp parallel for
        for (j = first; j < size-1 ; j+= 2){
            if (array[j] > array[j+1]){
                int temp = array[j+1];
                array[j+1]=array[j];
                array[j]= temp;

        }
    }
}

I want to make the parallel version at least as efficient as the serial one, because right now it takes like 10 times more, becoming worse with the more threads I use.


问:
Find pixels with a combo of saturation and brightness over X and return the percentage of those in the total pixel count
I am trying to take an image and evaluate the total number of pixels that have a combination of saturation and brightness over a specific baseline in an image.  This formula works properly.

```<code>sqrt(s/255. * v/255.)
</code>```

A value of a medium red for example would be 0.5, where a totally saturated bright red would be 1.
Returning the saturation isn't enough for the type of metric I wish to collect.

I want to return a single percentage of those pixels over the baseline, versus the total pixels in the image.  I am a bit stuck trying to get this filter to work and to do the total calculation of the result versus the total pixels.

```<code>BASELINE = 0.8
pixels = hsv.reshape((hsv.shape[0] * hsv.shape[1], 3))
    for h,s,v in pixels:
      d[h] = sqrt(s/255. * v/255.)
      vibrant_px[h] = filter(lambda x: x > BASELINE, d)
</code>```

How to total vibrant_px versus total pixels that are over BASELINE?

For the most part this works, but getting the total results from the tuple is frustrating me.

Body:
I am trying to take an image and evaluate the total number of pixels that have a combination of saturation and brightness over a specific baseline in an image.  This formula works properly.

sqrt(s/255. * v/255.)

A value of a medium red for example would be 0.5, where a totally saturated bright red would be 1.
Returning the saturation isn't enough for the type of metric I wish to collect.

I want to return a single percentage of those pixels over the baseline, versus the total pixels in the image.  I am a bit stuck trying to get this filter to work and to do the total calculation of the result versus the total pixels.

BASELINE = 0.8
pixels = hsv.reshape((hsv.shape[0] * hsv.shape[1], 3))
    for h,s,v in pixels:
      d[h] = sqrt(s/255. * v/255.)
      vibrant_px[h] = filter(lambda x: x > BASELINE, d)

How to total vibrant_px versus total pixels that are over BASELINE?

For the most part this works, but getting the total results from the tuple is frustrating me.


问:
LocalStorage Clearing when trying to remove a single item
I'm having an issue with localStorage. Whenever the X (e.target.tagName === 'I') icon is clicked to remove one single item from localStorage, all of localStorage is cleared. What's going on? Any suggestions will be appreciated.

Javascript File

```<code>const todoInput = document.querySelector('#todo-item')
const todoList = document.querySelector('.todo-list')
const form = document.querySelector('form')
const todos = []
const savedTodos = JSON.parse(localStorage.getItem('todos')) || []

for (let i = 0; i < savedTodos.length; i++) {
  let newTodo = document.createElement('LI')
  newTodo.innerText = savedTodos[i]
  newTodo.classList.add('todo-item')
  const deleteBtn = document.createElement('I')
  deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
  newTodo.append(deleteBtn)
  todoList.appendChild(newTodo)
}

form.addEventListener('submit', function (e) {
  // e.preventDefault()
  const newTodo = document.createElement('li')
  newTodo.innerText = todoInput.value
  newTodo.classList.add('todo-item')
  const deleteBtn = document.createElement('i')
  deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
  newTodo.append(deleteBtn)
  todoList.appendChild(newTodo)

  todoInput.value = ''

  todos.push(newTodo.innerText)
  console.log(newTodo.innerText)

  localStorage.setItem('todos', JSON.stringify(todos))
})

function removeFromStorage(itemToRemove) {

  for (let i = 0; i < todos.length; i++) {
    if (todos[i] === itemToRemove) {
      todos.splice(i, 1)
    }
  }
  localStorage.setItem('todos', JSON.stringify(todos))
}

todoList.addEventListener('click', function (e) {
// When this line of code is run all local storage is deleted
  if (e.target.tagName === 'I') {
    e.target.parentElement.remove()
    removeFromStorage(e.target.parentElement.innerText)
  } else if (e.target.tagName === 'LI') {
    e.target.classList.toggle('todo-complete')
  }
  console.log(e.target.innerText)
})
</code>```

Body:
I'm having an issue with localStorage. Whenever the X (e.target.tagName === 'I') icon is clicked to remove one single item from localStorage, all of localStorage is cleared. What's going on? Any suggestions will be appreciated.

Javascript File

const todoInput = document.querySelector('#todo-item')
const todoList = document.querySelector('.todo-list')
const form = document.querySelector('form')
const todos = []
const savedTodos = JSON.parse(localStorage.getItem('todos')) || []

for (let i = 0; i < savedTodos.length; i++) {
  let newTodo = document.createElement('LI')
  newTodo.innerText = savedTodos[i]
  newTodo.classList.add('todo-item')
  const deleteBtn = document.createElement('I')
  deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
  newTodo.append(deleteBtn)
  todoList.appendChild(newTodo)
}

form.addEventListener('submit', function (e) {
  // e.preventDefault()
  const newTodo = document.createElement('li')
  newTodo.innerText = todoInput.value
  newTodo.classList.add('todo-item')
  const deleteBtn = document.createElement('i')
  deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
  newTodo.append(deleteBtn)
  todoList.appendChild(newTodo)

  todoInput.value = ''

  todos.push(newTodo.innerText)
  console.log(newTodo.innerText)

  localStorage.setItem('todos', JSON.stringify(todos))
})

function removeFromStorage(itemToRemove) {

  for (let i = 0; i < todos.length; i++) {
    if (todos[i] === itemToRemove) {
      todos.splice(i, 1)
    }
  }
  localStorage.setItem('todos', JSON.stringify(todos))
}

todoList.addEventListener('click', function (e) {
// When this line of code is run all local storage is deleted
  if (e.target.tagName === 'I') {
    e.target.parentElement.remove()
    removeFromStorage(e.target.parentElement.innerText)
  } else if (e.target.tagName === 'LI') {
    e.target.classList.toggle('todo-complete')
  }
  console.log(e.target.innerText)
})