问:
Python RGB to OneHot Function not working in Dataloader Generator
I am performing multiclass segmentation, and I am converting multi-class 'mask' images to a matrix of label values; the masks are made of regions with discrete pixel values, and so there are a countable number of classes present. (currently 4).

I created a test code that will essentially take a mask image (opened with PIL and converted to NumPy array), find out the pixel value of each pixel, match that pixel value to a corresponding label value in a dictionary, and output a 2-D array with each index corresponding to specific class from the given dictionary.

I got code working that does just that; I was able to load image using PIL's Image.open(imgpath) function, and convert image to array of label values; I was then also able to successfully convert the code back to rgb format by matching each label value with the corresponding pixel. So I was happy with that.

However, when I inserted this code into an actual training paradigm, it did not work. The output was an array of zeros, the array of zeros that is defined at the beginning of the function as a placeholder for future values.

The only difference between implementations here is that when the function failed to work, it was being called by the pytorch torch.utils.data.DataLoader function to feed the images in an appropriate manner to the machine learning model. But everything else is the same, in terms of image augmentation; this is why I am very confused as to why the function works when analyzing one image from file, versus using the Dataloader functions; in both cases, the image that is sent to the function is an opened PIL image that is converted to numpy array.

Difference in path flow between two functions:

Works:
FilePath -> Image.open -> Numpy array -> Function -> Output

Doesn't work:
torch.utils.data.Dataloader(fileFolder) -> image index -> Image.open -> Function -> bad output

Here is the working code: (rgb is the image, the color dict is a dictionary of pixel values corresponding to classes)

```<code>def rgbToOnehotNew(rgb, colorDict):
    dense = np.zeros(rgb.shape[:2])
    for label, color in enumerate(colorDict.keys()):
        if label < len(colorDict.keys()):
            dense[np.all(rgb == color, axis=-1)] = label
    return dense
</code>```

Here is the code that doesn't work (if you notice, its pretty much the exact same code; i just ensured dtype and size of pixels was correct):

```<code>def rgbToOnehotNew(rgb, colorDict):
    rgb = np.array(rgb).astype('uint8')
    if np.any(rgb) >= 1:
        rgb = rgb*255
    dense = np.zeros(rgb.shape[:2])

    for label, color in enumerate(colorDict.keys()):
        print(label, color)

        if label < len(colorDict.keys()):
            dense[np.all(rgb == color, axis=-1)] = label

    return dense
</code>```

However, this code does work in the function using the Dataloader:

```<code>def rgbToOnehotNew(rgb, colorDict):
    rgb = np.array(rgb).astype('uint8')
    if np.any(rgb) >= 1:
        rgb = rgb*255
    dense = np.zeros(rgb.shape[:2])
    for label, color in enumerate(colorDict.keys()):
        color = np.array(color)
        if label < len(colorDict.keys()):
            dense[np.all(rgb == color, axis=-1)] = label
            for _x, x in enumerate(rgb):
                for _y, y in enumerate(x):
                # print(rgb[_x][_y], color)
                    pixel = np.array(rgb[_x][_y])
                    if np.all(pixel == color):
                        dense[_x][_y] = label
    return dense
</code>```

But that code is at least 10x slower than the first code snippet. Would anyone have any suggestions?

Body:
I am performing multiclass segmentation, and I am converting multi-class 'mask' images to a matrix of label values; the masks are made of regions with discrete pixel values, and so there are a countable number of classes present. (currently 4).

I created a test code that will essentially take a mask image (opened with PIL and converted to NumPy array), find out the pixel value of each pixel, match that pixel value to a corresponding label value in a dictionary, and output a 2-D array with each index corresponding to specific class from the given dictionary.

I got code working that does just that; I was able to load image using PIL's Image.open(imgpath) function, and convert image to array of label values; I was then also able to successfully convert the code back to rgb format by matching each label value with the corresponding pixel. So I was happy with that.

However, when I inserted this code into an actual training paradigm, it did not work. The output was an array of zeros, the array of zeros that is defined at the beginning of the function as a placeholder for future values.

The only difference between implementations here is that when the function failed to work, it was being called by the pytorch torch.utils.data.DataLoader function to feed the images in an appropriate manner to the machine learning model. But everything else is the same, in terms of image augmentation; this is why I am very confused as to why the function works when analyzing one image from file, versus using the Dataloader functions; in both cases, the image that is sent to the function is an opened PIL image that is converted to numpy array.

Difference in path flow between two functions:

Works:
FilePath -> Image.open -> Numpy array -> Function -> Output

Doesn't work:
torch.utils.data.Dataloader(fileFolder) -> image index -> Image.open -> Function -> bad output

Here is the working code: (rgb is the image, the color dict is a dictionary of pixel values corresponding to classes)

def rgbToOnehotNew(rgb, colorDict):
    dense = np.zeros(rgb.shape[:2])
    for label, color in enumerate(colorDict.keys()):
        if label < len(colorDict.keys()):
            dense[np.all(rgb == color, axis=-1)] = label
    return dense

Here is the code that doesn't work (if you notice, its pretty much the exact same code; i just ensured dtype and size of pixels was correct):

def rgbToOnehotNew(rgb, colorDict):
    rgb = np.array(rgb).astype('uint8')
    if np.any(rgb) >= 1:
        rgb = rgb*255
    dense = np.zeros(rgb.shape[:2])

    for label, color in enumerate(colorDict.keys()):
        print(label, color)

        if label < len(colorDict.keys()):
            dense[np.all(rgb == color, axis=-1)] = label

    return dense

However, this code does work in the function using the Dataloader:

def rgbToOnehotNew(rgb, colorDict):
    rgb = np.array(rgb).astype('uint8')
    if np.any(rgb) >= 1:
        rgb = rgb*255
    dense = np.zeros(rgb.shape[:2])
    for label, color in enumerate(colorDict.keys()):
        color = np.array(color)
        if label < len(colorDict.keys()):
            dense[np.all(rgb == color, axis=-1)] = label
            for _x, x in enumerate(rgb):
                for _y, y in enumerate(x):
                # print(rgb[_x][_y], color)
                    pixel = np.array(rgb[_x][_y])
                    if np.all(pixel == color):
                        dense[_x][_y] = label
    return dense

But that code is at least 10x slower than the first code snippet. Would anyone have any suggestions?


来源: stackexchange

问:
Using Solr, how to configure a fieldType analyzer to see a numeric character then space then alpha characters together as a separate token?
I have created a field 'allsearchstr' that is copied from approximately 200 other fields. I would like the end user to be able to query that field with something like '2 ohm resistors' that would return all docs having a resistance of 2 ohms.

Sample content of the allsearchstr field for one document looks like the following:

```<code>"allsearchstr":\["Y",
"Thick Film",
"1",
"0402 RES 1/16W 2R0 5%",
"General Purpose",
"0.35",
"Solder Pads",
"63mW",
"SMT",
"Active",
"2 Ohm",
"RESISTORS",
"CHIP RESISTORS",
"PASSIVE",
"50V",
"Chip Technologies",
"5%",
"0402 (1005)",
"-55 to +155C",
"±200ppm",
"CR0402J2R0T1LF",
"0.5"\]

</code>```

The current fieldType is configured in the schema as:

```<code><fieldType name="utstring" class="solr.TextField" omitNorms="true" sortMissingLast="true"\>
  <analyzer\>
    <tokenizer class="solr.KeywordTokenizerFactory"/\>
    <filter class="solr.LowerCaseFilterFactory"/\>
  </analyzer\>
</fieldType\>

</code>```

This config sees '2 ohm resistors' as one token.

I have tried various tokenizers & filters but have not been successful in finding the correct combination. I keep ending up with tokens that either see the whole input as one token or tokenizes split on spaces.

I am using Solr 7.5.0 on Centos

Any assistance pointing me in the right direction would be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I have created a field 'allsearchstr' that is copied from approximately 200 other fields. I would like the end user to be able to query that field with something like '2 ohm resistors' that would return all docs having a resistance of 2 ohms.

Sample content of the allsearchstr field for one document looks like the following:

"allsearchstr":\["Y",
"Thick Film",
"1",
"0402 RES 1/16W 2R0 5%",
"General Purpose",
"0.35",
"Solder Pads",
"63mW",
"SMT",
"Active",
"2 Ohm",
"RESISTORS",
"CHIP RESISTORS",
"PASSIVE",
"50V",
"Chip Technologies",
"5%",
"0402 (1005)",
"-55 to +155C",
"±200ppm",
"CR0402J2R0T1LF",
"0.5"\]

The current fieldType is configured in the schema as:

<fieldType name="utstring" class="solr.TextField" omitNorms="true" sortMissingLast="true"\>
  <analyzer\>
    <tokenizer class="solr.KeywordTokenizerFactory"/\>
    <filter class="solr.LowerCaseFilterFactory"/\>
  </analyzer\>
</fieldType\>

This config sees '2 ohm resistors' as one token.

I have tried various tokenizers & filters but have not been successful in finding the correct combination. I keep ending up with tokens that either see the whole input as one token or tokenizes split on spaces.

I am using Solr 7.5.0 on Centos

Any assistance pointing me in the right direction would be appreciated.


问:
how to find postgresql syntax error at position (using eclipse)
I am using Postgres for sql within eclipse and i ran my code and it gave me an error

```<code>syntax error at end of input position 13
</code>```

however, I'm a bit confused as to find position 13 because I am using eclipse and I have written about 200 lines of code and I don't think it is line 13..

I don't know if I'm being stupid but I don't know how to find the error at the said position because I don't know how to find the position!

```<code>String query = "SELECT * FROM BRANCH";
    ResultSet rs = executeQuery(connection, query);
    try {

      while (rs.next()) {
        System.out.println("Column 1 returned");
        System.out.println(rs.getString(1));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
    rs.close();

    dropTable(connection, " delayedFlights");
    createTable(connection," delayedFlights( ID_of_Delayed_Flight int pr"
        + "imary key, month int, dayOfMonth int, dayOfWeek int, depTime int, scheduledDeptTime int, arrTime int, "
        + "scheduledArrTime int, uniqueCarrier varchar(5), flightNum int, actualFlightTime int, scheduledFlightTime int,"
        + "airTime int, arrDelay int, depDelay int, orig varchar(5), dest varchar(5), distance int);");
    int rows = insertIntoTableFromFile(connection, "delayedFlights", "src/delayedFlights.txt");
    System.out.println(rows + " rows inserted.");

    dropTable(connection, " airport");
    createTable(connection, " airport( airportCode int primary key, airportName varchar(20), city varchar(25),"
        + "state varchar(25));");
    int rows2 = insertIntoTableFromFile(connection, "airport", "src/airport.txt");
    System.out.println(rows2 + " rows inserted.");
</code>```

Body:
I am using Postgres for sql within eclipse and i ran my code and it gave me an error

syntax error at end of input position 13

however, I'm a bit confused as to find position 13 because I am using eclipse and I have written about 200 lines of code and I don't think it is line 13..

I don't know if I'm being stupid but I don't know how to find the error at the said position because I don't know how to find the position!

String query = "SELECT * FROM BRANCH";
    ResultSet rs = executeQuery(connection, query);
    try {

      while (rs.next()) {
        System.out.println("Column 1 returned");
        System.out.println(rs.getString(1));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
    rs.close();

    dropTable(connection, " delayedFlights");
    createTable(connection," delayedFlights( ID_of_Delayed_Flight int pr"
        + "imary key, month int, dayOfMonth int, dayOfWeek int, depTime int, scheduledDeptTime int, arrTime int, "
        + "scheduledArrTime int, uniqueCarrier varchar(5), flightNum int, actualFlightTime int, scheduledFlightTime int,"
        + "airTime int, arrDelay int, depDelay int, orig varchar(5), dest varchar(5), distance int);");
    int rows = insertIntoTableFromFile(connection, "delayedFlights", "src/delayedFlights.txt");
    System.out.println(rows + " rows inserted.");

    dropTable(connection, " airport");
    createTable(connection, " airport( airportCode int primary key, airportName varchar(20), city varchar(25),"
        + "state varchar(25));");
    int rows2 = insertIntoTableFromFile(connection, "airport", "src/airport.txt");
    System.out.println(rows2 + " rows inserted.");


问:
What is the best way of handling sessions on the server when using frontend Firebase Auth?
I'm creating a .NET MAUI app that uses Firebase Auth for its authentication. While the login itself is handled on the frontend, I'd like a way for the server to know if my user has an active session. The only way I've found is to send an ID token with every request and then verify if the user is logged in there, but that seems a bit clumsy.

Is there a better way to handle the session (for example, sending the token when the user logs in and then creating a session on the backend) or at least automatically send the ID token without having to manually include it in each post?

Thanks for any answers or help!


问:
Deleting a private GPG Key in Azure Cloud Shell
In Azure Cloud Shell I was able to create a GPG key.
Now I want to delete it...

```<code>gpg --delete-secret-key [ID-OF-KEY]
</code>```

Which results in...

```<code>Delete this key from the keyring? (y/N) y
This is a secret key! - really delete? (y/N) y
gpg: deleting secret key failed: Permission denied
gpg: deleting secret subkey failed: Permission denied
</code>```

I had permissions to create it. Why can't I delete it?

Body:
In Azure Cloud Shell I was able to create a GPG key.
Now I want to delete it...

gpg --delete-secret-key [ID-OF-KEY]

Which results in...

Delete this key from the keyring? (y/N) y
This is a secret key! - really delete? (y/N) y
gpg: deleting secret key failed: Permission denied
gpg: deleting secret subkey failed: Permission denied

I had permissions to create it. Why can't I delete it?


问:
Building pip package for multiple platforms
I have a project written in C++ with a binding for Python created with Swig. The use of the Python binding depends off of a shared library.

Using distutils I have successfully created a pip package for x86_64 linux (my host machine). Here is a stripped down version of my setup.py file

setuptools.setup(
    name='example',
    distclass=BinaryDistribution,
    version='0.0.1',
    author='moi',
    description='example Python API',
    keywords='example, pypi, package',
    long_description=long_description,
    long_description_content_type='text/markdown',
    #packages=[''],
    package_dir={'': 'Python'},
    packages=setuptools.find_packages(where='Python')
)
```

This generates a wheel named example-0.0.1-cp310-cp310-manylinux1_x86_64.whl.

What is the proper way to generate wheels for different platforms, for example allowing a package to be used for OSX as well as Linux based systems while only being in possession of one of the target machines.

I think the manylinux1_x86_64 tag is a big generalization, does this mean all linux based systems of x86_64 architecture can utilize this package? Ubuntu, Kali, Fedora?

Body:
I have a project written in C++ with a binding for Python created with Swig. The use of the Python binding depends off of a shared library.

Using distutils I have successfully created a pip package for x86_64 linux (my host machine). Here is a stripped down version of my setup.py file

setuptools.setup(
    name='example',
    distclass=BinaryDistribution,
    version='0.0.1',
    author='moi',
    description='example Python API',
    keywords='example, pypi, package',
    long_description=long_description,
    long_description_content_type='text/markdown',
    #packages=[''],
    package_dir={'': 'Python'},
    packages=setuptools.find_packages(where='Python')
)

This generates a wheel named example-0.0.1-cp310-cp310-manylinux1_x86_64.whl.

What is the proper way to generate wheels for different platforms, for example allowing a package to be used for OSX as well as Linux based systems while only being in possession of one of the target machines.

I think the manylinux1_x86_64 tag is a big generalization, does this mean all linux based systems of x86_64 architecture can utilize this package? Ubuntu, Kali, Fedora?


问:
Accessing the name of a class as a string in JavaScript when class was created using another constructor
I'm trying to print the name of a class that is being used to create a new object, but running into an issue because the class is a mongoose model that was created using mongoose.model():

```<code>const mongoose = require("mongoose");

const genreSchema = mongoose.Schema({ name: String });
const Genre = mongoose.model("Genre", genreSchema);

async function create(Model, modelInfo) {
  const instance = new Model(modelInfo);
  // Await some asynchronous work
  console.log(instance.constructor.name, "created: ", instance);
}

create(Genre, { name: "Thriller" });
</code>```

When doing console.log(instance.constructor.name), the result is model. I was hoping for Genre, but I'm guessing this happens because constructor in this case is referring to the constructor for the Genre class (prototype chaining I believe), which is model (mongoose.model()).

If I try console.log(Genre.constructor.name) the result is function (which I am guessing refers to the constructor of the mongoose.model()), and console.log(Genre.name) yields model as well. console.log(instance.name) of course yields Thriller.

Anybody know how I can get it to print out Genre?

Body:
I'm trying to print the name of a class that is being used to create a new object, but running into an issue because the class is a mongoose model that was created using mongoose.model():

const mongoose = require("mongoose");

const genreSchema = mongoose.Schema({ name: String });
const Genre = mongoose.model("Genre", genreSchema);

async function create(Model, modelInfo) {
  const instance = new Model(modelInfo);
  // Await some asynchronous work
  console.log(instance.constructor.name, "created: ", instance);
}

create(Genre, { name: "Thriller" });

When doing console.log(instance.constructor.name), the result is model. I was hoping for Genre, but I'm guessing this happens because constructor in this case is referring to the constructor for the Genre class (prototype chaining I believe), which is model (mongoose.model()).

If I try console.log(Genre.constructor.name) the result is function (which I am guessing refers to the constructor of the mongoose.model()), and console.log(Genre.name) yields model as well. console.log(instance.name) of course yields Thriller.

Anybody know how I can get it to print out Genre?


问:
In React MultiSelect, make at least one selection required using react-hook-form
I'm using the MultiSelect component from react-multi-select-component in a React 18 create-react-app application that uses Typescript:

```<code>import {MultiSelect} from 'react-multi-select-component';
</code>```

And I'm using react-hook-form to validate required fields on form submission:

```<code>import {useForm} from 'react-hook-form';
</code>```

I want to force the user to select at least one item from the MultiSelect. Can I do this using react-hook-form? I cannot find any example.

I have my MultiSelect inside a wrapper like so:

```<code>const MultiSelectWrapper = (props : MultiSelectType) => {
return (
    <MultiSelect
    options={props.options}
    value={props.value}
    onChange={props.onChange}
    disableSearch={props.disableSearch}
    labelledBy={props.labelledBy}
    className={props.className}
    defaultIsOpen={props.defaultIsOpen}
    />)
;
};
export default MultiSelectWrapper;
</code>```

And I'm rendering it inside the form tag like so:

```<code><MultiSelectWrapper disableSearch={true}
 labelledBy='Policy Types'
 value={policyTypes}
 options={policyTypeOptions}
 onChange={setPolicyTypes}
 className="w-72"
 defaultIsOpen={false}/>
</code>```

Getting validation to work for text and select inputs is very easy. For a text input, inside of a regular form tag, I just do this:

```<code><input
 {...register("title", {
      required : "Title is required",
      minLength: {
      value: 1,
      message: "Please enter at least one character for Title."
 }
 })}
 id="title" type="text"
 value={title}
 placeholder="Enter title here"
 className="rounded px-2 py-2 min-w-full"
 onChange={(e) => {setTitle(e.target.value);}} />
 <span className="text-red-600">
 {errors.title?.message}</span>
</code>```

Requiring the user to select an option from a select input it is equally trivial:

```<code><select>
{...register("formTypeId", {
    required : "Form Type is required",
    min: {
    value: 1,
    message: "Please select a Form Type."
  }
   })}
   className="px-3 py-3 rounded-full w-60"
    id="formTypeId"
  value={formTypeId}
  onChange={(e) => {
  e.preventDefault();
  setFormTypeId(parseInt(e.target.value));
  }}>
  <option value="0">--Select a Form Type--</option>
  {formTypesData.map((formType: FormTypeType) => <FormType key={formType.formTypeId} formTypeId={formType.formTypeId} description={formType.description}/>)}
  </select>
  <span className="text-red-600">{errors.formTypeId?.message}</span>
</code>```

Body:
I'm using the MultiSelect component from react-multi-select-component in a React 18 create-react-app application that uses Typescript:

import {MultiSelect} from 'react-multi-select-component';

And I'm using react-hook-form to validate required fields on form submission:

import {useForm} from 'react-hook-form';

I want to force the user to select at least one item from the MultiSelect. Can I do this using react-hook-form? I cannot find any example.

I have my MultiSelect inside a wrapper like so:

const MultiSelectWrapper = (props : MultiSelectType) => {
return (
    <MultiSelect
    options={props.options}
    value={props.value}
    onChange={props.onChange}
    disableSearch={props.disableSearch}
    labelledBy={props.labelledBy}
    className={props.className}
    defaultIsOpen={props.defaultIsOpen}
    />)
;
};
export default MultiSelectWrapper;

And I'm rendering it inside the form tag like so:

<MultiSelectWrapper disableSearch={true}
 labelledBy='Policy Types'
 value={policyTypes}
 options={policyTypeOptions}
 onChange={setPolicyTypes}
 className="w-72"
 defaultIsOpen={false}/>

Getting validation to work for text and select inputs is very easy. For a text input, inside of a regular form tag, I just do this:

<input
 {...register("title", {
      required : "Title is required",
      minLength: {
      value: 1,
      message: "Please enter at least one character for Title."
 }
 })}
 id="title" type="text"
 value={title}
 placeholder="Enter title here"
 className="rounded px-2 py-2 min-w-full"
 onChange={(e) => {setTitle(e.target.value);}} />

 {errors.title?.message}

Requiring the user to select an option from a select input it is equally trivial:

<select>
{...register("formTypeId", {
    required : "Form Type is required",
    min: {
    value: 1,
    message: "Please select a Form Type."
  }
   })}
   className="px-3 py-3 rounded-full w-60"
    id="formTypeId"
  value={formTypeId}
  onChange={(e) => {
  e.preventDefault();
  setFormTypeId(parseInt(e.target.value));
  }}>
  <option value="0">--Select a Form Type--</option>
  {formTypesData.map((formType: FormTypeType) => <FormType key={formType.formTypeId} formTypeId={formType.formTypeId} description={formType.description}/>)}
  </select>
  {errors.formTypeId?.message}


问:
RSpec - Rerun failed tests that are also tagged?
We have written a large number of selenium UI tests that very occasionally fail due to dumb reasons like a web server being too slow.  Additionally, we make heavy use of rspec tags to only run the tests that we want to run.   We want to retry ONLY the tests that are tagged with something AND that have previously failed.  In the following example, running rspec --tag all --only_failures runs the last two tests, when I only want it to run the 2nd test.

spec_helper.rb

```<code>RSpec.configure do |config|
  config.example_status_persistence_file_path = "RunResults.txt"
end
</code>```

test_spec.rb

```<code>require 'rspec'
require 'spec_helper'
require './test'

RSpec.describe Test do
    it "should pass", :all, :one do
        expect(1).to eql(1)
    end

    it "should fail", :all, :two do
        expect(1).to eql(2)
    end

    it "should fail", :three do
        expect(1).to eql(2)
    end
end
</code>```

RunResults.txt

```<code>example_id               | status | run_time        |
------------------------ | ------ | --------------- |
./spec/test_spec.rb[1:1] | passed | 0.00055 seconds |
./spec/test_spec.rb[1:2] | failed | 0.01796 seconds |
./spec/test_spec.rb[1:3] | failed | 0.00017 seconds |
</code>```

RSpec

```<code>$ rspec --tag all --only_failures
Run options: include {:all=>true, :last_run_status=>"failed"}
.FF

Failures:

  1) Test should fail
     Failure/Error: expect(1).to eql(2)

       expected: 2
            got: 1

       (compared using eql?)
     # ./spec/test_spec.rb:11:in `block (2 levels) in <top (required)>'

  2) Test should fail
     Failure/Error: expect(1).to eql(2)

       expected: 2
            got: 1

       (compared using eql?)
     # ./spec/test_spec.rb:15:in `block (2 levels) in <top (required)>'

Finished in 0.01949 seconds (files took 0.24733 seconds to load)
3 examples, 2 failures

Failed examples:

rspec ./spec/test_spec.rb:10 # Test should fail
rspec ./spec/test_spec.rb:14 # Test should fail
</code>```

Body:
We have written a large number of selenium UI tests that very occasionally fail due to dumb reasons like a web server being too slow.  Additionally, we make heavy use of rspec tags to only run the tests that we want to run.   We want to retry ONLY the tests that are tagged with something AND that have previously failed.  In the following example, running rspec --tag all --only_failures runs the last two tests, when I only want it to run the 2nd test.

spec_helper.rb

RSpec.configure do |config|
  config.example_status_persistence_file_path = "RunResults.txt"
end

test_spec.rb

require 'rspec'
require 'spec_helper'
require './test'

RSpec.describe Test do
    it "should pass", :all, :one do
        expect(1).to eql(1)
    end

    it "should fail", :all, :two do
        expect(1).to eql(2)
    end

    it "should fail", :three do
        expect(1).to eql(2)
    end
end

RunResults.txt

example_id               | status | run_time        |
------------------------ | ------ | --------------- |
./spec/test_spec.rb[1:1] | passed | 0.00055 seconds |
./spec/test_spec.rb[1:2] | failed | 0.01796 seconds |
./spec/test_spec.rb[1:3] | failed | 0.00017 seconds |

RSpec

$ rspec --tag all --only_failures
Run options: include {:all=>true, :last_run_status=>"failed"}
.FF

Failures:

  1) Test should fail
     Failure/Error: expect(1).to eql(2)

       expected: 2
            got: 1

       (compared using eql?)
     # ./spec/test_spec.rb:11:in `block (2 levels) in <top (required)>'

  2) Test should fail
     Failure/Error: expect(1).to eql(2)

       expected: 2
            got: 1

       (compared using eql?)
     # ./spec/test_spec.rb:15:in `block (2 levels) in <top (required)>'

Finished in 0.01949 seconds (files took 0.24733 seconds to load)
3 examples, 2 failures

Failed examples:

rspec ./spec/test_spec.rb:10 # Test should fail
rspec ./spec/test_spec.rb:14 # Test should fail


问:
SQLAlchemy hybrid property query self-reference parent attribute
I have to following Node model who has a ref_id FK that could point to itself, and accessing parents through the associated_refs attribute:

```<code>class Node(Base):

    class NodeStatus(enum.IntEnum):
        STATUS_1 = 0
        STATUS_2 = 1

    id = Column(Integer, primary_key=True)
    status = Column(Enum(NodeStatus))
    ref_id = Column(Integer, ForeignKey("Node.id", ondelete="SET NULL"))

    ref = relationship(
        "Node",
        foreign_keys=[ref_id],
        uselist=False,
        remote_side="Node.id",
        backref=backref("associated_refs")
    )

</code>```

I want to define a hybrid property by checking if for an instance its parents have the status STATUS_1:

```<code>class Node(Base):
    ...
    @hybrid_property
    def ref_is_status_1(self) -> bool:
        if self.associated_refs:
            return self.associated_refs[0].status == self.NodeStatus.STATUS_1
        else:
            return False

    @ref_is_status_1.expression
    def ref_is_status_1(cls):
        # Help here!
        pass
</code>```

But honestly, I don't know how to do it. Ideally, I would like to be able to query without having to query through SQLA's session.execute, which would make it so we can't write unit tests and hinder performance since we've got hundreds of thousands of nodes in the DB!

I tried using expressions with count so I could filter Nodes by those having a count  = 1 and by id but it always returns empty:

```<code>class Node(Base):
    ...

    @ref_is_status_1.expression
    def ref_is_status_1(cls):
        return select(func.count(Node.id)).where(
                     and_(
                         Node.ref_id == cls.id,
                         Node.status == Node.NodeStatus.STATUS_1
                     )).label("ref_is_status_1")
</code>```

I also tried this answer with a boolean case but it threw a ProgrammingError while due to a SELECT * statement without a table being specified:

```<code>class Node(Base):
    ...

    @ref_is_status_1.expression
    def ref_is_status_1(cls):
        return (
            select([
                case([(exists().where(
                    and_(
                        Node.ref_id == cls.id,
                        Node.status == Node.NodeStatus.STATUS_1
                    )).correlate(cls), True)],
                     else_=False
                     ).label("has_ref_is_status_1")
            ]).label("ref_is_status_1")
        )
</code>```

Body:
I have to following Node model who has a ref_id FK that could point to itself, and accessing parents through the associated_refs attribute:

class Node(Base):

    class NodeStatus(enum.IntEnum):
        STATUS_1 = 0
        STATUS_2 = 1

    id = Column(Integer, primary_key=True)
    status = Column(Enum(NodeStatus))
    ref_id = Column(Integer, ForeignKey("Node.id", ondelete="SET NULL"))

    ref = relationship(
        "Node",
        foreign_keys=[ref_id],
        uselist=False,
        remote_side="Node.id",
        backref=backref("associated_refs")
    )

I want to define a hybrid property by checking if for an instance its parents have the status STATUS_1:

class Node(Base):
    ...
    @hybrid_property
    def ref_is_status_1(self) -> bool:
        if self.associated_refs:
            return self.associated_refs[0].status == self.NodeStatus.STATUS_1
        else:
            return False

    @ref_is_status_1.expression
    def ref_is_status_1(cls):
        # Help here!
        pass

But honestly, I don't know how to do it. Ideally, I would like to be able to query without having to query through SQLA's session.execute, which would make it so we can't write unit tests and hinder performance since we've got hundreds of thousands of nodes in the DB!

I tried using expressions with count so I could filter Nodes by those having a count  = 1 and by id but it always returns empty:

class Node(Base):
    ...

    @ref_is_status_1.expression
    def ref_is_status_1(cls):
        return select(func.count(Node.id)).where(
                     and_(
                         Node.ref_id == cls.id,
                         Node.status == Node.NodeStatus.STATUS_1
                     )).label("ref_is_status_1")

I also tried this answer with a boolean case but it threw a ProgrammingError while due to a SELECT * statement without a table being specified:

class Node(Base):
    ...

    @ref_is_status_1.expression
    def ref_is_status_1(cls):
        return (
            select([
                case([(exists().where(
                    and_(
                        Node.ref_id == cls.id,
                        Node.status == Node.NodeStatus.STATUS_1
                    )).correlate(cls), True)],
                     else_=False
                     ).label("has_ref_is_status_1")
            ]).label("ref_is_status_1")
        )


问:
Call to Web Service with ESB Routing Itinerary Service contains no content
I have an Itinerary that  is called from a WCF Web Service (WCFService) through BizTalk. The first thing it does is a transformation, using Maps in WCFService. It then routes the response from the mapping to a Rest Service. I created WS-WebHttp adapter to be used with ESB.

The issue is that when it posts to the web service using HttpRequestMessage object, the message does not contain any content. As a test I also routed the transformation to passthough send port as a file and the transformation was correct.

My Itinerary

Here are the settings for the routing service
Routing Service Settings

The content-type is application/json.

I tested it using SOAPUI and it returned the content of the data going in.
Here is the Pipeline on the dynamic send port (request/response)

SendPipelineRequest

I believe I read that an ItinerarySelector is not used in the pipeline, because all the information is handled by the ItineraryCache.

I not sure where the issue is. I assume that the content from the transformation will be in the message passed on by the itinerary. Is there a way I can check this with itinerary before calling the service?

I appreciate the help.

UPDATE: No Content. I was doing a transformation through an itinerary service, instead of the pipeline. once I removed the transformation from the itinerary, and added the map to the incoming receive port, the Rest service receive the content, transformed.


问:
Using expo-notifications to produce a notification daily at a random time
Hi so I've been experimenting with the expo-notifications library all day and firstly it's really neat however I've run into a bit of an obstacle and that is scheduling a notification that repeats daily but at a random time and shows different data (e.g. fetch quote from an API)

To better explain think of how BeReal send their notifications... daily, random times. I'm tryna mimic that locally.

I can't figure out how to achieve this and would really appreciate some clarification on whether this is even possible.

I've created a basic custom hook to experiment:

```<code>import { View, Text, Platform } from "react-native";
import React, { useEffect, useState, useRef } from "react";
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
// import { useNavigation } from "@react-navigation/native";

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

export default function useNotifications() {
  const [expoPushToken, setExpoPushToken] = useState("");
  const [givenNotificationPerm, setGivenNotificationPerm] = useState(false);
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    // permissions(); - asks for permission
    givenPermissions(); // checks if has permissions
    getScheduled(); // get current notifications in pipeline

    Notifications.cancelAllScheduledNotificationsAsync();

    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
        console.log("--- notification received ---");
        // const show_time = notification?.request?.trigger?.dateComponents;
        // console.log(show_time);
        console.log(notification);
        console.log("------");
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log("--- notification tapped ---");
        const screen = response?.notification?.request?.content?.data?.screen;
        const show_time =
          response?.notification?.request?.content?.data?.show_time; // temp
        // navigation.navigate("Root", { screen: screen });
        console.log("this showed: " + show_time);
        console.log("------");
      });

    return () => {
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  async function permissions() {
    registerForPushNotificationsAsync().then((token) =>
      setExpoPushToken(token)
    );
  }

  async function getScheduled() {
    console.log("getting schedfuled notifcation");

    const slay = await Notifications.getAllScheduledNotificationsAsync();
    console.log("scheduled:");
    console.log(slay);
  }

  function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
  }

  async function schedulePushNotification() {
    console.log("reqested notifcation");
    const randomSeconds = getRandomIntInclusive(61, 75);

    const months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
    ];
    const random = Math.floor(Math.random() * months.length);

    Notifications.scheduleNotificationAsync({
      content: {
        title: `${months[random]} is random`,
        data: { screen: "screenName", show_time: randomSeconds },
      },
      trigger: {
        seconds: randomSeconds,
        repeats: true,
      },
    });
    await Notifications.cancelAllScheduledNotificationsAsync();
    getScheduled();
  }

  async function registerForPushNotificationsAsync() {
    let token;

    if (Platform.OS === "android") {
      await Notifications.setNotificationChannelAsync("default", {
        name: "default",
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: "#FF231F7C",
      });
    }

    if (Device.isDevice) {
      const { status: existingStatus } =
        await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;
      if (existingStatus !== "granted") {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }
      if (finalStatus !== "granted") {
        alert("Failed to get push token for push notification!");
        return;
      }
      token = (await Notifications.getExpoPushTokenAsync()).data;
      console.log(token);
    } else {
      alert("Must use physical device for Push Notifications");
    }

    return token;
  }

  async function givenPermissions() {
    if (Device.isDevice) {
      const { status: existingStatus } =
        await Notifications.getPermissionsAsync();
      if (existingStatus !== "granted") {
        setGivenNotificationPerm(false);
      }
      setGivenNotificationPerm(true);
    } else {
      alert("Must use physical device for Push Notifications");
    }
  }

  return {
    expoPushToken,
    notification,
    permissions,
    schedulePushNotification,
    givenNotificationPerm,
  };
}
</code>```

Pastebin code

And then for the App.js screen:

```<code>export default function App() {
  const { permissions, schedulePushNotification } = useNotifications();

  return(
    <>
    <Button title="Enable notifications - onboarding screen only button" onPress={permissions} />
    <Button title="Schedule notification" onPress={schedulePushNotification} />
    </>
  )
}
</code>```

Click the button multiple times, multiple notifications scheduled with random time and month for example purposes but how would i put this into practice to create an almost automation desire?

Right now my brain is thinking of just creating an array of 5 notifications and schedule them all in one go and then after X time has passed produce another 5 notifications but to do that i would have to ensure the user comes on the app within that timeframe to schedule more etc.

Bit stuck. Help appreciated

Thanks so much.

Body:
Hi so I've been experimenting with the expo-notifications library all day and firstly it's really neat however I've run into a bit of an obstacle and that is scheduling a notification that repeats daily but at a random time and shows different data (e.g. fetch quote from an API)

To better explain think of how BeReal send their notifications... daily, random times. I'm tryna mimic that locally.

I can't figure out how to achieve this and would really appreciate some clarification on whether this is even possible.

I've created a basic custom hook to experiment:

import { View, Text, Platform } from "react-native";
import React, { useEffect, useState, useRef } from "react";
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
// import { useNavigation } from "@react-navigation/native";

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

export default function useNotifications() {
  const [expoPushToken, setExpoPushToken] = useState("");
  const [givenNotificationPerm, setGivenNotificationPerm] = useState(false);
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    // permissions(); - asks for permission
    givenPermissions(); // checks if has permissions
    getScheduled(); // get current notifications in pipeline

    Notifications.cancelAllScheduledNotificationsAsync();

    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
        console.log("--- notification received ---");
        // const show_time = notification?.request?.trigger?.dateComponents;
        // console.log(show_time);
        console.log(notification);
        console.log("------");
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log("--- notification tapped ---");
        const screen = response?.notification?.request?.content?.data?.screen;
        const show_time =
          response?.notification?.request?.content?.data?.show_time; // temp
        // navigation.navigate("Root", { screen: screen });
        console.log("this showed: " + show_time);
        console.log("------");
      });

    return () => {
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  async function permissions() {
    registerForPushNotificationsAsync().then((token) =>
      setExpoPushToken(token)
    );
  }

  async function getScheduled() {
    console.log("getting schedfuled notifcation");

    const slay = await Notifications.getAllScheduledNotificationsAsync();
    console.log("scheduled:");
    console.log(slay);
  }

  function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
  }

  async function schedulePushNotification() {
    console.log("reqested notifcation");
    const randomSeconds = getRandomIntInclusive(61, 75);

    const months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
    ];
    const random = Math.floor(Math.random() * months.length);

    Notifications.scheduleNotificationAsync({
      content: {
        title: `${months[random]} is random`,
        data: { screen: "screenName", show_time: randomSeconds },
      },
      trigger: {
        seconds: randomSeconds,
        repeats: true,
      },
    });
    await Notifications.cancelAllScheduledNotificationsAsync();
    getScheduled();
  }

  async function registerForPushNotificationsAsync() {
    let token;

    if (Platform.OS === "android") {
      await Notifications.setNotificationChannelAsync("default", {
        name: "default",
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: "#FF231F7C",
      });
    }

    if (Device.isDevice) {
      const { status: existingStatus } =
        await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;
      if (existingStatus !== "granted") {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }
      if (finalStatus !== "granted") {
        alert("Failed to get push token for push notification!");
        return;
      }
      token = (await Notifications.getExpoPushTokenAsync()).data;
      console.log(token);
    } else {
      alert("Must use physical device for Push Notifications");
    }

    return token;
  }

  async function givenPermissions() {
    if (Device.isDevice) {
      const { status: existingStatus } =
        await Notifications.getPermissionsAsync();
      if (existingStatus !== "granted") {
        setGivenNotificationPerm(false);
      }
      setGivenNotificationPerm(true);
    } else {
      alert("Must use physical device for Push Notifications");
    }
  }

  return {
    expoPushToken,
    notification,
    permissions,
    schedulePushNotification,
    givenNotificationPerm,
  };
}

Pastebin code

And then for the App.js screen:

export default function App() {
  const { permissions, schedulePushNotification } = useNotifications();

  return(
    <>
    <Button title="Enable notifications - onboarding screen only button" onPress={permissions} />
    <Button title="Schedule notification" onPress={schedulePushNotification} />
    </>
  )
}

Click the button multiple times, multiple notifications scheduled with random time and month for example purposes but how would i put this into practice to create an almost automation desire?

Right now my brain is thinking of just creating an array of 5 notifications and schedule them all in one go and then after X time has passed produce another 5 notifications but to do that i would have to ensure the user comes on the app within that timeframe to schedule more etc.

Bit stuck. Help appreciated

Thanks so much.


问:
MongoDB save pre-defined aggregation pipeline in server itself, and pass some sort of input variables
I have a Python application (using pymongo) to run an aggregation pipeline on MongoDB server. The aggregation pipeline is quite large with around 18 stages and the final stage is a $merge -- so it doesn't return anything back to the Python client. Note that even though the pipeline is very large, it only accesses a few documents and it executes really fast.

From the Python client, I am calling this pipeline around a million times using multi-threading (with 32 threads). For each call, the only difference in the aggregation pipeline is in the first $match stage where the values of the fields change. In the sample code below, only parameters that change in each call in var-list1, var2, and var3.

```<code>pipeline = [
    {
        '$match': {
            'week': {'$in': <var-list1>},
            'eventCode': <var2>,
            'customer': <var3>
        }
    }, {
        ..... some long list of aggregation stages which is fixed...
    }, {
        '$merge': {
            'into': 'my_out_collection',
            'on': ['week', 'eventCode', 'customer'],
            'whenMatched': 'replace',
            'whenNotMatched': 'insert'
        }
    }
]
</code>```

My MongoDB server has the capacity to accept more parallel threads (based on disk and CPU usage metrics). However, I am not able to use this as my client's network-out traffic is hitting the ceiling. I suspect this is because the aggregation pipeline I am using is very big.

Does MongoDB support any ways of saving an aggregation pipeline in the server, with some placeholder variables, that can be executed by just passing in the variables?

MongoDB server version = 4.4

Pymongo = 3.10.1

Body:
I have a Python application (using pymongo) to run an aggregation pipeline on MongoDB server. The aggregation pipeline is quite large with around 18 stages and the final stage is a $merge -- so it doesn't return anything back to the Python client. Note that even though the pipeline is very large, it only accesses a few documents and it executes really fast.

From the Python client, I am calling this pipeline around a million times using multi-threading (with 32 threads). For each call, the only difference in the aggregation pipeline is in the first $match stage where the values of the fields change. In the sample code below, only parameters that change in each call in var-list1, var2, and var3.

pipeline = [
    {
        '$match': {
            'week': {'$in': <var-list1>},
            'eventCode': <var2>,
            'customer': <var3>
        }
    }, {
        ..... some long list of aggregation stages which is fixed...
    }, {
        '$merge': {
            'into': 'my_out_collection',
            'on': ['week', 'eventCode', 'customer'],
            'whenMatched': 'replace',
            'whenNotMatched': 'insert'
        }
    }
]

My MongoDB server has the capacity to accept more parallel threads (based on disk and CPU usage metrics). However, I am not able to use this as my client's network-out traffic is hitting the ceiling. I suspect this is because the aggregation pipeline I am using is very big.

Does MongoDB support any ways of saving an aggregation pipeline in the server, with some placeholder variables, that can be executed by just passing in the variables?

MongoDB server version = 4.4

Pymongo = 3.10.1


问:
createBrowserRouter and heroku
THIS IS NOT A DUPLICATE. I am asking about createBrowserHistory. The question you claim is a duplicate does NOT use createBrowserHistory.

I've found many questions about react-router and heroku but am having trouble finding ones using createBrowserRouter which is recommended in the v6 react-router docs.

Everything works fine locally but when I upload it to heroku, the app says 'Cannot GET' and whatever page it is for everything except my homepage. I tried adding a static.json but that didn't work. I also tried setting the homepage to my heroku apps url and that didn't help either. Here's the relevaant code snippets (the whole index.js is long)

index.js
`

```<code>...const router = createBrowserRouter([
      {
        path: '/',
        element: <Home />,
        errorElement: <Error />,
        children: [
        ]
      },
      {
        path: 'work-history',
        element: <WorkHistory />
      },...

    ...const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <Provider store={store}>
          <RouterProvider router={router} />
        </Provider>
      </React.StrictMode>
    );`
</code>```

static.js

```<code>`{
  "root": "build/",
  "clean_urls": false,
  "routes": {
    "/**": "index.html"
  }
}`
</code>```

Title: createBrowserRouter and heroku

Body:
THIS IS NOT A DUPLICATE. I am asking about createBrowserHistory. The question you claim is a duplicate does NOT use createBrowserHistory.

I've found many questions about react-router and heroku but am having trouble finding ones using createBrowserRouter which is recommended in the v6 react-router docs.

Everything works fine locally but when I upload it to heroku, the app says 'Cannot GET' and whatever page it is for everything except my homepage. I tried adding a static.json but that didn't work. I also tried setting the homepage to my heroku apps url and that didn't help either. Here's the relevaant code snippets (the whole index.js is long)

index.js
`

...const router = createBrowserRouter([
      {
        path: '/',
        element: <Home />,
        errorElement: <Error />,
        children: [
        ]
      },
      {
        path: 'work-history',
        element: <WorkHistory />
      },...

    ...const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <Provider store={store}>
          <RouterProvider router={router} />
        </Provider>
      </React.StrictMode>
    );`

static.js

`{
  "root": "build/",
  "clean_urls": false,
  "routes": {
    "/**": "index.html"
  }
}`


问:
how to use glove in nlpaug
I'm trying to create a word augmenter using glove. This is my code:

import nlpaug.augmenter.word.word_embs as nawwe
aug = nawwe.WordEmbsAug(model_type='glove',model_path='/content/drive/MyDrive/data/Glove/glove.6B.300d.txt', action = 'insert')
```

(I'm reading the glove .txt file from my google drive).
But when I execute it, it gives this error:

load_word2vec_format() got an unexpected keyword argument 'no_header'

How should I fix that?

Title: how to use glove in nlpaug

Body:
I'm trying to create a word augmenter using glove. This is my code:

import nlpaug.augmenter.word.word_embs as nawwe
aug = nawwe.WordEmbsAug(model_type='glove',model_path='/content/drive/MyDrive/data/Glove/glove.6B.300d.txt', action = 'insert')

(I'm reading the glove .txt file from my google drive).
But when I execute it, it gives this error:

load_word2vec_format() got an unexpected keyword argument 'no_header'

How should I fix that?


问:
Not receiving any data in Kibana from Elasticsearch/Logstash. ELK Stack made in docker-compose
I'm trying to build my first ELK Stack in Docker for a school project.

The goal is to have an ElasticSearch container along with it's volume.
A LogStash container linked to ElasticSearch along with it's volume aswell.
A Filebeat container to send data to LogStash
And finaly a Kibana Container to visualise the logs.

The problem I'm having is that even though all seems to be configured and working, Kibana isn't receiving anything from ElasticSearch. When I try to add a new index pattern I'm faced with this message : "No data streams, indices, or index aliases match your index pattern."
And not a thing is visible in Index Management.

Here's the docker-compose.yml:

```<code>version: '3.6'

services:
    Elasticsearch:
        image: elasticsearch:8.5.3
        container_name: elasticsearch
        restart: always
        volumes:
            - elastic_data:/usr/share/elasticsearch/data/
        environment:
            ES_JAVA_OPTS: "-Xmx750m -Xms750m"
            discovery.type: single-node
            xpack.security.enabled: false
        ports:
            - '9200:9200'
            - '9300:9300'
        networks:
            - elk
    Logstash:
        image: logstash:8.5.3
        container_name: logstash
        restart: always
        volumes:
            - ./logstash/logstash.conf:/etc/logstash/conf.d/logstash.conf:ro
        command: logstash -f /etc/logstash/conf.d/logstash.conf
        depends_on:
            - Elasticsearch
        ports:
            - '9600:9600'
        environment:
            LS_JAVA_OPTS: "-Xmx750m -Xms750m"
        networks:
            - elk
    Kibana:
        image: kibana:8.5.3
        container_name: kibana
        restart: always
        ports:
            - '5601:5601'
        environment:
            - ELASTICSEARCH_URL=http://elasticsearch:9200
        depends_on:
            - Elasticsearch
        networks:
            - elk
    Filebeat:
        container_name: filebeat
        image: "docker.elastic.co/beats/filebeat:8.5.3"
        restart: always
        user: root
        volumes:
            - ./filebeat/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro
            - /var/lib/docker:/var/lib/docker:ro
            - /var/run/docker.sock:/var/run/docker.sock
        networks:
            - elk

volumes:
    elastic_data:

networks:
    elk:
        driver: bridge
</code>```

logstash/logstash.conf:

```<code>input {
    beats {
        port => 5044
    }
}
output {
    elasticsearch {
        hosts => "elasticsearch"
        codec => "json"
        index => "logstash-%{indexDay}"
    }
    stdout { codec => rubydebug }
}
</code>```

And finally the filebeat/filebeat.yml:

```<code>filebeat.inputs:
- type: log
  enabled: true
  paths:
    - '/var/lib/docker/containers/*/*.log'

processors:
- add_docker_metadata:
    host: "unix:///var/run/docker.sock"

output.logstash:
  hosts: ["logstash:5044"]
</code>```

Any idea what I'm doing wrong?

Body:
I'm trying to build my first ELK Stack in Docker for a school project.

The goal is to have an ElasticSearch container along with it's volume.
A LogStash container linked to ElasticSearch along with it's volume aswell.
A Filebeat container to send data to LogStash
And finaly a Kibana Container to visualise the logs.

The problem I'm having is that even though all seems to be configured and working, Kibana isn't receiving anything from ElasticSearch. When I try to add a new index pattern I'm faced with this message : "No data streams, indices, or index aliases match your index pattern."
And not a thing is visible in Index Management.

Here's the docker-compose.yml:

version: '3.6'

services:
    Elasticsearch:
        image: elasticsearch:8.5.3
        container_name: elasticsearch
        restart: always
        volumes:
            - elastic_data:/usr/share/elasticsearch/data/
        environment:
            ES_JAVA_OPTS: "-Xmx750m -Xms750m"
            discovery.type: single-node
            xpack.security.enabled: false
        ports:
            - '9200:9200'
            - '9300:9300'
        networks:
            - elk
    Logstash:
        image: logstash:8.5.3
        container_name: logstash
        restart: always
        volumes:
            - ./logstash/logstash.conf:/etc/logstash/conf.d/logstash.conf:ro
        command: logstash -f /etc/logstash/conf.d/logstash.conf
        depends_on:
            - Elasticsearch
        ports:
            - '9600:9600'
        environment:
            LS_JAVA_OPTS: "-Xmx750m -Xms750m"
        networks:
            - elk
    Kibana:
        image: kibana:8.5.3
        container_name: kibana
        restart: always
        ports:
            - '5601:5601'
        environment:
            - ELASTICSEARCH_URL=http://elasticsearch:9200
        depends_on:
            - Elasticsearch
        networks:
            - elk
    Filebeat:
        container_name: filebeat
        image: "docker.elastic.co/beats/filebeat:8.5.3"
        restart: always
        user: root
        volumes:
            - ./filebeat/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro
            - /var/lib/docker:/var/lib/docker:ro
            - /var/run/docker.sock:/var/run/docker.sock
        networks:
            - elk

volumes:
    elastic_data:

networks:
    elk:
        driver: bridge

logstash/logstash.conf:

input {
    beats {
        port => 5044
    }
}
output {
    elasticsearch {
        hosts => "elasticsearch"
        codec => "json"
        index => "logstash-%{indexDay}"
    }
    stdout { codec => rubydebug }
}

And finally the filebeat/filebeat.yml:

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - '/var/lib/docker/containers/*/*.log'

processors:
- add_docker_metadata:
    host: "unix:///var/run/docker.sock"

output.logstash:
  hosts: ["logstash:5044"]

Any idea what I'm doing wrong?


问:
Why is it when i query an object from ROOM database using 2 clauses but it keeps coming up empty?
I have a POJO that am using as an entity that looks like this:

```<code>public class Payment {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id_payment")
int paymentID;
@Embedded
@NonNull
SubjectTeacherCrossRef subjectTeacherCrossRef;
@NonNull
@ColumnInfo(name = "teacher_name")
String teacherName;
@NonNull
@ColumnInfo(name = "payment_date")
String paymentDate;
@NonNull
@ColumnInfo(name = "hours_teached")
int hoursTeached;
@NonNull
@ColumnInfo(name = "payment_total")
int paymentTotal;
</code>```

And inside my Dao i have a query that look like this:

```<code>    @Query("SELECT * FROM payment WHERE payment_date = :date AND teacher_name = :teacherName")
public LiveData<Payment> getPaymentByTeacherAndDate(String date,String teacherName);
</code>```

I am using a repository and a viewModel in this app as proposed by official documentation but i don't think the code there is relevant.

Here is the class where am calling for the method that's responsible of fetching the data from the database:

```<code>public class ReceiptFragment extends Fragment {
private TextView teacherName, total;
private RecyclerView recyclerView;
private ReceiptDetailsAdapter adapter;
private SchoolViewModel viewModel;
private int id;
private List<String> dates;
private long start, end;
private SimpleDateFormat simpleDateFormat;
private List<Payment> payments;
private String test;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_receipt, container, false);
    teacherName = v.findViewById(R.id.tv_receipt_teacher_name);
    recyclerView = v.findViewById(R.id.rv_payment_details);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setHasFixedSize(true);
    total = v.findViewById(R.id.tv_total_payment);
    adapter = new ReceiptDetailsAdapter();
    recyclerView.setAdapter(adapter);
    test = new String();
    viewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
    payments = new ArrayList<>();
    simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    id = getArguments().getInt("id");
    start = getArguments().getLong("start date");
    end = getArguments().getLong("end date");
    List<Payment> datesTest = new ArrayList<>();

    //Setting the Teacher Name
    viewModel.getTeacherByID(id).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
        @Override
        public void onChanged(Teacher teacher) {
            teacherName.setText(teacher.getTeacherName());
        }
    });

    viewModel.getTeacherByID(id).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
        @Override
        public void onChanged(Teacher teacher) {
            for (long i = start; i <= end; i += 86400000) {
                String date = simpleDateFormat.format(i);
                viewModel.getPaymentByTeacherAndDate(date.trim(), teacher.getTeacherName())
                        .observe(getViewLifecycleOwner(), new Observer<Payment>() {
                            @Override
                            public void onChanged(Payment payment) {
                                if (!(payment == null)) {
                                    payments.add(payment);
                                    adapter.setPaymentsDetails(payments);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        });
            }
        }
    });

    return v;
}
</code>```

Both the parameters that am passing to the method are valid as i have checked if that might be the problem.

And i have already tested the recyclerView using a dummy set and it worked just fine.

I suppose that the payment object received by the viewModel in some cases can be null because there will be some dates between the first and last dates that has no payments in them, that's why i created the "null check" before adding it to the list, BUT non of the payment object that i am receiving are valid!

Body:
I have a POJO that am using as an entity that looks like this:

public class Payment {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id_payment")
int paymentID;
@Embedded
@NonNull
SubjectTeacherCrossRef subjectTeacherCrossRef;
@NonNull
@ColumnInfo(name = "teacher_name")
String teacherName;
@NonNull
@ColumnInfo(name = "payment_date")
String paymentDate;
@NonNull
@ColumnInfo(name = "hours_teached")
int hoursTeached;
@NonNull
@ColumnInfo(name = "payment_total")
int paymentTotal;

And inside my Dao i have a query that look like this:

    @Query("SELECT * FROM payment WHERE payment_date = :date AND teacher_name = :teacherName")
public LiveData<Payment> getPaymentByTeacherAndDate(String date,String teacherName);

I am using a repository and a viewModel in this app as proposed by official documentation but i don't think the code there is relevant.

Here is the class where am calling for the method that's responsible of fetching the data from the database:

public class ReceiptFragment extends Fragment {
private TextView teacherName, total;
private RecyclerView recyclerView;
private ReceiptDetailsAdapter adapter;
private SchoolViewModel viewModel;
private int id;
private List<String> dates;
private long start, end;
private SimpleDateFormat simpleDateFormat;
private List<Payment> payments;
private String test;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_receipt, container, false);
    teacherName = v.findViewById(R.id.tv_receipt_teacher_name);
    recyclerView = v.findViewById(R.id.rv_payment_details);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setHasFixedSize(true);
    total = v.findViewById(R.id.tv_total_payment);
    adapter = new ReceiptDetailsAdapter();
    recyclerView.setAdapter(adapter);
    test = new String();
    viewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
    payments = new ArrayList<>();
    simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    id = getArguments().getInt("id");
    start = getArguments().getLong("start date");
    end = getArguments().getLong("end date");
    List<Payment> datesTest = new ArrayList<>();

    //Setting the Teacher Name
    viewModel.getTeacherByID(id).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
        @Override
        public void onChanged(Teacher teacher) {
            teacherName.setText(teacher.getTeacherName());
        }
    });

    viewModel.getTeacherByID(id).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
        @Override
        public void onChanged(Teacher teacher) {
            for (long i = start; i <= end; i += 86400000) {
                String date = simpleDateFormat.format(i);
                viewModel.getPaymentByTeacherAndDate(date.trim(), teacher.getTeacherName())
                        .observe(getViewLifecycleOwner(), new Observer<Payment>() {
                            @Override
                            public void onChanged(Payment payment) {
                                if (!(payment == null)) {
                                    payments.add(payment);
                                    adapter.setPaymentsDetails(payments);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        });
            }
        }
    });

    return v;
}

Both the parameters that am passing to the method are valid as i have checked if that might be the problem.

And i have already tested the recyclerView using a dummy set and it worked just fine.

I suppose that the payment object received by the viewModel in some cases can be null because there will be some dates between the first and last dates that has no payments in them, that's why i created the "null check" before adding it to the list, BUT non of the payment object that i am receiving are valid!


问:
Should I convert my Grails domain relations to use Hibernate Bags?
In Grails 1.3.7 I've spent quite some time to convert my domain class relations according to Burt's suggestions in http://www.infoq.com/presentations/GORM-Performance

Now, Grails 2 supports Hibernate's Bags and I am considering to revert my changes back to hasMany/belongsTo.

With which option will I be more future-proof?

Which problems might arise if I stick to the manual/explicit implementation?

Which problems might arise if I switch to Bags?

Is there any advantage in either variant compared to the other?

Note that the application will see long-term improvements over many years (so no 'deploy-and-forget' :).

UPDATE: One main concern is how much hassle it would incur in regards to manual changes in the database if I did the change after the app goes live. Currently it is unreleased, so it poses to be reasonable before Go-Live.

UPDATE: THE ANSWER

In the blogpost 'Hibernate Bags in Grails 2.0' dated November 2011, Burt Beckwith describes issues with Bags in Grails 2 and concludes:

So I guess I’m back to advocating the approach from my earlier talks;
  don’t map a collection of Books in the Author class, but add an Author
  field to the Book class instead

So the answer is to stick with the converted (i.e. non-set/-list/-bag) variant.

Please vote for re-opening this thread so it may be answered & accepted in correct fashion.

ContentLicense: CC BY-SA 3.0


问:
How to correctly mock with unittest.mock across different modules
I've got a simple exercise function in module a.my_cal.py:

```<code># a.my_cal.py
from datetime import datetime

def is_weekday():
    today = datetime.today()
    day_of_the_week = today.weekday()
    print(f"Day of the week: {today}")
    return (0 <= day_of_the_week < 5)
</code>```

The function returns true for a weekday and false otherwise.

I am trying to test the function by mocking the datetime.today value so that the test passes on any day of the week.

My test is in module b.test_my_cal.py and it looks as follows:

```<code># b.test_my_cal
from unittest.mock import Mock
import src.my_calendar

monday = src.my_calendar.datetime(year=2023, month=1, day=2)

datetime = Mock()

def test_my_cal():
    datetime.today.return_value = monday
    print(f"Print mocked day: {datetime.today.return_value}")

    assert src.my_calendar.is_weekday()
</code>```

What am I missing here, as the function under test always gets the current day rather than the mocked Monday?

Body:
I've got a simple exercise function in module a.my_cal.py:

# a.my_cal.py
from datetime import datetime

def is_weekday():
    today = datetime.today()
    day_of_the_week = today.weekday()
    print(f"Day of the week: {today}")
    return (0 <= day_of_the_week < 5)

The function returns true for a weekday and false otherwise.

I am trying to test the function by mocking the datetime.today value so that the test passes on any day of the week.

My test is in module b.test_my_cal.py and it looks as follows:

# b.test_my_cal
from unittest.mock import Mock
import src.my_calendar

monday = src.my_calendar.datetime(year=2023, month=1, day=2)

datetime = Mock()

def test_my_cal():
    datetime.today.return_value = monday
    print(f"Print mocked day: {datetime.today.return_value}")

    assert src.my_calendar.is_weekday()

What am I missing here, as the function under test always gets the current day rather than the mocked Monday?


问:
Allow targeting .NET Framework in reference projects with .NET 7 when on Windows
I'm making a cross platform app that uses WPF on Windows for UI and Cocoa on Mac.

So I've got a project opens a WPF window, which is dynamically linked to the main application (which is a .NET 7 project). When this is on Mac it will use Cocoa to open the window and the WPF project won't be compiled.

The problem is, when running on Windows, it gives the error:

System.IO.FileNotFoundException: 'Could not load file or assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.'

How do I solve this error without changing the main application project to .NET Framework (it needs to be cross platform).


问:
Repositioning bootstrap card after filtering
through Bootstrap Studio and a few lines of PHP, I dynamically generate a series of Cards.
I can filter the cards via an input box, but the filtered cards, don't reposition....they do if i change the width of the browser window....is there a way to make them reposition?

I'm posting my code

```<code><div style="padding: 20px;border-radius: 20px;" id="card-list">
                    <div class="row" id="myItems" data-masonry="{"percentPosition": true }" >
                      <?php
                      //creo l'elenco dei campionati che si disputeranno fra oggi e domani
                      foreach ($arr_fed_NS as $key => $value) {
                        $text_camp=str_replace(']','',str_replace('[','',$value));
                        // echo '<br>ecco: '.$text_camp.'<BR>';
                        echo'
                            <div class="col-sm-6 col-lg-4 mb-4">
                                <div class="card">
                                    <a href="table.php?camp=['.$text_camp.']"><picture type="" srcset=""><img class="card-img-top p-3" src="'.$arr_camp[$text_camp].'" style="border-radius: 24px; object-fit: cover"></picture></a>
                                    <div class="card-body">
                                        <h3 class="fw-bolder card-title" style="text-align: center;--bs-body-font-weight: bold;">'.$text_camp.'</h3>
                                    </div>
                                </div>
                            </div>';
                        }
                        ?>
                    </div><script async="" src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js" integrity="sha384-GNFwBvfVxBkLMJpYMOABq3c+d3KnQxudP/mGPkzpZSTYykLBNsZEnG2D9G/X/+7D" crossorigin="anonymous"></script>
                </div>
</code>```
```<code>function prova(){
    const input = document.getElementById('filter').value.toUpperCase();
    const card = document.getElementsByClassName('card');

    for (let i = 0; i < card.length; i++) {
      let title = card[i].querySelector(".card-body h3.card-title");

      if (title.innerText.toUpperCase().indexOf(input) > -1){
        card[i].style.display="";

      }else {
        card[i].style.display="none";
      }
    }

  }
</code>```

Body:
through Bootstrap Studio and a few lines of PHP, I dynamically generate a series of Cards.
I can filter the cards via an input box, but the filtered cards, don't reposition....they do if i change the width of the browser window....is there a way to make them reposition?

I'm posting my code

                      <?php
                      //creo l'elenco dei campionati che si disputeranno fra oggi e domani
                      foreach ($arr_fed_NS as $key => $value) {
                        $text_camp=str_replace(']','',str_replace('[','',$value));
                        // echo '
ecco: '.$text_camp.'
';
                        echo'

                                    <picture type="" srcset=""></picture>

'.$text_camp.'

';
                        }
                        ?>

function prova(){
    const input = document.getElementById('filter').value.toUpperCase();
    const card = document.getElementsByClassName('card');

    for (let i = 0; i < card.length; i++) {
      let title = card[i].querySelector(".card-body h3.card-title");

      if (title.innerText.toUpperCase().indexOf(input) > -1){
        card[i].style.display="";

      }else {
        card[i].style.display="none";
      }
    }

  }


问:
C# TCP Socket Distinguish from different clients
I might have a pretty basic question for some of you.

I have created a one(server) to many(clients) relationship where in which server selects a client to send and receive data from and to.

My question is, how can I distinguish incoming data from the different clients? Would I have to simply indicate this in a buffer?

Currently My server listens, accepts and adds clients to a list clientList:

```<code>private void StartListen()
        {
            //Creating a TCP Connection and listening to the port
            tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
            tcpListener.Start();

            toolStripStatusLabel1.Text = "Listening on port 6666 ...";
            int counter = 0;
            appStatus = 0;

            while (true)
            {
                try
                {
                    client = tcpListener.AcceptTcpClient();
                    counter++;
                    clientList.Add(client);

                    IPEndPoint ipend = (IPEndPoint)client.Client.RemoteEndPoint;
                    //Updating status of connection
                    toolStripStatusLabel1.Text = "Connected from " + IPAddress.Parse(ipend.Address.ToString());
                    appStatus = 1;
                    th_inPutStream = new Thread(delegate () { inPutStream(client); });
                    th_inPutStream.Start();
                    th_checkConnection = new Thread(checkConnection);
                    th_checkConnection.Start();

                }
                catch (Exception err)
                {
                    Cleanup_dep();
                }
            }
        }
</code>```

Now i assume if I want to send a message to a specific client, id select the client by clientList[i] and send data.

My question is, when data is available in the network stream to read, how can i know which client its coming from?

This is how I manage incoming data:

```<code>private void inPutStream(TcpClient client)
        {
            try
            {
                while (true)
                {
                    NetworkStream networkstream = client.GetStream();

                    if (networkstream.DataAvailable == true)
                    {
                        int messageID = 0;
                        int messageSize = 0;
                        int bufferSize = 100;

                        //First retrieve size of header
                        byte[] fileSizeBytes = new byte[4];
                        int bytes = networkstream.Read(fileSizeBytes, 0, 4);
                        int dataLength = BitConverter.ToInt32(fileSizeBytes, 0);

                        //Read stream containing header with message details
                        byte[] header = new byte[dataLength];
                        int headerbyte = networkstream.Read(header, 0, dataLength);
                        string headerString = Encoding.ASCII.GetString(header, 0, headerbyte);

                        // Process Message information ie Message ID & Message Size
                        string[] headerSplit = headerString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        Dictionary<string, string> headers = new Dictionary<string, string>();
                        foreach (string s in headerSplit)
                        {
                            if (s.Contains(":"))
                            {
                                headers.Add(s.Substring(0, s.IndexOf(":")), s.Substring(s.IndexOf(":") + 1));
                            }
                        }
                        //Fetch Message ID & Size
                        messageSize = Convert.ToInt32(headers["len"]);
                        messageID = Convert.ToInt32(headers["MsgId"]);

                        //Filter actions by Message ID
                        if (messageID == 1)//Machine info
                        {
                            string machineinfo = processMessage(messageSize, bufferSize, networkstream);
                            clientNames.Add(machineinfo.Split(new char[] { '\r', '\n' })[0]);
                            updateClientListUI();
                        }
                        if (messageID == 2)//CMD Commands
                        {
                            updateText(txtCmdConsole, processMessage(messageSize, bufferSize, networkstream));
                        }
                    }
                }
            }
            catch (Exception err)
            {
                {
                    Cleanup_dep();
                }
            }

        }
</code>```

So if networkstream.DataAvailable == true then it reads, but how can i know from which stream?

Body:
I might have a pretty basic question for some of you.

I have created a one(server) to many(clients) relationship where in which server selects a client to send and receive data from and to.

My question is, how can I distinguish incoming data from the different clients? Would I have to simply indicate this in a buffer?

Currently My server listens, accepts and adds clients to a list clientList:

private void StartListen()
        {
            //Creating a TCP Connection and listening to the port
            tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
            tcpListener.Start();

            toolStripStatusLabel1.Text = "Listening on port 6666 ...";
            int counter = 0;
            appStatus = 0;

            while (true)
            {
                try
                {
                    client = tcpListener.AcceptTcpClient();
                    counter++;
                    clientList.Add(client);

                    IPEndPoint ipend = (IPEndPoint)client.Client.RemoteEndPoint;
                    //Updating status of connection
                    toolStripStatusLabel1.Text = "Connected from " + IPAddress.Parse(ipend.Address.ToString());
                    appStatus = 1;
                    th_inPutStream = new Thread(delegate () { inPutStream(client); });
                    th_inPutStream.Start();
                    th_checkConnection = new Thread(checkConnection);
                    th_checkConnection.Start();

                }
                catch (Exception err)
                {
                    Cleanup_dep();
                }
            }
        }

Now i assume if I want to send a message to a specific client, id select the client by clientList[i] and send data.

My question is, when data is available in the network stream to read, how can i know which client its coming from?

This is how I manage incoming data:

private void inPutStream(TcpClient client)
        {
            try
            {
                while (true)
                {
                    NetworkStream networkstream = client.GetStream();

                    if (networkstream.DataAvailable == true)
                    {
                        int messageID = 0;
                        int messageSize = 0;
                        int bufferSize = 100;

                        //First retrieve size of header
                        byte[] fileSizeBytes = new byte[4];
                        int bytes = networkstream.Read(fileSizeBytes, 0, 4);
                        int dataLength = BitConverter.ToInt32(fileSizeBytes, 0);

                        //Read stream containing header with message details
                        byte[] header = new byte[dataLength];
                        int headerbyte = networkstream.Read(header, 0, dataLength);
                        string headerString = Encoding.ASCII.GetString(header, 0, headerbyte);

                        // Process Message information ie Message ID & Message Size
                        string[] headerSplit = headerString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        Dictionary<string, string> headers = new Dictionary<string, string>();
                        foreach (string s in headerSplit)
                        {
                            if (s.Contains(":"))
                            {
                                headers.Add(s.Substring(0, s.IndexOf(":")), s.Substring(s.IndexOf(":") + 1));
                            }
                        }
                        //Fetch Message ID & Size
                        messageSize = Convert.ToInt32(headers["len"]);
                        messageID = Convert.ToInt32(headers["MsgId"]);

                        //Filter actions by Message ID
                        if (messageID == 1)//Machine info
                        {
                            string machineinfo = processMessage(messageSize, bufferSize, networkstream);
                            clientNames.Add(machineinfo.Split(new char[] { '\r', '\n' })[0]);
                            updateClientListUI();
                        }
                        if (messageID == 2)//CMD Commands
                        {
                            updateText(txtCmdConsole, processMessage(messageSize, bufferSize, networkstream));
                        }
                    }
                }
            }
            catch (Exception err)
            {
                {
                    Cleanup_dep();
                }
            }

        }

So if networkstream.DataAvailable == true then it reads, but how can i know from which stream?


问:
How to disable Google "Tap to search" feature programmatically in mobile/tablet devices, BUT keeping "hold to search"
I would like to know the way for disabling "Tap to search" feature programmatically in mobile/tablet devices, but keeping "hold to search".

'user-select: none;' doesn't solve my issue, because I want to keep tye "hold to search" feature.

```<code>user-select: none;
</code>```

Example: If we visit https://lokkeestudios.com (a portfolio website) with our phone, we can see that if we tap in a word, the search engine will not appear, however if we go to https://coryhughart.com we can see the same issue as in my website. If we touch some word of the website using the mobile phone, the search engine appears.

Image that shows the Google "Tap/hold to search"
Image

Body:
I would like to know the way for disabling "Tap to search" feature programmatically in mobile/tablet devices, but keeping "hold to search".

'user-select: none;' doesn't solve my issue, because I want to keep tye "hold to search" feature.

user-select: none;

Example: If we visit https://lokkeestudios.com (a portfolio website) with our phone, we can see that if we tap in a word, the search engine will not appear, however if we go to https://coryhughart.com we can see the same issue as in my website. If we touch some word of the website using the mobile phone, the search engine appears.

Image that shows the Google "Tap/hold to search"
Image


问:
How to dynamically parse an SpecificRecord in avro in Java?
I'm just starting with avro and beam, I'm working in a ptransform that converts a SpecificRecord into a Map.

The goal is to iterate the field of the SpecificRecord and write the values into a KV structure, the data is coming from Kafka and the ptransform will be used to process different kafka topics that contain data encoded in different avro schemas.

```<code>private static final class FlattenSpecificRecordRecord
      implements SerializableFunction<KV<String, SpecificRecord>, Iterable<ElasticRow>> {
    private final Stream _stream;

    FlattenSpecificRecordRecord(Stream stream) {
      this._stream = stream;
    }

    public static FlattenSpecificRecordRecord of(Stream stream) {
      return new FlattenSpecificRecordRecord(stream);
    }

    @Override
    public Iterable<ElasticRow> apply(KV<String, SpecificRecord> recordKV) {
      // ElasticRow is like a map
      SpecificRecord record = recordKV.getValue()
      // How to traverse this?
      return ???
    }
  }
</code>```

To traverse I was thinking in something like this

```<code>public class RecordConverter implements Serializable {
  private final String _className;
  private final SpecificRecord _record;

  public RecordConverter(String className, SpecificRecord record) {
    this._className = className;
    this._record = record;
  }

  public List<Object> execute() {
    List<Object> objects = new ArrayList<>();
    Schema schema = _record.getSchema();
    GenericRecord avroRecord = new GenericData.Record(_record.getSchema());
    Queue<Schema.Field> fields = new LinkedList<>();
    if (schema.getType() == Schema.Type.RECORD) {
      fields.addAll(schema.getFields());
    }
    for (Schema.Field field : fields) {
      if (field.schema().getType() == Schema.Type.RECORD) {
        fields.add(field);
        continue;
      }
      Object obj = avroRecord.get(field.name());
      System.out.println("This is your value " + obj);
      objects.add(obj);
    }
    return objects;
  }
}
</code>```

where the schema could be something like this (nested records)

```<code>{
  "type": "record",
  "name": "Address",
  "fields": [
    {
      "name": "streetaddress",
      "type": "string"
    },
    {
      "name": "city",
      "type": "City"
    }
  ]
}
</code>```

and the output would be a list of all the nested values within the record

But not sure if this will work, I also checked and the doc says that the recommended way to consume a SpecificRecord is using DatumReader.

As part of the payload I have access to the scheme name of the class
com.company.MyAvroObject in case this simplifies things a bit like creating an instance using reflection.

Any advice on how to proceed?

Body:
I'm just starting with avro and beam, I'm working in a ptransform that converts a SpecificRecord into a Map.

The goal is to iterate the field of the SpecificRecord and write the values into a KV structure, the data is coming from Kafka and the ptransform will be used to process different kafka topics that contain data encoded in different avro schemas.

private static final class FlattenSpecificRecordRecord
      implements SerializableFunction<KV<String, SpecificRecord>, Iterable<ElasticRow>> {
    private final Stream _stream;

    FlattenSpecificRecordRecord(Stream stream) {
      this._stream = stream;
    }

    public static FlattenSpecificRecordRecord of(Stream stream) {
      return new FlattenSpecificRecordRecord(stream);
    }

    @Override
    public Iterable<ElasticRow> apply(KV<String, SpecificRecord> recordKV) {
      // ElasticRow is like a map
      SpecificRecord record = recordKV.getValue()
      // How to traverse this?
      return ???
    }
  }

To traverse I was thinking in something like this

public class RecordConverter implements Serializable {
  private final String _className;
  private final SpecificRecord _record;

  public RecordConverter(String className, SpecificRecord record) {
    this._className = className;
    this._record = record;
  }

  public List<Object> execute() {
    List<Object> objects = new ArrayList<>();
    Schema schema = _record.getSchema();
    GenericRecord avroRecord = new GenericData.Record(_record.getSchema());
    Queue<Schema.Field> fields = new LinkedList<>();
    if (schema.getType() == Schema.Type.RECORD) {
      fields.addAll(schema.getFields());
    }
    for (Schema.Field field : fields) {
      if (field.schema().getType() == Schema.Type.RECORD) {
        fields.add(field);
        continue;
      }
      Object obj = avroRecord.get(field.name());
      System.out.println("This is your value " + obj);
      objects.add(obj);
    }
    return objects;
  }
}

where the schema could be something like this (nested records)

{
  "type": "record",
  "name": "Address",
  "fields": [
    {
      "name": "streetaddress",
      "type": "string"
    },
    {
      "name": "city",
      "type": "City"
    }
  ]
}

and the output would be a list of all the nested values within the record

But not sure if this will work, I also checked and the doc says that the recommended way to consume a SpecificRecord is using DatumReader.

As part of the payload I have access to the scheme name of the class
com.company.MyAvroObject in case this simplifies things a bit like creating an instance using reflection.

Any advice on how to proceed?


问:
How do I Fix: ImportError: cannot import name 'app_commands' from partially initialized module 'discord'
I have 2.1.0 version of ds (It should have app_commands)</p>
```<code>from discord import app_commands, Intents, Client, Interaction

class Bot(Client):
    def __init__(self, *, intents: Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self) -> None:
        await self.tree.sync(guild=None)

bot = Bot(intents=Intents.default())

@bot.event
async def on_ready():
    print(f"Conectado como: {bot.user}")

@bot.tree.command()
async def givemebadge(interaction: Interaction):
    await interaction.response.send_message("Listo!, espera 24 horas para reclamar la insignia\nPuedes reclamarla aquí: https://discord.com/developers/active-developer")

bot.run("TokenHere")

</code>```
```<code>File "c:\Users\name\python\discord.py", line 1, in <module>
    from discord import app_commands, Intents, Client, Interaction
  File "c:\Users\name\python\discord.py", line 1, in <module>
    from discord import app_commands, Intents, Client, Interaction
ImportError: cannot import name 'app_commands' from partially initialized module 'discord' (most likely due to a circular import) (c:\Users\name\python\discord.py)
</code>```

Body:
I have 2.1.0 version of ds (It should have app_commands)

from discord import app_commands, Intents, Client, Interaction

class Bot(Client):
    def __init__(self, *, intents: Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self) -> None:
        await self.tree.sync(guild=None)

bot = Bot(intents=Intents.default())

@bot.event
async def on_ready():
    print(f"Conectado como: {bot.user}")

@bot.tree.command()
async def givemebadge(interaction: Interaction):
    await interaction.response.send_message("Listo!, espera 24 horas para reclamar la insignia\nPuedes reclamarla aquí: https://discord.com/developers/active-developer")

bot.run("TokenHere")

File "c:\Users\name\python\discord.py", line 1, in <module>
    from discord import app_commands, Intents, Client, Interaction
  File "c:\Users\name\python\discord.py", line 1, in <module>
    from discord import app_commands, Intents, Client, Interaction
ImportError: cannot import name 'app_commands' from partially initialized module 'discord' (most likely due to a circular import) (c:\Users\name\python\discord.py)


问:
IntelliJ reports errors in testng.xml after swtiching from Maven to Gradle
Since I'v swtitched from Maven to Gradle, IntelliJ reports errors in all my TestNG .xml configuration files. It seems to be unable to find location of my custom listeners classes as in attached picture.

It is however, somehow able to provide autocompletion:

My build.gradle mentions that config files are not in root but in /testng folder:

```<code>test {
    useTestNG() {
        suites 'testng/' + System.getProperty('suiteFile', 'testng.xml') ?: 'testng.xml'
    }

    systemProperties(System.getProperties())
}
</code>```

It's been like that for few months now, I am not sure what can I do about it besides switching off error notifications?

Body:
Since I'v swtitched from Maven to Gradle, IntelliJ reports errors in all my TestNG .xml configuration files. It seems to be unable to find location of my custom listeners classes as in attached picture.

It is however, somehow able to provide autocompletion:

My build.gradle mentions that config files are not in root but in /testng folder:

test {
    useTestNG() {
        suites 'testng/' + System.getProperty('suiteFile', 'testng.xml') ?: 'testng.xml'
    }

    systemProperties(System.getProperties())
}

It's been like that for few months now, I am not sure what can I do about it besides switching off error notifications?