问:
Unable to Run AudioGraph in Background Task
I'm developing a Xamarin application. It's a glorified audio player. I created a background task for the UWP part which extends IBackgroundTask from Windows.ApplicationModel.Background.

```<code>using Windows.ApplicationModel.Background;

public sealed class BackgroundServiceManager : IBackgroundTask {

    private IIpcNode m_node;//Sends/Receive message powered by LocalSettings
    private BackgroundTaskDeferral m_deferral;

    public void Run(IBackgroundTaskInstance taskInstance) {
        DebugUtils.Log("BackgroundServiceManager.Run()");

        m_deferral = taskInstance.GetDeferral();

        m_services = new List<IBackgroundService> {
            (m_playbackService = new PlaybackService()),
            (m_smartLightService = new SmartLightsService())
        };

        this.RegisterServices();

        taskInstance.Task.Completed += OnTaskCompleted;
        taskInstance.Canceled += OnTaskCanceled;

        //Listen to messages powered by LocalSettings
        m_node.StartListening();
    }

    //...

}

</code>```

I start the task using an application trigger. The background task lives in a separate project.

```<code>public async Task InitializeBackgroundTask() {

    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    localSettings.Values.Clear();

    BackgroundExecutionManager.RemoveAccess();
    var accessStatus = await BackgroundExecutionManager.RequestAccessAsync();

    if (accessStatus == BackgroundAccessStatus.DeniedBySystemPolicy
    || accessStatus == BackgroundAccessStatus.DeniedByUser
    || accessStatus == BackgroundAccessStatus.Unspecified)
        return;

    UnregisterExistingTasks();

    var builder = new BackgroundTaskBuilder() {
        Name = BACKGROUND_TASK_NAME,
        TaskEntryPoint = BACKGROUND_TASK_ENTRY_POINT,
    };

    var applicationTrigger = new ApplicationTrigger();
    builder.SetTrigger(applicationTrigger);

    var registration = (BackgroundTaskRegistration)null;
    try {
        registration = builder.Register();
    }
    catch (Exception ex) {
        throw new Exception(string.Format("Unable to register {0} background task.", BACKGROUND_TASK_NAME), ex);
    }

    registration.Completed += OnBackgroundTaskCompleted;
    registration.Progress += OnRegistrationProgress;

    this.Node.StartListening();

    var result = await applicationTrigger.RequestAsync();

    if (result != ApplicationTriggerResult.Allowed)
        throw new Exception("Unable to trigger background task.");
}
</code>```

I have a background task declaration in my main UWP project. The task type is "general" and I provide the proper entry point.

Also, the Background Media Playback capability is checked.

The task works perfectly fine, but AudioGraph doesn't generate sounds on the background task. MediaPlayer does, however. I need AudioGraph as it allows for seamless audio looping.

Here's my AudioGraph test method. I created it to isolate AudioGraph-related code:

```<code>public static async Task TestAudioGraph(int toneFrequency) {
    var audioFileInfo = await AudioUtils.CreateToneFile(toneFrequency);

    var settings = new AudioGraphSettings(Windows.Media.Render.AudioRenderCategory.Media);
    var createAudioGraphResult = await AudioGraph.CreateAsync(settings);

    if (createAudioGraphResult.Status != AudioGraphCreationStatus.Success)
        throw new Exception(createAudioGraphResult.Status.ToString());

    var audioGraph = createAudioGraphResult.Graph;
    var createDeviceOutputNodeResult = await audioGraph.CreateDeviceOutputNodeAsync();

    if (createDeviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
        throw new Exception(createDeviceOutputNodeResult.Status.ToString());

    var deviceOutputNode = createDeviceOutputNodeResult.DeviceOutputNode;

    var storageFile = await StorageFile.GetFileFromPathAsync(audioFileInfo.FileFullPath);
    var createFileInputNodeResult = await audioGraph.CreateFileInputNodeAsync(storageFile);

    if (createFileInputNodeResult.Status != AudioFileNodeCreationStatus.Success)
        throw new Exception(createFileInputNodeResult.Status.ToString());

    var fileInputNode = createFileInputNodeResult.FileInputNode;
    fileInputNode.OutgoingGain = 1;
    fileInputNode.LoopCount = Int32.MaxValue;

    fileInputNode.AddOutgoingConnection(deviceOutputNode);

    fileInputNode.Start();
    audioGraph.Start();

    await Task.Delay(3000);
}
</code>```

Sending of sound test message from foreground:

```<code>public async Task TestSound() {
    //Test sound on foreground first
    await Task.Run(async () => await UWPUtils.TestAudioGraph(200));

    var message = new UWPIpcMessage("TESTSOUND", null);
    await this.Node.SendMessage(message, true);
}
</code>```

Background's handling of sound test message:

```<code>m_node.Subscribe("TESTSOUND", async (message) => {
    //Then test sound on background
    await Task.Run(async () => await UWPUtils.TestAudioGraph(800));
    return null;
});
</code>```

Would you happen to know why AudioGraph doesn't work? Am I missing a setting or is this possible at all?

I look on the web and couldn't find examples or working samples, just hints that what I'm attempting is possible.

P-S: My task type is "general", because I found no way of triggering "audio" type of tasks.

Thank you

Body:
I'm developing a Xamarin application. It's a glorified audio player. I created a background task for the UWP part which extends IBackgroundTask from Windows.ApplicationModel.Background.

using Windows.ApplicationModel.Background;

public sealed class BackgroundServiceManager : IBackgroundTask {

    private IIpcNode m_node;//Sends/Receive message powered by LocalSettings
    private BackgroundTaskDeferral m_deferral;

    public void Run(IBackgroundTaskInstance taskInstance) {
        DebugUtils.Log("BackgroundServiceManager.Run()");

        m_deferral = taskInstance.GetDeferral();

        m_services = new List<IBackgroundService> {
            (m_playbackService = new PlaybackService()),
            (m_smartLightService = new SmartLightsService())
        };

        this.RegisterServices();

        taskInstance.Task.Completed += OnTaskCompleted;
        taskInstance.Canceled += OnTaskCanceled;

        //Listen to messages powered by LocalSettings
        m_node.StartListening();
    }

    //...

}

I start the task using an application trigger. The background task lives in a separate project.

public async Task InitializeBackgroundTask() {

    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    localSettings.Values.Clear();

    BackgroundExecutionManager.RemoveAccess();
    var accessStatus = await BackgroundExecutionManager.RequestAccessAsync();

    if (accessStatus == BackgroundAccessStatus.DeniedBySystemPolicy
    || accessStatus == BackgroundAccessStatus.DeniedByUser
    || accessStatus == BackgroundAccessStatus.Unspecified)
        return;

    UnregisterExistingTasks();

    var builder = new BackgroundTaskBuilder() {
        Name = BACKGROUND_TASK_NAME,
        TaskEntryPoint = BACKGROUND_TASK_ENTRY_POINT,
    };

    var applicationTrigger = new ApplicationTrigger();
    builder.SetTrigger(applicationTrigger);

    var registration = (BackgroundTaskRegistration)null;
    try {
        registration = builder.Register();
    }
    catch (Exception ex) {
        throw new Exception(string.Format("Unable to register {0} background task.", BACKGROUND_TASK_NAME), ex);
    }

    registration.Completed += OnBackgroundTaskCompleted;
    registration.Progress += OnRegistrationProgress;

    this.Node.StartListening();

    var result = await applicationTrigger.RequestAsync();

    if (result != ApplicationTriggerResult.Allowed)
        throw new Exception("Unable to trigger background task.");
}

I have a background task declaration in my main UWP project. The task type is "general" and I provide the proper entry point.

Also, the Background Media Playback capability is checked.

The task works perfectly fine, but AudioGraph doesn't generate sounds on the background task. MediaPlayer does, however. I need AudioGraph as it allows for seamless audio looping.

Here's my AudioGraph test method. I created it to isolate AudioGraph-related code:

public static async Task TestAudioGraph(int toneFrequency) {
    var audioFileInfo = await AudioUtils.CreateToneFile(toneFrequency);

    var settings = new AudioGraphSettings(Windows.Media.Render.AudioRenderCategory.Media);
    var createAudioGraphResult = await AudioGraph.CreateAsync(settings);

    if (createAudioGraphResult.Status != AudioGraphCreationStatus.Success)
        throw new Exception(createAudioGraphResult.Status.ToString());

    var audioGraph = createAudioGraphResult.Graph;
    var createDeviceOutputNodeResult = await audioGraph.CreateDeviceOutputNodeAsync();

    if (createDeviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
        throw new Exception(createDeviceOutputNodeResult.Status.ToString());

    var deviceOutputNode = createDeviceOutputNodeResult.DeviceOutputNode;

    var storageFile = await StorageFile.GetFileFromPathAsync(audioFileInfo.FileFullPath);
    var createFileInputNodeResult = await audioGraph.CreateFileInputNodeAsync(storageFile);

    if (createFileInputNodeResult.Status != AudioFileNodeCreationStatus.Success)
        throw new Exception(createFileInputNodeResult.Status.ToString());

    var fileInputNode = createFileInputNodeResult.FileInputNode;
    fileInputNode.OutgoingGain = 1;
    fileInputNode.LoopCount = Int32.MaxValue;

    fileInputNode.AddOutgoingConnection(deviceOutputNode);

    fileInputNode.Start();
    audioGraph.Start();

    await Task.Delay(3000);
}

Sending of sound test message from foreground:

public async Task TestSound() {
    //Test sound on foreground first
    await Task.Run(async () => await UWPUtils.TestAudioGraph(200));

    var message = new UWPIpcMessage("TESTSOUND", null);
    await this.Node.SendMessage(message, true);
}

Background's handling of sound test message:

m_node.Subscribe("TESTSOUND", async (message) => {
    //Then test sound on background
    await Task.Run(async () => await UWPUtils.TestAudioGraph(800));
    return null;
});

Would you happen to know why AudioGraph doesn't work? Am I missing a setting or is this possible at all?

I look on the web and couldn't find examples or working samples, just hints that what I'm attempting is possible.

P-S: My task type is "general", because I found no way of triggering "audio" type of tasks.

Thank you


来源: stackexchange

问:
how to binding ngform on angular office js
I am trying to bind ngform on angular office js, but i am getting the follow error No directive found with exportAs 'ngform'. even though I have formsModule imported on app.module.ts. Does any has been working with the form binding on angular office js

expect to display data on get data

ContentLicense: CC BY-SA 4.0


问:
PDFkit not preserving style dimensions in inches
I'm using Jinja2 to generate HTML for flash cards (4 to a page). I have CSS styles that set width and height for table cells in inches so that they're sized the way I want. When I open the HTML file in Firefox or Chrome and print to PDF, the cards fill the whole page as expected.

However, I'd like to be able to generate a PDF for users, so I'm using pdfkit to generate a PDF from the HTML. When I generate a PDF using pdfkit, the flash cards are significantly smaller - around 2.8 inches wide instead of 3.75 inches. It seems like pdfkit is scaling the elements differently for some reason.

Below is a minimal reproduction of the problem in two files. Opening test.html in Chrome or Firefox and printing to 8.5x11 paper (or saving to PDF with those settings) should show the cards filling the page as expected. Generating a pdf using test.py should generate a pdf with much smaller cards.

test.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        @page {
            margin: 0.4in 0.4in 0.4in 0.4in;
        }
        .card {
            width: 3.75in;
            height: 4.95in;
            font-size: 10pt;
        }
        table.card-table, td.card{
            border: 1px;
            border-style: dotted;
            border-color: #AAAAAA;
            vertical-align: top;
        }
        table.card-table {
            page-break-after: always;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <table class="card-table">
        <tbody>
            <tr>
                <td class="card">Test</td>
                <td class="card">Test</td>
            </tr>
            <tr>
                <td class="card">Test</td>
                <td class="card">Test</td>
            </tr>
        </tbody>
    </table>
    <table class="card-table">
        <tbody>
            <tr>
                <td class="card">Test</td>
                <td class="card">Test</td>
            </tr>
            <tr>
                <td class="card">Test</td>
                <td class="card">Test</td>
            </tr>
        </tbody>
    </table>
</body>
</html>
</code>```

test.py:

```<code>import pdfkit

pdfkit.from_file('test.html', 'out.pdf', options={
    'dpi': 300,
    'page-size': 'Letter',
    'margin-top': '0.4in',
    'margin-right': '0.4in',
    'margin-bottom': '0.4in',
    'margin-left': '0.4in',
})
</code>```

Body:
I'm using Jinja2 to generate HTML for flash cards (4 to a page). I have CSS styles that set width and height for table cells in inches so that they're sized the way I want. When I open the HTML file in Firefox or Chrome and print to PDF, the cards fill the whole page as expected.

However, I'd like to be able to generate a PDF for users, so I'm using pdfkit to generate a PDF from the HTML. When I generate a PDF using pdfkit, the flash cards are significantly smaller - around 2.8 inches wide instead of 3.75 inches. It seems like pdfkit is scaling the elements differently for some reason.

Below is a minimal reproduction of the problem in two files. Opening test.html in Chrome or Firefox and printing to 8.5x11 paper (or saving to PDF with those settings) should show the cards filling the page as expected. Generating a pdf using test.py should generate a pdf with much smaller cards.

test.html:

<!DOCTYPE html>

    <meta charset="utf-8">

                Test
                Test

                Test
                Test

                Test
                Test

                Test
                Test

test.py:

import pdfkit

pdfkit.from_file('test.html', 'out.pdf', options={
    'dpi': 300,
    'page-size': 'Letter',
    'margin-top': '0.4in',
    'margin-right': '0.4in',
    'margin-bottom': '0.4in',
    'margin-left': '0.4in',
})


问:
How to send/receive raw ethernet packets from `eth0` to `eth1`?
I created a docker container and connected it to two bridge networks as:

```<code># network 1
docker network create --driver=bridge network1 --subnet=172.56.0.0/24

#network 2
docker network create --driver=bridge network2 --subnet=172.56.1.0/24

docker run \
    --name container \
    --privileged \
    --cap-add=ALL -d \
    -v /dev:/dev \
    --network network1 \
    -v /lib/modules:/lib/modules \
    container-image tail -f /dev/null

docker network connect network2 container
</code>```

Then, I add a bridge NIC to connect eth0 to eth1 and add IP address to it:

```<code># creating bridge NIC
brctl addbr br0
brctl addif br0 eth0
brctl addif br0 eth1
ifconfig br0 up

# adding IP address to br0
ip addr add 172.56.0.3/24 brd + dev br0
route add default gw 172.56.0.1 dev br0
</code>```

Now, If I run ip addr, this is my output:

```<code>2: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 02:42:ac:38:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.56.0.3/24 brd 172.56.0.255 scope global br0
       valid_lft forever preferred_lft forever
6773: eth0@if6774: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br0 state UP group default
    link/ether 02:42:ac:38:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.56.0.2/24 brd 172.56.0.255 scope global eth0
       valid_lft forever preferred_lft forever
6775: eth1@if6776: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br0 state UP group default
    link/ether 02:42:ac:38:01:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.56.1.2/24 brd 172.56.1.255 scope global eth1
       valid_lft forever preferred_lft forever
</code>```

Now, I'm trying to send a raw ethernet packet by using scapy as:

```<code>from scapy.all import *
import sys

src_mac_address = sys.argv[1]
dst_mac_address = sys.argv[2]

packet = Ether(src = src_mac_address, dst = dst_mac_address)

answer = srp(packet, iface='eth0')
</code>```

It sends the packet, but it would not be received by the other side. I checked the traffic by using bmon, So I see the packet coming out of eth0, but it is never going to be received by the eth1. Is something wrong here? I appreciate your help. By the way, I chose src and dst MAC addresses as: src_mac_address = 02:42:ac:38:00:02 for eth0 and dst_mac_address = 02:42:ac:38:00:02 for eth1.

Body:
I created a docker container and connected it to two bridge networks as:

# network 1
docker network create --driver=bridge network1 --subnet=172.56.0.0/24

#network 2
docker network create --driver=bridge network2 --subnet=172.56.1.0/24

docker run \
    --name container \
    --privileged \
    --cap-add=ALL -d \
    -v /dev:/dev \
    --network network1 \
    -v /lib/modules:/lib/modules \
    container-image tail -f /dev/null

docker network connect network2 container

Then, I add a bridge NIC to connect eth0 to eth1 and add IP address to it:

# creating bridge NIC
brctl addbr br0
brctl addif br0 eth0
brctl addif br0 eth1
ifconfig br0 up

# adding IP address to br0
ip addr add 172.56.0.3/24 brd + dev br0
route add default gw 172.56.0.1 dev br0

Now, If I run ip addr, this is my output:

2: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 02:42:ac:38:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.56.0.3/24 brd 172.56.0.255 scope global br0
       valid_lft forever preferred_lft forever
6773: eth0@if6774: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br0 state UP group default
    link/ether 02:42:ac:38:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.56.0.2/24 brd 172.56.0.255 scope global eth0
       valid_lft forever preferred_lft forever
6775: eth1@if6776: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br0 state UP group default
    link/ether 02:42:ac:38:01:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.56.1.2/24 brd 172.56.1.255 scope global eth1
       valid_lft forever preferred_lft forever

Now, I'm trying to send a raw ethernet packet by using scapy as:

from scapy.all import *
import sys

src_mac_address = sys.argv[1]
dst_mac_address = sys.argv[2]

packet = Ether(src = src_mac_address, dst = dst_mac_address)

answer = srp(packet, iface='eth0')

It sends the packet, but it would not be received by the other side. I checked the traffic by using bmon, So I see the packet coming out of eth0, but it is never going to be received by the eth1. Is something wrong here? I appreciate your help. By the way, I chose src and dst MAC addresses as: src_mac_address = 02:42:ac:38:00:02 for eth0 and dst_mac_address = 02:42:ac:38:00:02 for eth1.


问:
Replication in ifogsim
I want to make a data replication manager in my fog architecture
this data replica manager component has 3 methods a monitor module, a predication module, data replica placement module)in fog layer
I really need it for my thesis
in ifogsim i made a class and made my 3layer architecture
but I don't know which of the class of ifogsim I should modify to make a data replica manager</p>

Title: Replication in ifogsim


问:
Custom Approval ActionIdType AWS
I am trying to build a custom approval step for my CodePipeline on AWS. The AWS built default approval ActionTypeId does not let you output artifacts. I want my approval step to be able to output artifacts. I found this document on creating custom ActionTypeIds but I am still confused an fuzzy on this. Any help will be really appreciated.

I've posted the code from AWS. can someone help me understand the "settings" and the "configurationProperties" sections?

```<code>{
    "category": "Approval",
    "provider": "My-Custom-ActionIdType",
    "version": "1",
    "settings": {
        "entityUrlTemplate": "https://my-build-instance/job/{Config:CGBoyProject}/",
        "executionUrlTemplate": "https://my-build-instance/job/{Config:ProjectName}/lastSuccessfulBuild/{ExternalExecutionId}/"
    },
    "configurationProperties": [{
        "name": "ProjectName",
        "required": true,
        "key": true,
        "secret": false,
        "queryable": false,
        "description": "The name of the build project must be provided when this action is added to the pipeline.",
        "type": "String"
    }],
    "inputArtifactDetails": {
        "maximumCount": integer,
        "minimumCount": integer
    },
    "outputArtifactDetails": {
        "maximumCount": integer,
        "minimumCount": integer
    },
    "tags": [{
      "key": "Project",
      "value": "ProjectA"
    }]
}

</code>```

Title: Custom Approval ActionIdType AWS

Body:
I am trying to build a custom approval step for my CodePipeline on AWS. The AWS built default approval ActionTypeId does not let you output artifacts. I want my approval step to be able to output artifacts. I found this document on creating custom ActionTypeIds but I am still confused an fuzzy on this. Any help will be really appreciated.

I've posted the code from AWS. can someone help me understand the "settings" and the "configurationProperties" sections?

{
    "category": "Approval",
    "provider": "My-Custom-ActionIdType",
    "version": "1",
    "settings": {
        "entityUrlTemplate": "https://my-build-instance/job/{Config:CGBoyProject}/",
        "executionUrlTemplate": "https://my-build-instance/job/{Config:ProjectName}/lastSuccessfulBuild/{ExternalExecutionId}/"
    },
    "configurationProperties": [{
        "name": "ProjectName",
        "required": true,
        "key": true,
        "secret": false,
        "queryable": false,
        "description": "The name of the build project must be provided when this action is added to the pipeline.",
        "type": "String"
    }],
    "inputArtifactDetails": {
        "maximumCount": integer,
        "minimumCount": integer
    },
    "outputArtifactDetails": {
        "maximumCount": integer,
        "minimumCount": integer
    },
    "tags": [{
      "key": "Project",
      "value": "ProjectA"
    }]
}


问:
Buy and Hold Abnormal returns in R studio
I am trying to compute buy and hold abnormal returns (BHAR) for a sample of stock with different event date.

The formula to compute BHAR is as follow:

BHAR formula

Rit is the actual firm return and the expected return is computed using the Market model :

Expected return equation

the alpha and beta are defined using a regression of the firm data with the market proxy, on an estimation period of 252 trading days that start 11 days before the event date (to shield it from the effect of the announcment).

I have 3 dataframes:

index_data with prices and date of the market index used as proxy

stock_data with the tickers of my selected firms, the date and the closing price

event_data with event dates and the corresponding tickers

In pseudo-code what i'd like to do is :

for each value in event_data

compute the estimation window start as: event date - 265 days - 11 days

compute the estimation window end as: event date - 11

fit a linear regression model between stock_data and index_data on the estimation window

extract alpha and beta coefficients for each stock

compute the expected return as alpha + Beta * Market return in a new column in stock_data dataframe
 end for

Compute the BHAR as the actual firm return cumulative product - the expected return cumulative product

I have tried the following code:

```<code># Loop through the tickers in ticker_BHAR
for (ticker in event_data$Ticker[1:19]) {
  # Get the event date for the current ticker
  event_date <- as.date(event_data$date[event_data$Ticker == ticker], format = "%d-%m-%Y")

  # Compute the start and end dates for the estimation window
  start_date <- event_date - 265 - 11
  end_date <- event_date - 11

  # Subset the stock_data and index_data dataframes to only include the dates in the estimation window
  stock_subset <- stock_data[stock_data$Ticker == ticker & stock_data$date >= start_date & stock_data$date <= end_date, ]
  index_subset <- index_data[index_data$date >= start_date & index_data$date <= end_date, ]

  # Fit a linear regression model between the stock and index data
  model <- lm(stock_subset$adjusted ~ index_subset$close)

  # Extract the alpha and beta coefficients from the model
  alpha <- coef(model)[1]
  beta <- coef(model)[2]

  # Compute the expected return for the current ticker and add it to the stock_data dataframe
  stock_data[stock_data$Ticker == ticker, "expected_return"] <- alpha + beta * market_return
}
</code>```

The error I get when running the code is :

 "Error in model.frame.default(formula = stock_subset$adjusted ~ index_subset$close,  : variables length differ (found for 'index_subset$close')"

I am a big newbie, I am working on providing a MRE

Thank you for your help.

Body:
I am trying to compute buy and hold abnormal returns (BHAR) for a sample of stock with different event date.

The formula to compute BHAR is as follow:

BHAR formula

Rit is the actual firm return and the expected return is computed using the Market model :

Expected return equation

the alpha and beta are defined using a regression of the firm data with the market proxy, on an estimation period of 252 trading days that start 11 days before the event date (to shield it from the effect of the announcment).

I have 3 dataframes:

index_data with prices and date of the market index used as proxy

stock_data with the tickers of my selected firms, the date and the closing price

event_data with event dates and the corresponding tickers

In pseudo-code what i'd like to do is :

for each value in event_data

compute the estimation window start as: event date - 265 days - 11 days

compute the estimation window end as: event date - 11

fit a linear regression model between stock_data and index_data on the estimation window

extract alpha and beta coefficients for each stock

compute the expected return as alpha + Beta * Market return in a new column in stock_data dataframe
 end for

Compute the BHAR as the actual firm return cumulative product - the expected return cumulative product

I have tried the following code:

# Loop through the tickers in ticker_BHAR
for (ticker in event_data$Ticker[1:19]) {
  # Get the event date for the current ticker
  event_date <- as.date(event_data$date[event_data$Ticker == ticker], format = "%d-%m-%Y")

  # Compute the start and end dates for the estimation window
  start_date <- event_date - 265 - 11
  end_date <- event_date - 11

  # Subset the stock_data and index_data dataframes to only include the dates in the estimation window
  stock_subset <- stock_data[stock_data$Ticker == ticker & stock_data$date >= start_date & stock_data$date <= end_date, ]
  index_subset <- index_data[index_data$date >= start_date & index_data$date <= end_date, ]

  # Fit a linear regression model between the stock and index data
  model <- lm(stock_subset$adjusted ~ index_subset$close)

  # Extract the alpha and beta coefficients from the model
  alpha <- coef(model)[1]
  beta <- coef(model)[2]

  # Compute the expected return for the current ticker and add it to the stock_data dataframe
  stock_data[stock_data$Ticker == ticker, "expected_return"] <- alpha + beta * market_return
}

The error I get when running the code is :

 "Error in model.frame.default(formula = stock_subset$adjusted ~ index_subset$close,  : variables length differ (found for 'index_subset$close')"

I am a big newbie, I am working on providing a MRE

Thank you for your help.


问:
No compileOnly configuration in the build.gradle but it is
I have the following error message during the build, but no compileOnly dependency in my build.gradle. Why it's happens, and how to solve?
Regards

Resolving dependency configuration 'compileOnly' is not allowed as it
is defined as 'canBeResolved=false'. Instead, a resolvable
('canBeResolved=true') dependency configuration that extends
'compileOnly' should be resolved.

```<code>buildscript {
    ext.kotlin_version = '1.6.0'

    repositories {
        mavenCentral()

        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }

        maven {
            url "https://plugins.gradle.org/m2/"
        }

        repositories {
            flatDir {
                dirs 'jars'
            }
        }
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

plugins {
    id "org.jetbrains.intellij" version "1.10.1"
    id "org.jetbrains.grammarkit" version "2020.1"

}

configurations {
    configurations.implementation.setCanBeResolved(true)
}

group 'com.interfaced'
version '0.2.7'

apply plugin: 'kotlin'
apply plugin: 'org.jetbrains.intellij'

sourceSets {
    all {
        java.srcDirs += ['src/main/gen']
        kotlin.srcDirs += ['src/main/kotlin']
        resources.srcDirs = ['src/main/resources']
    }
}

grammarKit {
    jflexRelease = '1.7.0-2'
}

repositories {
    mavenCentral()
    maven {
        url "https://cache-redirector.jetbrains.com/intellij-dependencies"
    }
}

dependencies {
    // https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib
    compileClasspath  group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: '1.7.22'

    compileClasspath  files('jars/grammar-kit.jar')
    compileClasspath  group: 'junit', name: 'junit', version: '4.12'
    compileClasspath  "org.jetbrains.kotlin:kotlin-stdlib-jdk7"

}

intellij {
    version '2022.3'
}

import org.jetbrains.grammarkit.tasks.GenerateLexer
import org.jetbrains.grammarkit.tasks.GenerateParser

def GENERATE_GROUP = 'Generate'

task generateLexer(type: GenerateLexer) {
    source = "src/main/grammar/BrightScript.flex"
    targetDir = "src/main/gen/com/interfaced/brs/lang/lexer"
    targetClass = "_BrsLexer"
    skeleton = "src/main/grammar/idea-flex.skeleton"
    purgeOldFiles = true

    description = 'Generate Lexer Java sources for BrightScript'
    group = GENERATE_GROUP
}

task generateParser(type: GenerateParser) {
    source = "src/main/grammar/BrightScript.bnf"
    targetRoot = 'src/main/gen'
    pathToParser = 'src/main/gen/com/interfaced/brs/lang/BrsParser.java'
    pathToPsiRoot = 'src/main/gen/com/interfaced/brs/lang/psi'
    purgeOldFiles = true

    description = 'Generate Parser Java sources for BrightScript'
    group = GENERATE_GROUP

    // patch up to date check
    outputs.upToDateWhen { false }
}

compileKotlin {
    kotlinOptions.jvmTarget = "17"
}

compileKotlin.dependsOn(generateLexer, generateParser)
</code>```

Body:
I have the following error message during the build, but no compileOnly dependency in my build.gradle. Why it's happens, and how to solve?
Regards

Resolving dependency configuration 'compileOnly' is not allowed as it
is defined as 'canBeResolved=false'. Instead, a resolvable
('canBeResolved=true') dependency configuration that extends
'compileOnly' should be resolved.

buildscript {
    ext.kotlin_version = '1.6.0'

    repositories {
        mavenCentral()

        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }

        maven {
            url "https://plugins.gradle.org/m2/"
        }

        repositories {
            flatDir {
                dirs 'jars'
            }
        }
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

plugins {
    id "org.jetbrains.intellij" version "1.10.1"
    id "org.jetbrains.grammarkit" version "2020.1"

}

configurations {
    configurations.implementation.setCanBeResolved(true)
}

group 'com.interfaced'
version '0.2.7'

apply plugin: 'kotlin'
apply plugin: 'org.jetbrains.intellij'

sourceSets {
    all {
        java.srcDirs += ['src/main/gen']
        kotlin.srcDirs += ['src/main/kotlin']
        resources.srcDirs = ['src/main/resources']
    }
}

grammarKit {
    jflexRelease = '1.7.0-2'
}

repositories {
    mavenCentral()
    maven {
        url "https://cache-redirector.jetbrains.com/intellij-dependencies"
    }
}

dependencies {
    // https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib
    compileClasspath  group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: '1.7.22'

    compileClasspath  files('jars/grammar-kit.jar')
    compileClasspath  group: 'junit', name: 'junit', version: '4.12'
    compileClasspath  "org.jetbrains.kotlin:kotlin-stdlib-jdk7"

}

intellij {
    version '2022.3'
}

import org.jetbrains.grammarkit.tasks.GenerateLexer
import org.jetbrains.grammarkit.tasks.GenerateParser

def GENERATE_GROUP = 'Generate'

task generateLexer(type: GenerateLexer) {
    source = "src/main/grammar/BrightScript.flex"
    targetDir = "src/main/gen/com/interfaced/brs/lang/lexer"
    targetClass = "_BrsLexer"
    skeleton = "src/main/grammar/idea-flex.skeleton"
    purgeOldFiles = true

    description = 'Generate Lexer Java sources for BrightScript'
    group = GENERATE_GROUP
}

task generateParser(type: GenerateParser) {
    source = "src/main/grammar/BrightScript.bnf"
    targetRoot = 'src/main/gen'
    pathToParser = 'src/main/gen/com/interfaced/brs/lang/BrsParser.java'
    pathToPsiRoot = 'src/main/gen/com/interfaced/brs/lang/psi'
    purgeOldFiles = true

    description = 'Generate Parser Java sources for BrightScript'
    group = GENERATE_GROUP

    // patch up to date check
    outputs.upToDateWhen { false }
}

compileKotlin {
    kotlinOptions.jvmTarget = "17"
}

compileKotlin.dependsOn(generateLexer, generateParser)


问:
What's the best way to integrate Tailwindcss Heroicions into Laravel 9?
What's the best way to integrate Tailwindcss Heroicions into Laravel 9?

This is my workflow. I created a "symbols" folder in my Laravel file structure:

resources > views > components > symbols

Then I download and save each SVG file: arrow-down.blade.php.

In the SVG blade file I empty the class attribute and replace it with {{ $class }}:

```<code><svg xmlns="http://www.w3.org/2000/svg" class="{{ $class }}">
  <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
</svg>
</code>```

And integrate it like this:

```<code><x-symbols.star class="w-6 h-6"/>
</code>```

Is there a better way? Can I download Heroicons as Blade files so I don't have to do this manual work?

Body:
What's the best way to integrate Tailwindcss Heroicions into Laravel 9?

This is my workflow. I created a "symbols" folder in my Laravel file structure:

resources > views > components > symbols

Then I download and save each SVG file: arrow-down.blade.php.

In the SVG blade file I empty the class attribute and replace it with {{ $class }}:

<svg xmlns="http://www.w3.org/2000/svg" class="{{ $class }}">
  <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
</svg>

And integrate it like this:

<x-symbols.star class="w-6 h-6"/>

Is there a better way? Can I download Heroicons as Blade files so I don't have to do this manual work?


问:
Is there an analog of the Sleep function in c++, but which could continue working until the time expires?
Is there a function that could suspend the stream for a certain time, and if some event occurred (for example: the user pressed a button), then the function would resume the stream before the time expires? If not, what can you advise?

As an example, I wrote a function that takes 2 parameters:
the delay time in milliseconds;
bool-a variable that, if changed to true, will terminate the loop ahead of time.

```<code>#include <iostream>
float Timer(clock_t milliseconds, bool& stop) {
    clock_t start = clock(), now;

    while ((now = clock() - start) <= milliseconds) {
        if (stop) {
            return now / 1000.f;
        }
    }

    return 0;
}
</code>```

Body:
Is there a function that could suspend the stream for a certain time, and if some event occurred (for example: the user pressed a button), then the function would resume the stream before the time expires? If not, what can you advise?

As an example, I wrote a function that takes 2 parameters:
the delay time in milliseconds;
bool-a variable that, if changed to true, will terminate the loop ahead of time.

#include <iostream>
float Timer(clock_t milliseconds, bool& stop) {
    clock_t start = clock(), now;

    while ((now = clock() - start) <= milliseconds) {
        if (stop) {
            return now / 1000.f;
        }
    }

    return 0;
}


问:
Make NavigationBar completely transparent
I need the NavigationBar to display only the navigation bar strip.

To do this, I added the following to themes.xml

```<code><item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</code>```

But this is not enough, since my NavigationBar has a translucent backgraund, to fix this, I found this code.

```<code>getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
</code>```

And in a sense it worked, but everything disappeared for me, including the navigation bar strip. How can I implement what I want?

It is necessary that only the strip is displayed on top of the activity, without background.

Body:
I need the NavigationBar to display only the navigation bar strip.

To do this, I added the following to themes.xml

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>

But this is not enough, since my NavigationBar has a translucent backgraund, to fix this, I found this code.

getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

And in a sense it worked, but everything disappeared for me, including the navigation bar strip. How can I implement what I want?

It is necessary that only the strip is displayed on top of the activity, without background.


问:
How to select a month in a combobox calendar inside an iframe with python Playwright?
I'm trying to select (click) a month in a combobox calendar. calendar image

The element is inside an iframe. 1º print html     | 2º print html

I tried:

```<code>element = '//div[@class="drp-calendar right"]//option[@value="11"]'
page.frame_locator('//frame[@name="GCBody"]').locator(element).click()
</code>```

But it's returning an error:

"element is not visible - waiting..."

But the element is actually visible!  calendar image

Playwright error log:

```<code>  waiting for frame_locator("xpath=//frame[@name=\"GCBody\"]")
  locator resolved to visible <frame noresize="" border="no" name="GCBody" frameborde…></frame>
waiting for frame_locator("xpath=//frame[@name=\"GCBody\"]").locator("xpath=//div[@class=\"drp-calendar right\"]//option[@value=\"11\"]")
  locator resolved to hidden <option value="11">Dezembro</option>
attempting click action
  waiting for element to be visible, enabled and stable
    element is not visible - waiting...
</code>```

Body:
I'm trying to select (click) a month in a combobox calendar. calendar image

The element is inside an iframe. 1º print html     | 2º print html

I tried:

element = '//div[@class="drp-calendar right"]//option[@value="11"]'
page.frame_locator('//frame[@name="GCBody"]').locator(element).click()

But it's returning an error:

"element is not visible - waiting..."

But the element is actually visible!  calendar image

Playwright error log:

  waiting for frame_locator("xpath=//frame[@name=\"GCBody\"]")
  locator resolved to visible <frame noresize="" border="no" name="GCBody" frameborde…></frame>
waiting for frame_locator("xpath=//frame[@name=\"GCBody\"]").locator("xpath=//div[@class=\"drp-calendar right\"]//option[@value=\"11\"]")
  locator resolved to hidden <option value="11">Dezembro</option>
attempting click action
  waiting for element to be visible, enabled and stable
    element is not visible - waiting...


问:
Positioning students based on marks
I have the following code that retrieves a list of students and their marks for a particular subject.

SELECT *
FROM student_subject_averages
where teaching_load_id IN (
    SELECT id
    from teaching_loads
    where teaching_loads.teacher_id=1573 AND subject_id=24 AND
          teaching_loads.class_id IN (
               SELECT id
               from grades
               WHERE grades.stream_id=4))
```

How do I position the student according to their average in descending order?

I want the query to return the position of each child according to their mark

Title: Positioning students based on marks

Body:
I have the following code that retrieves a list of students and their marks for a particular subject.

SELECT *
FROM student_subject_averages
where teaching_load_id IN (
    SELECT id
    from teaching_loads
    where teaching_loads.teacher_id=1573 AND subject_id=24 AND
          teaching_loads.class_id IN (
               SELECT id
               from grades
               WHERE grades.stream_id=4))

How do I position the student according to their average in descending order?

I want the query to return the position of each child according to their mark


问:
How to make address sanitizer work in windows server 2008 r2?
My program is build by VS2022 with address sanitizer enabled. It works in my own PC(win11). But when running it in windows server 2008 r2, it reports error like "cannot locate PssQuerySnapshot in KERNEL32.dll". It seems the system is too old to support this function.

Without address sanitizer, the program works. The program do has some memory bugs which only trigger in the server, so I want to use address sanitizer to find them.

Does anyone know how to make it work? Maybe the easiest way is to upgrade system to higher version, but I cannot do it.


问:
Python scrapy_selenium SeleniumMiddleware returns Timeout error from renderer
I'm using scrapy to run tests using Selenium Webdriver. Most of the time script works fine, but sometimes it returns a Timeout error when initializing SeleniumMiddleware.

Below is my custom download middleware which inherits from SeleniumMiddleware.

```<code>class CustomDownloadMiddleware(SeleniumMiddleware):
def __init__(self, *args, **kwargs):

    try:
        super().__init__(*args, **kwargs) # This is where Timeout exception happens
    except Exception as e:
        print("-- Unable initialize Selenium Middleware ---")
        print(e) # This is where it prints the exception message

def process_request(self, request, spider):
    """Process a request using the selenium driver if applicable"""
    ...
</code>```

Below is the error message I'm receiving.

```<code>Message: session not created
source-app-1  | from timeout: Timed out receiving message from renderer: 600.000
source-app-1  |   (Session info: headless chrome=102.0.5005.182)
</code>```

I'm using Python with scrapy, scrapy_selenium libraries and I use Chrome webdriver.
I see this failure at a rate of about 1 in 10.

FYI... There is a similar post related to this issue but there is no clear answer to what's causing it or how to fix it. (I've tried all posible solutions mentioned in that post)
Selenium Timed out receiving message from renderer

UPDATE

I dive deeper and the Timeout exception is happening when the code initiates the webdriver.Chrome() class, from python's selenium packages.

Body:
I'm using scrapy to run tests using Selenium Webdriver. Most of the time script works fine, but sometimes it returns a Timeout error when initializing SeleniumMiddleware.

Below is my custom download middleware which inherits from SeleniumMiddleware.

class CustomDownloadMiddleware(SeleniumMiddleware):
def __init__(self, *args, **kwargs):

    try:
        super().__init__(*args, **kwargs) # This is where Timeout exception happens
    except Exception as e:
        print("-- Unable initialize Selenium Middleware ---")
        print(e) # This is where it prints the exception message

def process_request(self, request, spider):
    """Process a request using the selenium driver if applicable"""
    ...

Below is the error message I'm receiving.

Message: session not created
source-app-1  | from timeout: Timed out receiving message from renderer: 600.000
source-app-1  |   (Session info: headless chrome=102.0.5005.182)

I'm using Python with scrapy, scrapy_selenium libraries and I use Chrome webdriver.
I see this failure at a rate of about 1 in 10.

FYI... There is a similar post related to this issue but there is no clear answer to what's causing it or how to fix it. (I've tried all posible solutions mentioned in that post)
Selenium Timed out receiving message from renderer

UPDATE

I dive deeper and the Timeout exception is happening when the code initiates the webdriver.Chrome() class, from python's selenium packages.


问:
Passing Django request object into script to build absolute URI?
I am trying to build a one time script by passing in a django request in order to build an absolute URI.

I am using the HttpRequest() method as follows...

request = HttpRequest()

And passing it into the function that I am calling when running my script.

I keep running into a KeyError

My script that is being ran is as follows,

```<code>from django.http import HttpRequest

for form in forms:

    form_data = get_data(form)

    for user in User.objects.all():

        request = HttpRequest()

        config_user_forms(request, user)
</code>```

Errors out with the following,

```<code>  File "config_user_forms.py", line 65, in <module>
    redeploy_form(request, user)
  File "/tmp/8dae22604556cc2/users/admin/users.py", line 654, in redeploy_form
    build_url = request.build_absolute_uri(
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 223, in build_url
    location = self._current_scheme_host + location
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/utils/functional.py", line 45, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 240, in _current_scheme_host
    return "{}://{}".format(self.scheme, self.get_host())
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 121, in get_host
    host = self._get_raw_host()
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 111, in _get_raw_host
    host = self.META["SERVER_NAME"]
KeyError: 'SERVER_NAME'
</code>```

I am a bit stumped on a work around, and appreciate any help in advance!

Body:
I am trying to build a one time script by passing in a django request in order to build an absolute URI.

I am using the HttpRequest() method as follows...

request = HttpRequest()

And passing it into the function that I am calling when running my script.

I keep running into a KeyError

My script that is being ran is as follows,

from django.http import HttpRequest

for form in forms:

    form_data = get_data(form)

    for user in User.objects.all():

        request = HttpRequest()

        config_user_forms(request, user)

Errors out with the following,

  File "config_user_forms.py", line 65, in <module>
    redeploy_form(request, user)
  File "/tmp/8dae22604556cc2/users/admin/users.py", line 654, in redeploy_form
    build_url = request.build_absolute_uri(
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 223, in build_url
    location = self._current_scheme_host + location
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/utils/functional.py", line 45, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 240, in _current_scheme_host
    return "{}://{}".format(self.scheme, self.get_host())
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 121, in get_host
    host = self._get_raw_host()
  File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 111, in _get_raw_host
    host = self.META["SERVER_NAME"]
KeyError: 'SERVER_NAME'

I am a bit stumped on a work around, and appreciate any help in advance!


问:
How can I stop my draggable div from going off-screen?
I have a colour picker in a draggable div that can be opened by clicking an image. It can be dragged around the page and closed at any time.

This is what it looks like:

But when you drag to too far to the edges, it goes out of view.

Like this:

This is my code:

let openColorPicker = document.getElementById("universalPicker");

function openPicker() {
  openColorPicker.style.display = "block";
}

let closeColorPicker = document.getElementById("universalPicker");

function closePicker() {
  closeColorPicker.style.display = "none";
}

// Make the DIV element draggable:
dragElement(document.getElementById("universalPicker"));

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#universalPicker {
  display: none;
  background-color: #575757;
  border-radius: 10px;
  width: 390px;
  padding: 10px;
  position: absolute;
  z-index: 99;
}

.color {
  padding: 0px;
  vertical-align: middle;
}

.openColorButton {
  margin: 10px;
  background-color: #000000;
  border: none;
}

.openColorButton:hover {
  outline: 2px solid #272727;
}

.move:hover {
  cursor: grab;
}</code>```

  <button onclick="closePicker()" title="Close">
                    close
                </button>
  <button title="Move" class="move">
                    open_with
                    </button>
  Pick any colour from this page:
  <input type="color" id="color" name="color" value="#19139D">

<button onclick="openPicker()" class="openColorButton"></button>```

I also need to be able to set a starting position for the picker when ever you click the open button. Is there anyway to do this? Thanks in advance

Body:
I have a colour picker in a draggable div that can be opened by clicking an image. It can be dragged around the page and closed at any time.

This is what it looks like:

But when you drag to too far to the edges, it goes out of view.

Like this:

This is my code:

let openColorPicker = document.getElementById("universalPicker");

function openPicker() {
  openColorPicker.style.display = "block";
}

let closeColorPicker = document.getElementById("universalPicker");

function closePicker() {
  closeColorPicker.style.display = "none";
}

// Make the DIV element draggable:
dragElement(document.getElementById("universalPicker"));

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

#universalPicker {
  display: none;
  background-color: #575757;
  border-radius: 10px;
  width: 390px;
  padding: 10px;
  position: absolute;
  z-index: 99;
}

.color {
  padding: 0px;
  vertical-align: middle;
}

.openColorButton {
  margin: 10px;
  background-color: #000000;
  border: none;
}

.openColorButton:hover {
  outline: 2px solid #272727;
}

.move:hover {
  cursor: grab;
}

  <button onclick="closePicker()" title="Close">
                    close
                </button>
  <button title="Move" class="move">
                    open_with
                    </button>
  Pick any colour from this page:
  <input type="color" id="color" name="color" value="#19139D">

<button onclick="openPicker()" class="openColorButton"></button>

I also need to be able to set a starting position for the picker when ever you click the open button. Is there anyway to do this? Thanks in advance


问:
Adding multiple flutter library modules fails build with duplicate class
Fail log

```<code>gw assembleDebug --scan

> Task :app:checkDebugDuplicateClasses FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
   > Duplicate class io.flutter.plugins.GeneratedPluginRegistrant found in modules flutter_debug-1.0-runtime (com.example.a.library_a:flutter_debug:1.0) and flutter_debug-2.0-runtime (com.example.b.library_b:flutter_debug:2.0)

     Go to the documentation to learn how to <a href="d.android.com/r/tools/classpath-sync-errors">Fix dependency resolution errors</a>.
</code>```

Steps to reproduce;

```<code>flutter create -t module --org com.example.a library_a
cd library_a
flutter pub add android_intent_plus
flutter build aar

cd ..

flutter create -t module --org com.example.b library_b
cd library_a
flutter pub add android_intent_plus
// Open pubspec.yaml and change android_intent_plus to 1.0.1
flutter build aar --build-number=2.0
</code>```

Add both library_a and library_b to an android project. (I tested with a new project)

Build fails with duplicate class.

flutter doctor;

```<code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.10, on macOS 12.5.1 21G83 darwin-arm, locale en-DE)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[!] Android Studio
    ✗ Unable to find bundled Java version.
[!] Android Studio
    ✗ Unable to find bundled Java version.
[!] Android Studio
    ✗ Unable to find bundled Java version.
[✓] Android Studio (version 2021.3)
[!] Android Studio
    ✗ Unable to find bundled Java version.
[✓] IntelliJ IDEA Ultimate Edition (version 2022.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.3)
[✓] VS Code (version 1.74.1)
[✓] Connected device (2 available)
[✓] HTTP Host Availability
</code>```

Body:
Fail log

gw assembleDebug --scan

> Task :app:checkDebugDuplicateClasses FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
   > Duplicate class io.flutter.plugins.GeneratedPluginRegistrant found in modules flutter_debug-1.0-runtime (com.example.a.library_a:flutter_debug:1.0) and flutter_debug-2.0-runtime (com.example.b.library_b:flutter_debug:2.0)

     Go to the documentation to learn how to Fix dependency resolution errors.

Steps to reproduce;

flutter create -t module --org com.example.a library_a
cd library_a
flutter pub add android_intent_plus
flutter build aar

cd ..

flutter create -t module --org com.example.b library_b
cd library_a
flutter pub add android_intent_plus
// Open pubspec.yaml and change android_intent_plus to 1.0.1
flutter build aar --build-number=2.0

Add both library_a and library_b to an android project. (I tested with a new project)

Build fails with duplicate class.

flutter doctor;

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.10, on macOS 12.5.1 21G83 darwin-arm, locale en-DE)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[!] Android Studio
    ✗ Unable to find bundled Java version.
[!] Android Studio
    ✗ Unable to find bundled Java version.
[!] Android Studio
    ✗ Unable to find bundled Java version.
[✓] Android Studio (version 2021.3)
[!] Android Studio
    ✗ Unable to find bundled Java version.
[✓] IntelliJ IDEA Ultimate Edition (version 2022.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.3)
[✓] VS Code (version 1.74.1)
[✓] Connected device (2 available)
[✓] HTTP Host Availability


问:
Pico Pi Python - Onewire temperature sensor
I am trying to get temperature sensor to work on pico pi, using PIN 16. I got DS18X20 and onewire library from GitHub. I'm trying to get temperature reading but it shows an error.

I tried running this code:

```<code>import time
import machine
import ds18x20
import onewire

# the device is on GPIO12
dat = machine.Pin(22)

# create the onewire object
on = onewire.OneWire(dat)
ds = ds18x20.DS18X20(on)

# scan for devices on the bus
roms = ds.scan()
print('found devices:', roms)

# loop 10 times and print all temperatures
for i in range(10):
    print('temperatures:', end=' ')
    ds.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        print(ds.read_temp(rom), end=' ')
    print()

</code>```

This is DS18X0 library:

```<code>"""
DS18x20 temperature sensor driver for MicroPython.
This driver uses the OneWire driver to control DS18S20 and DS18B20
temperature sensors.  It supports multiple devices on the same 1-wire bus.
The following example assumes the ground of your DS18x20 is connected to
Y11, vcc is connected to Y9 and the data pin is connected to Y10.
>>> from pyb import Pin
>>> gnd = Pin('Y11', Pin.OUT_PP)
>>> gnd.low()
>>> vcc = Pin('Y9', Pin.OUT_PP)
>>> vcc.high()
>>> from ds18x20 import DS18X20
>>> d = DS18X20(Pin('Y10'))
Call read_temps to read all sensors:
>>> result = d.read_temps()
>>> print(result)
[20.875, 20.8125]
Call read_temp to read the temperature of a specific sensor:
>>> result = d.read_temp(d.roms[0])
>>> print(result)
20.25
If only one DS18x20 is attached to the bus, then you don't need to
pass a ROM to read_temp:
>>> result = d.read_temp()
>>> print(result)
20.25
"""

from onewire import OneWire

class DS18X20(object):
    def __init__(self, pin):
        self.ow = OneWire(pin)
        # Scan the 1-wire devices, but only keep those which have the
        # correct # first byte in their rom for a DS18x20 device.
        self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]

    def read_temp(self, rom=None):
        """
        Read and return the temperature of one DS18x20 device.
        Pass the 8-byte bytes object with the ROM of the specific device you want to read.
        If only one DS18x20 device is attached to the bus you may omit the rom parameter.
        """
        rom = rom or self.roms[0]
        ow = self.ow
        ow.reset()
        ow.select_rom(rom)
        ow.write_byte(0x44)  # Convert Temp
        while True:
            if ow.read_bit():
                break
        ow.reset()
        ow.select_rom(rom)
        ow.write_byte(0xbe)  # Read scratch
        data = ow.read_bytes(9)
        return self.convert_temp(rom[0], data)

    def read_temps(self):
        """
        Read and return the temperatures of all attached DS18x20 devices.
        """
        temps = []
        for rom in self.roms:
            temps.append(self.read_temp(rom))
        return temps

    def convert_temp(self, rom0, data):
        """
        Convert the raw temperature data into degrees celsius and return as a float.
        """
        temp_lsb = data[0]
        temp_msb = data[1]
        if rom0 == 0x10:
            if temp_msb != 0:
                # convert negative number
                temp_read = temp_lsb >> 1 | 0x80  # truncate bit 0 by shifting, fill high bit with 1.
                temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement
            else:
                temp_read = temp_lsb >> 1  # truncate bit 0 by shifting
            count_remain = data[6]
            count_per_c = data[7]
            temp = temp_read - 0.25 + (count_per_c - count_remain) / count_per_c
            return temp
        elif rom0 == 0x28:
            return (temp_msb << 8 | temp_lsb) / 16
        else:
            assert False

</code>```

This is onewire library:

```<code>#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#

"""
OneWire library for MicroPython
"""

import time
import machine

class OneWire:
    CMD_SEARCHROM = const(0xf0)
    CMD_READROM = const(0x33)
    CMD_MATCHROM = const(0x55)
    CMD_SKIPROM = const(0xcc)

    def __init__(self, pin):
        self.pin = pin
        self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP)
        print("init")

    def init(self, pin):
        self.pin = pin
        self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP)
        print("init")

    def reset(self):
        """
        Perform the onewire reset function.
        Returns True if a device asserted a presence pulse, False otherwise.
        """
        sleep_us = time.sleep_us
        disable_irq = machine.disable_irq
        enable_irq = machine.enable_irq
        pin = self.pin

        pin(0)
        sleep_us(480)
        i = disable_irq()
        pin(1)
        sleep_us(60)
        status = not pin()
        enable_irq(i)
        sleep_us(420)
        return status

    def read_bit(self):
        sleep_us = time.sleep_us
        enable_irq = machine.enable_irq
        pin = self.pin

        pin(1) # half of the devices don't match CRC without this line
        i = machine.disable_irq()
        pin(0)
        sleep_us(1)
        pin(1)
        sleep_us(1)
        value = pin()
        enable_irq(i)
        sleep_us(40)
        return value

    def read_byte(self):
        value = 0
        for i in range(8):
            value |= self.read_bit() << i
        return value

    def read_bytes(self, count):
        buf = bytearray(count)
        for i in range(count):
            buf[i] = self.read_byte()
        return buf

    def write_bit(self, value):
        sleep_us = time.sleep_us
        pin = self.pin

        i = machine.disable_irq()
        pin(0)
        sleep_us(1)
        pin(value)
        sleep_us(60)
        pin(1)
        sleep_us(1)
        machine.enable_irq(i)

    def write_byte(self, value):
        for i in range(8):
            self.write_bit(value & 1)
            value >>= 1

    def write_bytes(self, buf):
        for b in buf:
            self.write_byte(b)

    def select_rom(self, rom):
        """
        Select a specific device to talk to. Pass in rom as a bytearray (8 bytes).
        """
        self.reset()
        self.write_byte(CMD_MATCHROM)
        self.write_bytes(rom)

    def crc8(self, data):
        """
        Compute CRC
        """
        crc = 0
        for i in range(len(data)):
            byte = data[i]
            for b in range(8):
                fb_bit = (crc ^ byte) & 0x01
                if fb_bit == 0x01:
                    crc = crc ^ 0x18
                crc = (crc >> 1) & 0x7f
                if fb_bit == 0x01:
                    crc = crc | 0x80
                byte = byte >> 1
        return crc

    def scan(self):
        """
        Return a list of ROMs for all attached devices.
        Each ROM is returned as a bytes object of 8 bytes.
        """
        devices = []
        diff = 65
        rom = False
        for i in range(0xff):
            rom, diff = self._search_rom(rom, diff)
            if rom:
                devices += [rom]
            if diff == 0:
                break
        return devices

    def _search_rom(self, l_rom, diff):
        if not self.reset():
            return None, 0
        self.write_byte(CMD_SEARCHROM)
        if not l_rom:
            l_rom = bytearray(8)
        rom = bytearray(8)
        next_diff = 0
        i = 64
        for byte in range(8):
            r_b = 0
            for bit in range(8):
                b = self.read_bit()
                if self.read_bit():
                    if b: # there are no devices or there is an error on the bus
                        return None, 0
                else:
                    if not b: # collision, two devices with different bit meaning
                        if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i):
                            b = 1
                            next_diff = i
                self.write_bit(b)
                if b:
                    r_b |= 1 << bit
                i -= 1
            rom[byte] = r_b
        return rom, next_diff

class DS18X20(object):
    def __init__(self, onewire):
        self.ow = onewire
        self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]
        self.fp = True
        try:
            1/1
        except TypeError:
            self.fp = False # floatingpoint not supported

    def isbusy(self):
        """
        Checks wether one of the DS18x20 devices on the bus is busy
        performing a temperature convertion
        """
        return not self.ow.read_bit()

    def start_conversion(self, rom=None):
        """
        Start the temp conversion on one DS18x20 device.
        Pass the 8-byte bytes object with the ROM of the specific device you want to read.
        If only one DS18x20 device is attached to the bus you may omit the rom parameter.
        """
        if (rom==None) and (len(self.roms)>0):
            rom=self.roms[0]
        if rom!=None:
            rom = rom or self.roms[0]
            ow = self.ow
            ow.reset()
            ow.select_rom(rom)
            ow.write_byte(0x44)  # Convert Temp

    def read_temp_async(self, rom=None):
        """
        Read the temperature of one DS18x20 device if the convertion is complete,
        otherwise return None.
        """
        if self.isbusy():
            return None
        if (rom==None) and (len(self.roms)>0):
            rom=self.roms[0]
        if rom==None:
            return None
        else:
            ow = self.ow
            ow.reset()
            ow.select_rom(rom)
            ow.write_byte(0xbe)  # Read scratch
            data = ow.read_bytes(9)
            return self.convert_temp(rom[0], data)

    def convert_temp(self, rom0, data):
        """
        Convert the raw temperature data into degrees celsius and return as a fixed point with 2 decimal places.
        """
        temp_lsb = data[0]
        temp_msb = data[1]
        if rom0 == 0x10:
            if temp_msb != 0:
                # convert negative number
                temp_read = temp_lsb >> 1 | 0x80  # truncate bit 0 by shifting, fill high bit with 1.
                temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement
            else:
                temp_read = temp_lsb >> 1  # truncate bit 0 by shifting
            count_remain = data[6]
            count_per_c = data[7]
            if self.fp:
                return temp_read - 25 + (count_per_c - count_remain) / count_per_c
            else:
                return 100 * temp_read - 25 + (count_per_c - count_remain) // count_per_c
        elif rom0 == 0x28:
            temp = None
            if self.fp:
                temp = (temp_msb << 8 | temp_lsb) / 16
            else:
                temp = (temp_msb << 8 | temp_lsb) * 100 // 16
            if (temp_msb & 0xf8) == 0xf8: # for negative temperature
                temp -= 0x1000
            return temp
        else:
            assert False

</code>```

This is the error I'm getting:

```<code>>>> %Run -c $EDITOR_CONTENT
init
Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
  File "ds18x20.py", line 33, in __init__
  File "onewire.py", line 30, in __init__
AttributeError: 'OneWire' object has no attribute 'OPEN_DRAIN'
>>>
</code>```

I've tried multiple ways to resolve this and watched a bunch of videos on youtube, but not sure what causes this issue.

Body:
I am trying to get temperature sensor to work on pico pi, using PIN 16. I got DS18X20 and onewire library from GitHub. I'm trying to get temperature reading but it shows an error.

I tried running this code:

import time
import machine
import ds18x20
import onewire

# the device is on GPIO12
dat = machine.Pin(22)

# create the onewire object
on = onewire.OneWire(dat)
ds = ds18x20.DS18X20(on)

# scan for devices on the bus
roms = ds.scan()
print('found devices:', roms)

# loop 10 times and print all temperatures
for i in range(10):
    print('temperatures:', end=' ')
    ds.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        print(ds.read_temp(rom), end=' ')
    print()

This is DS18X0 library:

"""
DS18x20 temperature sensor driver for MicroPython.
This driver uses the OneWire driver to control DS18S20 and DS18B20
temperature sensors.  It supports multiple devices on the same 1-wire bus.
The following example assumes the ground of your DS18x20 is connected to
Y11, vcc is connected to Y9 and the data pin is connected to Y10.
>>> from pyb import Pin
>>> gnd = Pin('Y11', Pin.OUT_PP)
>>> gnd.low()
>>> vcc = Pin('Y9', Pin.OUT_PP)
>>> vcc.high()
>>> from ds18x20 import DS18X20
>>> d = DS18X20(Pin('Y10'))
Call read_temps to read all sensors:
>>> result = d.read_temps()
>>> print(result)
[20.875, 20.8125]
Call read_temp to read the temperature of a specific sensor:
>>> result = d.read_temp(d.roms[0])
>>> print(result)
20.25
If only one DS18x20 is attached to the bus, then you don't need to
pass a ROM to read_temp:
>>> result = d.read_temp()
>>> print(result)
20.25
"""

from onewire import OneWire

class DS18X20(object):
    def __init__(self, pin):
        self.ow = OneWire(pin)
        # Scan the 1-wire devices, but only keep those which have the
        # correct # first byte in their rom for a DS18x20 device.
        self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]

    def read_temp(self, rom=None):
        """
        Read and return the temperature of one DS18x20 device.
        Pass the 8-byte bytes object with the ROM of the specific device you want to read.
        If only one DS18x20 device is attached to the bus you may omit the rom parameter.
        """
        rom = rom or self.roms[0]
        ow = self.ow
        ow.reset()
        ow.select_rom(rom)
        ow.write_byte(0x44)  # Convert Temp
        while True:
            if ow.read_bit():
                break
        ow.reset()
        ow.select_rom(rom)
        ow.write_byte(0xbe)  # Read scratch
        data = ow.read_bytes(9)
        return self.convert_temp(rom[0], data)

    def read_temps(self):
        """
        Read and return the temperatures of all attached DS18x20 devices.
        """
        temps = []
        for rom in self.roms:
            temps.append(self.read_temp(rom))
        return temps

    def convert_temp(self, rom0, data):
        """
        Convert the raw temperature data into degrees celsius and return as a float.
        """
        temp_lsb = data[0]
        temp_msb = data[1]
        if rom0 == 0x10:
            if temp_msb != 0:
                # convert negative number
                temp_read = temp_lsb >> 1 | 0x80  # truncate bit 0 by shifting, fill high bit with 1.
                temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement
            else:
                temp_read = temp_lsb >> 1  # truncate bit 0 by shifting
            count_remain = data[6]
            count_per_c = data[7]
            temp = temp_read - 0.25 + (count_per_c - count_remain) / count_per_c
            return temp
        elif rom0 == 0x28:
            return (temp_msb << 8 | temp_lsb) / 16
        else:
            assert False

This is onewire library:

#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#

"""
OneWire library for MicroPython
"""

import time
import machine

class OneWire:
    CMD_SEARCHROM = const(0xf0)
    CMD_READROM = const(0x33)
    CMD_MATCHROM = const(0x55)
    CMD_SKIPROM = const(0xcc)

    def __init__(self, pin):
        self.pin = pin
        self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP)
        print("init")

    def init(self, pin):
        self.pin = pin
        self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP)
        print("init")

    def reset(self):
        """
        Perform the onewire reset function.
        Returns True if a device asserted a presence pulse, False otherwise.
        """
        sleep_us = time.sleep_us
        disable_irq = machine.disable_irq
        enable_irq = machine.enable_irq
        pin = self.pin

        pin(0)
        sleep_us(480)
        i = disable_irq()
        pin(1)
        sleep_us(60)
        status = not pin()
        enable_irq(i)
        sleep_us(420)
        return status

    def read_bit(self):
        sleep_us = time.sleep_us
        enable_irq = machine.enable_irq
        pin = self.pin

        pin(1) # half of the devices don't match CRC without this line
        i = machine.disable_irq()
        pin(0)
        sleep_us(1)
        pin(1)
        sleep_us(1)
        value = pin()
        enable_irq(i)
        sleep_us(40)
        return value

    def read_byte(self):
        value = 0
        for i in range(8):
            value |= self.read_bit() << i
        return value

    def read_bytes(self, count):
        buf = bytearray(count)
        for i in range(count):
            buf[i] = self.read_byte()
        return buf

    def write_bit(self, value):
        sleep_us = time.sleep_us
        pin = self.pin

        i = machine.disable_irq()
        pin(0)
        sleep_us(1)
        pin(value)
        sleep_us(60)
        pin(1)
        sleep_us(1)
        machine.enable_irq(i)

    def write_byte(self, value):
        for i in range(8):
            self.write_bit(value & 1)
            value >>= 1

    def write_bytes(self, buf):
        for b in buf:
            self.write_byte(b)

    def select_rom(self, rom):
        """
        Select a specific device to talk to. Pass in rom as a bytearray (8 bytes).
        """
        self.reset()
        self.write_byte(CMD_MATCHROM)
        self.write_bytes(rom)

    def crc8(self, data):
        """
        Compute CRC
        """
        crc = 0
        for i in range(len(data)):
            byte = data[i]
            for b in range(8):
                fb_bit = (crc ^ byte) & 0x01
                if fb_bit == 0x01:
                    crc = crc ^ 0x18
                crc = (crc >> 1) & 0x7f
                if fb_bit == 0x01:
                    crc = crc | 0x80
                byte = byte >> 1
        return crc

    def scan(self):
        """
        Return a list of ROMs for all attached devices.
        Each ROM is returned as a bytes object of 8 bytes.
        """
        devices = []
        diff = 65
        rom = False
        for i in range(0xff):
            rom, diff = self._search_rom(rom, diff)
            if rom:
                devices += [rom]
            if diff == 0:
                break
        return devices

    def _search_rom(self, l_rom, diff):
        if not self.reset():
            return None, 0
        self.write_byte(CMD_SEARCHROM)
        if not l_rom:
            l_rom = bytearray(8)
        rom = bytearray(8)
        next_diff = 0
        i = 64
        for byte in range(8):
            r_b = 0
            for bit in range(8):
                b = self.read_bit()
                if self.read_bit():
                    if b: # there are no devices or there is an error on the bus
                        return None, 0
                else:
                    if not b: # collision, two devices with different bit meaning
                        if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i):
                            b = 1
                            next_diff = i
                self.write_bit(b)
                if b:
                    r_b |= 1 << bit
                i -= 1
            rom[byte] = r_b
        return rom, next_diff

class DS18X20(object):
    def __init__(self, onewire):
        self.ow = onewire
        self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]
        self.fp = True
        try:
            1/1
        except TypeError:
            self.fp = False # floatingpoint not supported

    def isbusy(self):
        """
        Checks wether one of the DS18x20 devices on the bus is busy
        performing a temperature convertion
        """
        return not self.ow.read_bit()

    def start_conversion(self, rom=None):
        """
        Start the temp conversion on one DS18x20 device.
        Pass the 8-byte bytes object with the ROM of the specific device you want to read.
        If only one DS18x20 device is attached to the bus you may omit the rom parameter.
        """
        if (rom==None) and (len(self.roms)>0):
            rom=self.roms[0]
        if rom!=None:
            rom = rom or self.roms[0]
            ow = self.ow
            ow.reset()
            ow.select_rom(rom)
            ow.write_byte(0x44)  # Convert Temp

    def read_temp_async(self, rom=None):
        """
        Read the temperature of one DS18x20 device if the convertion is complete,
        otherwise return None.
        """
        if self.isbusy():
            return None
        if (rom==None) and (len(self.roms)>0):
            rom=self.roms[0]
        if rom==None:
            return None
        else:
            ow = self.ow
            ow.reset()
            ow.select_rom(rom)
            ow.write_byte(0xbe)  # Read scratch
            data = ow.read_bytes(9)
            return self.convert_temp(rom[0], data)

    def convert_temp(self, rom0, data):
        """
        Convert the raw temperature data into degrees celsius and return as a fixed point with 2 decimal places.
        """
        temp_lsb = data[0]
        temp_msb = data[1]
        if rom0 == 0x10:
            if temp_msb != 0:
                # convert negative number
                temp_read = temp_lsb >> 1 | 0x80  # truncate bit 0 by shifting, fill high bit with 1.
                temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement
            else:
                temp_read = temp_lsb >> 1  # truncate bit 0 by shifting
            count_remain = data[6]
            count_per_c = data[7]
            if self.fp:
                return temp_read - 25 + (count_per_c - count_remain) / count_per_c
            else:
                return 100 * temp_read - 25 + (count_per_c - count_remain) // count_per_c
        elif rom0 == 0x28:
            temp = None
            if self.fp:
                temp = (temp_msb << 8 | temp_lsb) / 16
            else:
                temp = (temp_msb << 8 | temp_lsb) * 100 // 16
            if (temp_msb & 0xf8) == 0xf8: # for negative temperature
                temp -= 0x1000
            return temp
        else:
            assert False

This is the error I'm getting:

>>> %Run -c $EDITOR_CONTENT
init
Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
  File "ds18x20.py", line 33, in __init__
  File "onewire.py", line 30, in __init__
AttributeError: 'OneWire' object has no attribute 'OPEN_DRAIN'
>>>

I've tried multiple ways to resolve this and watched a bunch of videos on youtube, but not sure what causes this issue.


问:
Is it possible to set accessibility labels on system provided UIActivity items in UIActivityViewController?
When I use Accessibility Inspector to inspect the reminders and more buttons in the UIActivityViewController their labels are both simply "Activity". Is it possible to change these labels?

I don't see anywhere in the documentation where you can get a reference to the system provided UIShareGroupActivityCell items.


问:
top level must be a YAML sequence error in ROS2 even with YAML being a sequence
This YAML file is being passed into the ros_gz_bridge parameter_bridge as a config_file and I am getting an error saying:
Could not parse config, top level must be a YAML sequence

Is there something wrong with the layout of this YAML file? Even when I try to submit the test YAML config file that is in the documentation I still get the error.

    - topic_name: "lidar"
      ros_type_name: "sensor_msgs/msg/LaserScan"
      gz_type_name: "gz.msgs.LaserScan"

    - topic_name: "cmd_vel"
      ros_type_name: "geometry_msgs/msg/Twist"
      gz_type_name: "gz.msgs.Twist"

    - topic_name: "imu"
      ros_type_name: "sensor_msgs/msg/Imu"
      gz_type_name: "gz.msgs.IMU"

    - topic_name: "navsat"
      ros_type_name: "sensor_msgs/msg/NavSatFix"
      gz_type_name: "gz.msgs.NavSat"

    - topic_name: "navsat"
      ros_type_name: "sensor_msgs/msg/NavSatFix"
      gz_type_name: "gz.msgs.NavSat"

    - ros_topic_name: "odometry"
      gz_topic_name: "model/f1tenth/odometry"
      ros_type_name: "nav_msgs/msg/Odometry"
      gz_type_name: "gz.msgs.Odometry"

    - ros_topic_name: "tf"
      gz_topic_name: "model/f1tenth/tf"
      ros_type_name: "f2_msgs/msg/TFMessage"
      gz_type_name: "gz.msgs.Pose_V"
```


问:
How to prevent link click on slider until it’s in center position?
I need to suspend click events of a link block with a class of "album-link" unless the parent div contains the class, "is-active". then it can be clickable

In my test codepen I am able to get e.preventdefault() to work. You can only click the link that has “is-active”

```<code>
$(".is-album a").click(function (e) {
  if ($(".is-album a").parent().hasClass("is-active")) {
return true
  } else {
    e.preventDefault();
  }
});

</code>```

I’m suspecting that “is active” is being added before the slide reaches the center.

you can click to navigate the albums currently, but Goblin Mode is hyperlinked and if you click that one (when it’s in the left or right position) to slide over, it jumps to another page.

I need goblin mode to slide to the center first. And then with a second click, go to the next page.

How can I achieve this?
https://hab-playlist.webflow.io/

```<code>
$(".is-album a").click(function (e) {
  if ($(".is-album a").parent().hasClass("is-active")) {
return true
  } else {
    e.preventDefault();
  }
});

</code>```

Works in a static codepen, but not with the slider.

Body:
I need to suspend click events of a link block with a class of "album-link" unless the parent div contains the class, "is-active". then it can be clickable

In my test codepen I am able to get e.preventdefault() to work. You can only click the link that has “is-active”

$(".is-album a").click(function (e) {
  if ($(".is-album a").parent().hasClass("is-active")) {
return true
  } else {
    e.preventDefault();
  }
});

I’m suspecting that “is active” is being added before the slide reaches the center.

you can click to navigate the albums currently, but Goblin Mode is hyperlinked and if you click that one (when it’s in the left or right position) to slide over, it jumps to another page.

I need goblin mode to slide to the center first. And then with a second click, go to the next page.

How can I achieve this?
https://hab-playlist.webflow.io/

$(".is-album a").click(function (e) {
  if ($(".is-album a").parent().hasClass("is-active")) {
return true
  } else {
    e.preventDefault();
  }
});

Works in a static codepen, but not with the slider.