instruction stringlengths 0 30k ⌀ |
|---|
I'm trying to enter drawer into iframe in the component of react And for some reason it doesn't show it to me In the Iframe When I look in the dev tools the <body> that within the Iframe is empty
This is the code snippet:This is the code snippet:
```
<iframe >
<Drawer open={open} onClose={toggleDrawer(false)}>
<List>
<ListItem disablePadding>
<ListItemButton>
<ListItemText primary={'nenu'} />
</ListItemButton>
</ListItem>
</List>
</Drawer>
</iframe>
```
|
Why a component? Drawer of mui Does not work inside Iframe |
|reactjs|iframe|material-ui|drawer| |
null |
|google-api|youtube|youtube-api|api-key| |
|python|sparkpost| |
|javascript|json| |
{"Voters":[{"Id":23917386,"DisplayName":"Казаков Денис"}]} |
{"Voters":[{"Id":14098260,"DisplayName":"Alexander Nenashev"},{"Id":16540390,"DisplayName":"jabaa"},{"Id":3689450,"DisplayName":"VLAZ"}]} |
{"OriginalQuestionIds":[61392633],"Voters":[{"Id":17865804,"DisplayName":"Chris","BindingReason":{"GoldTagBadge":"fastapi"}}]} |
|python|django|pip| |
I am trying to click on a specific color then click buy button, I find color and can click on them, but buy element can not be found. I try some locator like XPATH, CSS_SELECTOR and others.
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Edge()
driver.maximize_window()
driver.get("https://www.digikala.com/product/dkp-4645665/")
try:
main_div = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "div.flex.lg\\:flex-wrap.overflow-x-auto.px-5.lg\\:px-0"))
)
child_elements = main_div.find_elements(By.CSS_SELECTOR, "div.bg-neutral-000.flex.items-center\
.justify-center.cursor-pointer.ml-2.px-2.lg\\:px-0.styles_InfoSectionVariationColor__pX_3M")
specific_value = "سفید"
add_to_cart= WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "button[data-testid='add-to-cart']"))
)
for child in child_elements:
time.sleep(1)
if child.text == specific_value:
add_to_cart.click()
break
except Exception as e:
print("Exception:", e)
finally:
driver.quit()
``` |
{"Voters":[{"Id":1431750,"DisplayName":"aneroid"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":14732669,"DisplayName":"ray"}]} |
.html:
<a id="my-toggle-button" class="nav-link" data-widget="control-sidebar" (click)="toggleSideBar()">Toggle Control Sidebar</a>
.ts:
toggleSideBar() {
$("#my-toggle-button").ControlSidebar('toggle');
}
Based on docs at https://adminlte.io/docs/3.0/javascript/control-sidebar.html
To be honest, you should be using @ViewChild here to access the HTML element but you may be restricted by your choice of library.
But seriously! This library is a really bad choice for a dashboard. It's old and jQuery focused. You want something tailored for Angular. Look at https://akveo.github.io/ngx-admin/.
According to https://risingstars.js.org/2020/en#section-angular ngx-admin is the #1 Angular library and will make your life much easier.
|
I know that some other people have pointed out the fact that you can run pip with a proxy, but I'd like to point out that you can do this "globally" too. I am developing in an Ubuntu 20 VM, and for me, running
export http_proxy=[proxy info]
export https_proxy=[proxy info]
pip install flask
worked. |
I'm working with a new Javafx project. I have legacy swing control panels. When I try to do "new SwingNode", I get an exception:
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.embed.swing.SwingNodeHelper (in unnamed module @0x35dc99d5) cannot access class com.sun.javafx.scene.NodeHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene to unnamed module @0x35dc99d5
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1027)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)
at javafx.embed.swing.SwingNode.<clinit>(SwingNode.java:135)
at test.app.MJFXtest.start(MJFXtest.java:11)
this is on javafx v21. I tried 19, but still the same.
_______________
```
package test.app;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.embed.swing.SwingNode;
public class MJFXtest extends Application {
@Override
public void start(Stage primaryStage) {
SwingNode sn = new SwingNode();
}
public static void main(String[] args) {
launch(args);
}
}
```
_________________
I expect this not to throw an exception on the new SwingNode(); line, but to create a new SwingNode.
I saw this Q/A about the same problem, but I have javafx-swing included in my pom file.
([https://stackoverflow.com/questions/55874607/the-class-swingnode-in-openjfx-causes-problems](https://stackoverflow.com))
This is the javafx section from pom.xml and it looks like all the relevant libraries are there.
```
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>21</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-swing -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-web -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>21</version>
<type>pom</type>
</dependency>
```
Any assistance would be appreciated. Thank you. |
Escape output, not filter the input? |
|php| |
null |
You can use the following function:
```cs
int ShiftOneBit(int value, int bit)
{
return (value & ~bit) | ((value & bit) >> 1);
}
```
Then use it like this
```cs
x = ShiftOneBit(x, 0b100);
x = ShiftOneBit(x, 0b10000);
``` |
After a painstaking few hours, I have got my tests passing correctly and posting as JSON by doing the following:
require 'rails_helper'
RSpec.describe RegistrationsController, type: :controller do
before :each do
request.env['devise.mapping'] = Devise.mappings[:user]
end
context 'Adding a Valid User' do
it 'Returns Success Code and User object' do
json = { user: { username: "richlewis14", school: "Baden Powell", email: "richlewis14@gmail.com", password: "Password1", password_confirmation: "Password1"}}.to_json
post :create, json
expect(response.code).to eq('201')
end
end
end
My routes are back to normal:
Rails.application.routes.draw do
constraints(subdomain: 'api') do
devise_for :users, path: 'lnf', controllers: { registrations: "registrations" }
end
end
And in my test environment I had to add:
config.action_mailer.default_url_options = { host: 'localhost' }
The key here was:
request.env['devise.mapping'] = Devise.mappings[:user]
Not fully sure as yet to what it does, it's next on my list to find out, but my tests are starting to run and pass.
|
To resolve the issue with mounting the volume in Podman, you can use the -e **PGDATA=./pgdata** in the Podman command.
This will set the PGDATA environment variable to a path within the container that Podman has permission to access. |
I have a bar chart with dates as the x axis
[![enter image description here][1]][1]
I need to highlight the weekends with a different colour.
In my calendar table I have a true/false column for if a date is a weekend
[![enter image description here][2]][2]
But I can't find within the conditional formatting of the columns anywhere to be able to use this.
When I pick rules it only gives me *count of weekend* not just a classic conditional statement of if(Weekend=TRUE) -> make column blue
Help would be appreciated.
**EDIT**
I've changed the Type to be categorical instead of continuous and got this
[![enter image description here][3]][3]
Which is a lot uglier as I'm not sure how to have fewer labels and I've changed the data type to Text (from True/False) and I have "Don't Summarize" for data summarization but conditional still gives:
[![enter image description here][4]][4]
It still has a summarize of either first or last which I can't remove
---------------------------------------------------------------------
SOLUTION.
I followed Jonathan's suggestion of splitting them out.
I created two new measures, one for total of work - weekends and another for the same as weekdays.
[![enter image description here][5]][5]
[![enter image description here][6]][6]
(I then modified my "Total Hours Worked" to just add these two values so I still had a total).
[![enter image description here][7]][7]
This then allowed me to have put in each as a separate value on my chart giving the result I wanted.
[![enter image description here][8]][8]
(I have renamed these for the sake of the graph but they're just - Total Weekday Hours worked)
[![enter image description here][9]][9]
[1]: https://i.stack.imgur.com/fvXsj.png
[2]: https://i.stack.imgur.com/E31yt.png
[3]: https://i.stack.imgur.com/aAi6p.png
[4]: https://i.stack.imgur.com/ZyFjz.png
[5]: https://i.stack.imgur.com/a0SUS.png
[6]: https://i.stack.imgur.com/gG9vn.png
[7]: https://i.stack.imgur.com/cKAiY.png
[8]: https://i.stack.imgur.com/6VJVC.png
[9]: https://i.stack.imgur.com/GlqD6.png |
bcrypt.compare receiving illegal argument string, undefined |
|javascript|node.js|express|bcryptjs| |
null |
I have 2 SQL queries.
Query #1:
SELECT
SUM(PrincipalBalance)
FROM
(SELECT
lt.AccountId,
SUM(CASE
WHEN TransactionTypeId IN (1)
THEN PrincipalPortionAmount
ELSE 0
END)
- SUM(CASE
WHEN TransactionTypeId NOT IN (1, 2)
THEN PrincipalPortionAmount
ELSE 0
END) AS PrincipalBalance
FROM
program.LoanTransaction lt
INNER JOIN
program.LoanAccount la ON lt.AccountId = la.Id
WHERE
BranchId = 301
AND TransactionDate <= 20231231000000
AND la.STATUS <> - 1
GROUP BY
lt.AccountId
HAVING
SUM(Debit - Credit) > 1) T
Query #2:
SELECT
ISNULL(SUM(CASE
WHEN TransactionTypeId IN (1)
THEN PrincipalPortionAmount
ELSE 0
END), 0)
- ISNULL(SUM(CASE
WHEN TransactionTypeId IN (43, 38, 4, 12, 7, 10)
THEN PrincipalPortionAmount
ELSE 0
END), 0)
FROM
program.LoanTransaction lt
INNER JOIN
program.LoanAccount la ON lt.AccountId = la.Id
WHERE
BranchId = 301
AND TransactionDate <= 20231231000000
AND la.Status <> -1
Query #1 result is<br> `80773498.0599999`
Query #2 result is<br> `81060946.8400006`
But both results should be the same. I don't get it, why the differences? How can I find out what is causing the differences?
|
{"Voters":[{"Id":147356,"DisplayName":"larsks"},{"Id":5641244,"DisplayName":"Levi Ramsey"},{"Id":3929826,"DisplayName":"Klaus D."}]} |
here's a slightly cleaner code,
```
// choosing is based on the assumption
// that the head is the last element in the body array
// if not, you can simply reverse the conditions
if (next == /*last in body*/) {
spriteName == "head_sprite";
} else if (next == /*first in body*/) {
spriteName = "tail_sprite";
} else if (next.x == prev.x || next.y == prev.y) {
spriteName == "body_sprite";
} else {
spriteName = "curved_sprite";
}
// now rotate and reverse
if (prev.x == next.x) {
// rotate 90deg
} else if (prev.x > next.x) {
// reverse horizontally
}
if (prev.y > next.y) {
// reverse vertically
}
```
it's much more convenient to rotate/reverse the sprite than choosing individual sprites based on each case.
i have selected from the snake_graphics.zip you attached those sprites
> ["head_down", "tail_down", "body_vertical", "body_bottomright"]
and renamed them to
> ["head_sprite", "tail_sprite", "body_sprite", "curved_sprite" ]
respectively.
i possibly might have mistaken in rotating/reversing the sprite
as i don't know for sure whether prev or next is the current ("assumed prev is"), but that's the basic idea
|
It seems like you're encountering an issue with Redux Toolkit and how you're defining your initial state and handling the data in your reducer. Let's take a closer look at your code.
Firstly, in your formSlice, you're defining initialState as an empty object, but then in your extraReducers, you're trying to directly access state.data. This would throw an error because initially, state is an empty object.
To fix this, you should define your initialState with the correct structure. In your case, it should match the structure of the state you're trying to update in your reducer. So, it should look like this:
const initialState = {
data: [],
status: 'idle',
error: null
};
Secondly, in your useSelector hook, you're accessing state.data, but since you've named your slice as 'data', you should access it like state.data.data.
Here's how you can adjust your useSelector:
const data = useSelector((state) => state.data.data);With these changes, your code should work properly. If you still encounter any issues, please let me know! |
How to detect 2 drag gestures independently in Jetpack Compose? |
|android|android-jetpack-compose| |
I hope you're all doing well. I've been working on addressing a specific constraint in OPL and attempted to write code to solve it. However, it's not functioning as expected. Could anyone provide guidance on the correct approach to do that.
Here is the constraint:
[![constraint image][1]][1]
```
range J = 1..5;
range R = 1..3;
range T = 1..10;
int P[J] = [0,1,2,3,4];
int d[J] = [1, 1, 3, 5, 2];
int EF[J] = [1, 2, 1, 1, 1];
int LF[J] = [2, 3, 4, 6, 2];
subject to {
forall(j in J, i in P[j])
sum (t in EF[j]..LF[j]) (t - d[j]) * x[j][t] - sum (t in EF[i]..LF[i]) t * x[i][t] >= 0;
}
```
I've attempted to apply my knowledge in OPL to address this issue, but I'm encountering difficulties. I would appreciate any advice on how to resolve this.
[1]: https://i.stack.imgur.com/ZyWkk.png |
null |
{"Voters":[{"Id":635608,"DisplayName":"Mat"},{"Id":3440745,"DisplayName":"Tsyvarev"},{"Id":2422778,"DisplayName":"Mike Szyndel"}],"SiteSpecificCloseReasonIds":[18]} |
[This is how it is coming](https://i.stack.imgur.com/QpU3A.png)
I was just trying to run HTML Code on vs code through google chrome. Its working correctly on other browsers. What can be the problem, the other html files are running correctly which I have made before.
|
Whenever I am running my VS HTML Code in chrome through go live, the html content is shown in some strange characters. What might be the problem? |
|html| |
null |
I have an array list of Location objects that I want to find the max and min value of. However, when calling collections.max(listN, PopulationComparator) it gives me the minimum value whereas for collection.min() it returns the max value. The problem is resolved once changing the order to be descending, but I don't understand why this would even matter.
static class PopulationComparator implements Comparator <Location>{
public int compare(Location a, Location b){
// ascending order
if(a.getPop() > b.getPop()){
return 1;
}else if(a.getPop() < b.getPop()){
return -1;
}else{
return 0;
}
}
}
public static void main(String[] args){
Location maxPopulation = Collections.max(listN, new PopulationComparator());
}
|
Python's `zip_longest` function creates an object that allows you to iterate over collections of data (i.e. iterator), that concatenates the elements from each iteration. The iteration continues until the longest iteration is exhausted. By default, a `"None"` value is used as the empty fill-value of a `zip_longest` function, but we can use the string `"UNKNOWN"` here for a nicer formatting and for our own purposes.
Here's the code:
from itertools import zip_longest
prims = ["CubeA", "CubeB", "CubeC"]
sizes = [50, 100]
animations = [True, False]
for prim, size, animated in zip_longest(prims, sizes, animations, fillvalue="UNKNOWN"):
print(prim, "has a size", size, "and animated:", animated)
---
### Results ###
# CubeA has a size 50 and animated: True
# CubeB has a size 100 and animated: False
# CubeC has a size UNKNOWN and animated: UNKNOWN |
Shopify theme edit to change bundles copy |
|shopify| |
null |
I expect nesting parallel structures to not yield any additional speed-up. You can assign a number of workers to the outer parallellisation, which doesn't leave any room to use even more workers from outside the current, already parallel, outer level. In any case, [it's recommended to parallelise the *outermost* loop][1] in case of nested loops, I expect the same to hold true for nesting other parallellisation structures.
In case your outer structure only contains two elements (i.e. your `idx` is `2`), you might be better off by serially evaluating that loop and using parallellisation on the reading, since you've already verified that that does indeed use more workers and thus reduces execution time.
There's a bunch of background links on how and when to leverage parallellisation in [this answer of mine][2] as well as [this one][3].
There's an example in the [`parfeval` docs][4] that updates a UI, that might be worth a try. Alternatively, you could try `spmd()` to parallellise your reading and assign a limited number of workers to each SPMD. Given you have two sockets with 6 workers each, I'd set the number of workers to 6, leaving a single socket for the main thread:
```lang-matlab
parpool(6)
spmd
your_code()
end
```
[1]:https://mathworks.com/help/parallel-computing/nested-parfor-loops-and-for-loops.html
[2]:https://stackoverflow.com/a/72527420/5211833
[3]:https://stackoverflow.com/a/32146700/5211833
[4]:https://ch.mathworks.com/help/parallel-computing/parallel.pool.parfeval.html;jsessionid=f754d31761563b9c189c8970882b#mw_56da3b6f-532f-45bf-bd30-4b01f5f64bf3 |
I try to use langchain load_evaluator() with local llm Ollama. But I don't understand which model I should use.
` `from langchain.evaluation import load_evaluator
` `from langchain.chat_models import ChatOllama
` `from langchain.llms import Ollama
` `from langchain.embeddings import HuggingFaceEmbeddings
#This is work
` `evaluator = load_evaluator("labeled_score_string", llm=ChatOllama(model="llama2"))
` `evaluator = load_evaluator("pairwise_string", llm=Ollama(model="llama2"))
#This is not
` `evaluator = load_evaluator("pairwise_embedding_distance", llm=HuggingFaceEmbeddings())
` `evaluator = load_evaluator("pairwise_embedding_distance", llm=Ollama(model="llama2"))
|
How to use langchain load_evaluator() with local llm? |
|langchain|large-language-model| |
null |
I'm working on a welcome screen and it can navigate 5 pages displayed using "Frame" control in the main window.
Now I need to x:bind some controls to the viewmodel of main window cause I don't want to create 5 viewmodels for all 5 pages. So how to implement this? Or how to pass the view model object of main window to 5 pages
Main window: WelcomeScreen.xaml
<Window
x:Class="WelcomeScreen.WelcomeScreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WelcomeScreen"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="">
<Grid ColumnDefinitions="*,*,*" RowDefinitions="*" >
<StackPanel Grid.Column="0" Grid.ColumnSpan="3" Orientation="Vertical" >
<Frame x:Name="NavigationFrame" />
<Line Stroke="LightGray" X1="0" Y1="0" X2="1200" Y2="0" StrokeThickness="2" Margin="12,0,12,0"/>
<RelativePanel>
<CheckBox x:Name="DoNotShowAaginCheckBox" Content="Don't show this again" FontFamily="{StaticResource VeneerFont}" Checked="{x:Bind ViewModel.OnChecked}" Unchecked="{x:Bind ViewModel.OnChecked}" Visibility="{x:Bind ViewModel.IsCheckBoxVisible,Mode=OneWay}" Margin="12,12,0,0" RelativePanel.AlignLeftWithPanel="True" />
<Button x:Name="BackButton" Width="100" Style="{StaticResource AccentButtonStyle}" FontFamily="{StaticResource VeneerFont}" Click="{x:Bind ViewModel.BackButton_Click}" RelativePanel.AlignLeftWithPanel="True" Content="Back" Visibility="{x:Bind ViewModel.IsBackButtonVisible,Mode=OneWay}" Margin="12,12,12,0"/>
<PipsPager x:Name="PipsPager" Margin="0,15,0,0" NumberOfPages="{x:Bind ViewModel.WelcomeScreenPageList.Count}" SelectedPageIndex="{x:Bind ViewModel.CurrentPageIndex, Mode=TwoWay}" RelativePanel.AlignHorizontalCenterWithPanel="True" SelectedIndexChanged="Pager_SelectedIndexChanged" />
<Button x:Name="NextButton" Width="100" Style="{StaticResource AccentButtonStyle}" FontFamily="{StaticResource VeneerFont}" Click="{x:Bind ViewModel.NextButton_Click}" Content="{x:Bind ViewModel.NextButtonText,Mode=OneWay}" RelativePanel.AlignRightWithPanel="True" Margin="0,12,12,0"/>
</RelativePanel>
</StackPanel>
</Grid>
</Window>
WelcomeScreen.xaml.cs:
public sealed partial class WelcomeScreen : Window
{
internal WelcomeScreenPageViewModel ViewModel { get; set; }
public WelcomeScreen(object viewModel) : this()
{
if (viewModel == null || viewModel.GetType() != typeof(WelcomeScreenPageViewModel))
return;
ViewModel = viewModel as WelcomeScreenPageViewModel;
}
public WelcomeScreen()
{
this.InitializeComponent();
this.InitializeControls();
}
public void Pager_SelectedIndexChanged(object sender,PipsPagerSelectedIndexChangedEventArgs e)
{
bool isForward = false;
if (ViewModel.CurrentPageIndex > ViewModel.PreviousPageIndex)
isForward = true;
ViewModel.PreviousPageIndex = ViewModel.CurrentPageIndex;
Type pagetype = Type.GetType(ViewModel.WelcomeScreenPageList[ViewModel.CurrentPageIndex]);
if (isForward)
{
NavigationFrame.Navigate(pagetype,
null,
new SlideNavigationTransitionInfo()
{ Effect = SlideNavigationTransitionEffect.FromRight });
}
else
{
NavigationFrame.Navigate(pagetype,
null,
new SlideNavigationTransitionInfo()
{ Effect = SlideNavigationTransitionEffect.FromLeft });
}
ViewModel.UpdateControls();
}
}
Page1:
<Page
x:Class="WelcomeScreen.WelcomeScreenPage1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WelcomeScreen"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource SystemControlBackgroundChromeWhiteBrush}">
<Grid ColumnDefinitions="*" RowDefinitions="*,*" >
HorizontalAlignment="Right" Grid.Row="0" Margin="0,5,5,0"/>
<StackPanel Orientation="Horizontal" Grid.Row="1">
<TextBlock x:Name="PageText" Text="{x:Bind WelcomeScreenPageViewModel.xxx? , Mode=OneWay}""/>
</StackPanel>
</Grid>
</Page>
WelcomeScreenPage1.xaml.cs:
public sealed partial class WelcomeScreenPage1 : Page
{
public WelcomeScreenPage1()
{
this.InitializeComponent();
}
} |
x:bind a embeded page to the parent window viewmodel in WinUi 3 |
|c#|mvvm|binding|winui-3|xbind| |
I have the same error.
And I change the build.gradle.kts file imports and activity imports. Its work fine now.
in graddle I add the:
dependencies {
val composeVersion = "1.4.2"
implementation("androidx.compose.material:material:$composeVersion")
}
In activity or composable file Text import should be like:
import androidx.compose.material.Text
|
How can I find a button element and click on it? |
|python|selenium-webdriver|web-scraping|selenium-chromedriver| |
null |
|django|django-rest-framework|django-views|active-model-serializers| |
want to import HuggingFaceInferenceAPI.
from llama_index.llms import HugggingFaceInferenceAPI
llama_index.llms documentation doesn't have HugggingFaceInferenceAPI module. Anyone has update on this? |
You can use [chess][1] flutter package
[1]: https://pub.dev/packages/chess
String move1 = 'e3';
String move2 = 'e4';
final success = chess.move(<String, String?>{
'from': move1,
'to': move2,
});
and check if success is true or false. |
|reactjs|onclick|astrojs| |
This is the column part which i have declared.
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: (_,{tags})=>{
<>
{tags.map((tag)=>{
return(
<Tag key={tag}>{tag}</Tag>
);
})}
</>
}
}
I have tried the code too that is given in antd official site. why this way doesn't work? |
Why I can't render items of an array in table data in react |
|reactjs| |
null |
I am trying to temporary switch node version to the second version lists in `.tool-versions` file but I was not able to find any options for this.
```shell
$ cat .tool-versions
nodejs 18.19.1 20.11.1
```
This is problematic because I have a CI pipeline that is uspposed to run using the alternative version, and the exact version is mentioned only in `.tool-versions.`
Running `asdf list nodejs` returns all available versions, so it might include other version not listed in `.tool-versions` and I do not want to accidentally use these. |
How to tell asdf to select the second version of nodejs from inside .tools-versions |
|asdf|asdf-vm| |
Bonjour j ai téléchargé pokemon infinite fusion mais quand je joue au debut cela m affiche incompatible marshal fil format. Comment puis je faire ?
J ai lancer une fois la partie tout etais correct puis le lendemain cela me l as afficher
J attend de l aide . |
Format version 4.8 required |
|java| |
null |
Hey guys I am trying to sum the values of the 100th row of a SAS data set ,I created using the randfun function this is the code i have ,am i doing something wrong?
Q1A=X[+,100];
print Q1A;
The log says ERROR: (execution) Invalid operand to operation. |
The settings I had worked. I think it took some time to reflect and I had to look at a different blog post to see the image uploaded due to the updated config of media_folder and public_folder.
https://blogs.neelamegam.in/2024-03-24-blogging-from-netlify-cms-what-a-wonder/ |
You can extend the `Error` class to create an error type whose constructor expects an argument of type `never`:
```
class NeverError extends Error {
constructor(check: never) {
super(`NeverError received unexpected value ${check}, type should have been never.`)
this.name = 'NeverError'
}
}
```
Then you can throw the error, and if `job` isn't `never` it'll also raise a compiler error:
```
if (job.type === 'add') {
add(job)
} else if (job.type === 'send') {
send(job)
} else {
throw new NeverError(job)
}
``` |
It appears that you are using one of the older container images in SageMaker, which may lead to compatibility issues.
This error typically arises when Node is being installed on an operating system whose GLIBC version does not meet Node's minimum requirements. For example, Node v18 needs GLIBC version 2.7 or newer. Consequently, attempting to install Node v18.x on a Linux OS that is using an older GLIBC version will result in these kind of errors.
To identify the GLIBC version available in your current container, execute the `ldd` command in a terminal.
```
ldd --version
```
To overcome this issue, consider switching to the [new SageMaker Studio experience][1] and use the [SageMaker Distribution image][2]. The SageMaker Distribution image not only offers significantly quicker startup times compared to SageMaker Studio Classic but also includes an updated version of GLIBC.
To install Node v18 on the SageMaker Distribution image, you'd only need to run the following:
```
sudo apt-get install -y nodejs
```
Alternatively, you also have the option to either create your own custom image that includes a more recent version of Linux and GLIBC or to install Node from source code. However, both approaches may require more effort than using the SageMaker distribution image.
[1]: https://aws.amazon.com/blogs/machine-learning/experience-the-new-and-improved-amazon-sagemaker-studio/
[2]: https://aws.amazon.com/blogs/machine-learning/sagemaker-distribution-is-now-available-on-amazon-sagemaker-studio/ |
First of all, the easiest way to use [`getResource`][1] is to put the resource in the same folder as the associated *.class* file. In your case that would mean putting files *kitty.gif* and *kuronomi.gif* in the same folder as file *hellokitty.class*. Then the URL of the resource can be obtained by calling:
```java
getClass().getResource("kitty.gif");
```
But even after you successfully obtain the resource, scaling the image as you do in your code will not work<sup>1</sup>. I am referring to these lines of your code:
```java
Image KittyImg = new ImageIcon(getClass().getResource("kitty.gif")).getImage();
kittyIcon = new ImageIcon(KittyImg.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH));
```
Instead I used `BufferedImage`. Refer to [Why getScaledInstance() does not work?][2]
Here is my rewrite of your code – including a `main` method that uses a [lambda expression][3]. Also I changed some of the [identifiers][4] so that they adhere to [Java naming conventions][5].
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class HelloKitty {
int screenWidth = 700;
int screenHeight = 800;
JFrame frame = new JFrame("Catch Hello Kitty!");
JLabel textL = new JLabel();
JPanel textP = new JPanel();
JPanel boardP = new JPanel();
JButton[] board = new JButton[9];
ImageIcon kittyIcon;
ImageIcon kuroIcon;
JButton currentKittyTile;
JButton currentKurTile;
Random r = new Random();
Timer setKittyTimer;
Timer setKuroTimer;
HelloKitty() {
// frame.setVisible(true);
frame.setSize(screenWidth, screenHeight);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
textL.setFont(new Font("Comic Sans MS", Font.PLAIN, 70));
textL.setHorizontalAlignment(JLabel.CENTER);
textL.setText("Score: 0");
textL.setOpaque(true);
textP.setLayout(new BorderLayout());
textP.add(textL);
frame.add(textP, BorderLayout.NORTH);
boardP.setLayout(new GridLayout(3, 3));
boardP.setBackground(Color.pink);
frame.add(boardP);
URL url = getClass().getResource("kitty.gif");
URL url2 = getClass().getResource("kuronomi.gif");
try {
Image img = ImageIO.read(url);
Image kittyImg = img.getScaledInstance(150, 150, Image.SCALE_SMOOTH);
kittyIcon = new ImageIcon(kittyImg);
Image img2 = ImageIO.read(url2);
Image kuronomiImg = img2.getScaledInstance(150, 150, Image.SCALE_SMOOTH);
kuroIcon = new ImageIcon(kuronomiImg);
for (int i = 0; i < 9; i++) {
JButton tile = new JButton();
board[i] = tile;
boardP.add(tile);
tile.setFocusable(false);
}
}
catch (IOException xIo) {
throw new RuntimeException(xIo);
}
setKittyTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentKittyTile != null) {
currentKittyTile.setIcon(null);
currentKittyTile = null;
}
int num = r.nextInt(9);
JButton tile = board[num];
currentKittyTile = tile;
currentKittyTile.setIcon(kittyIcon);
}
});
setKuroTimer = new Timer(1500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentKurTile != null) {
currentKurTile.setIcon(null);
currentKurTile = null;
}
int num = r.nextInt(9);
JButton tile = board[num];
currentKurTile = tile;
currentKurTile.setIcon(kuroIcon);
}
});
setKittyTimer.start();
setKuroTimer.start();
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new HelloKitty());
}
}
```
Here is a screen capture of the running app. Of-course the tiles that contain images change all the time due to your [timers][6].
[![screen capture][7]][7]
Now I guess you need to write [`ActionListener`][8]s to update the score whenever the user successfully "whacks a mole".
<sup>1</sup>I could not discover why.
[1]: https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html
[2]: https://stackoverflow.com/questions/33313911/why-getscaledinstance-does-not-work
[3]: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
[4]: https://stackoverflow.com/questions/29311723/what-are-identifiers-in-java-exactly
[5]: https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html
[6]: https://docs.oracle.com/javase%2Ftutorial%2Fuiswing%2F%2F/misc/timer.html
[7]: https://i.stack.imgur.com/rQfUg.png
[8]: https://docs.oracle.com/javase%2Ftutorial%2Fuiswing%2F%2F/events/actionlistener.html |
I have a large dataset of this format. I would like to
a) identify those IDs/rows with the following sequence of values 1 - 1 - >1 - >1 anywhere between x1 and x10; and
b) generate a new variable ("event") that identifies the beginning of the sequence, taking the value X1,...,X10.
```
my_df <- data.frame(ID = c("a","b","c","d","e","f","g","h"),
replicate(8,sample(1:4,8,rep=TRUE)))
```
For a), I have replaced values >1 with 2, then pasted the values from X1 to X10, and then filtered for the sequence 1 - 1 - 2 - 2. For b), I created the variable "event" using nested ifelse() to identify where the sequence begins. This works ok with only 8 columns.
Is there a way to increase efficiency for datasets with more columns?
I highly appreciate any pointers!
```
df_seq <- my_df%>%
mutate_at(vars(starts_with('X')), funs(ifelse(. > 1, 2, .)))%>%
mutate(seq = paste(X1,"-",X2,"-",X3,"-",X4,"-",X5,"-",X6,"-",X7,"-",X8))%>%
filter(grepl("1 - 1 - 2 - 2", seq))%>%
mutate(event = ifelse(X1 == 1 & X2 == 1 & X3 == 2 & X4 == 2,"X1",
ifelse(X2 == 1 & X3 == 1 & X4 == 2 & X5 == 2,"X2",
ifelse(X3 == 1 & X4 == 1 & X5 == 2 & X6 == 2,"X3",
ifelse(X4 == 1 & X5 == 1 & X6 == 2 & X7 == 2,"X4","X5")))))
``` |
A solution with 3.9+ code is:
from typing import Annotated
import typer
def main(
named_arg1: Annotated[str, typer.Option("--named_arg1")],
misc_args: Annotated[list[str], typer.Argument()] = None,
):
for misc_arg in misc_args or []:
print(misc_arg)
if __name__ == "__main__":
typer.run(main)
Then we can support the following commands:
python my_app.py --named_arg1=val1
python my_app.py --named_arg1=val1 misc_arg1
python my_app.py --named_arg1=val1 misc_arg1 misc_arg2
python my_app.py --named_arg1=val1 misc_arg1 misc_arg2 ...
|
* What went wrong:
A problem occuremphasized textred configuring project ':cloud_firestore'.
> Could not resolve all files for configuration ':cloud_firestore:classpath'.
> Could not download builder-7.0.2.jar (com.android.tools.build:builder:7.0.2)
> Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'.
> Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'.
> The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.4/userguide/build_environment.html#gradle_system_properties
> Remote host terminated the handshake
> Failed to notify project evaluation listener.
> Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.
> Could not find method implementation() for arguments [project ':firebase_core'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
> Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.
I try to upgrade the dependencies
flutter pub upgrade
|
The easiest (albeit not necessarily most elegant) solution is to define `xdot` as a list function over polymorphic numerical arguments, as those can be instantiated to either directly the number type used for the ODE solver, or the automatic-differentiation value-infinitesimal pairs. Then you just wrap each version in vectors/matrices as required for the solver:
import Numeric.GSL.ODE
import Numeric.LinearAlgebra
import Numeric.AD
vanderpol :: Vector Double -- ^ Time points
-> [Vector Double]
vanderpol ts = toColumns $
odeSolveV (BSimp $ \t -> fromLists . jac t . toList)
0.1 1e-8 1e-8
(\t -> fromList . xdot t . toList)
(fromList [0.5,0]) ts
where xdot :: Num a => a -> [a] -> [a]
xdot t [x,v] = [v, -x*(1-x^2)]
jac :: Double -> [Double] -> [[Double]]
jac t = jacobian (xdot $ realToFrac t)
The `realToFrac` is required because from the perspective of `jac`, `xdot` does not accept a `Double` argument but rather a `Reverse s Double` argument. |
Just calculate the sum (like you did for your first table) for both tables, then join the results together on item_id.
If you can guarantee that both warehouses will have the exact same unique list of item_ids then you can do an INNER JOIN. I've assumed that they may have some discrepancies, so I've opted for a FULL JOIN. However, It seems that MySQL doesn't support the FULL JOIN option. So I've taken the UNION of the LEFT JOIN and the RIGHT JOIN to achieve the desired result.
I've quoted the IN and OUT columns with backticks, as IN is a SQL keyword (not sure about OUT, best to be safe). That way they will be treated as column names and not whatever else they mean (i.e. IN is an operator).
First, setup some tables to mimic your data.
```
-- Create table corresponding to warehouse 1
DROP TABLE IF EXISTS warehouse1;
CREATE TABLE warehouse1(item_id CHAR(5) NOT NULL
, `in` BIGINT NOT NULL
, `out` BIGINT NOT NULL
);
INSERT INTO warehouse1(item_id
, `in`
, `out`
)
VALUES('item1', 10, 0)
, ('item1', 5, 0)
, ('item2', 0, 3)
, ('item2', 0, 2);
-- Create table corresponding to warehouse 2
CREATE TABLE warehouse2(item_id CHAR(5) NOT NULL
, `in` BIGINT NOT NULL
, `out` BIGINT NOT NULL
);
INSERT INTO warehouse2(item_id
, `in`
, `out`
)
VALUES('item1', 12, 0)
, ('item1', 50, 0)
, ('item2', 0, 10)
, ('item2', 0, 30);
```
Secondly, perform the aggregations and join the results.
```
-- Compute the sums for each table, grouped by the item_id and join them together
-- We want a FULL JOIN here. But MySQL doesn't support it, so we UNION a LEFT and a RIGHT
-- to get the same effect.
SELECT wh1.item_id AS item_id
, wh1.balance AS warehouse1_balance
, wh2.balance AS warehouse2_balance
FROM(
SELECT item_id
, SUM(`in` - `out`) AS balance
FROM warehouse1
GROUP BY item_id
) wh1
LEFT JOIN (
SELECT item_id
, SUM(`in` - `out`) AS balance
FROM warehouse2
GROUP BY item_id
) wh2
ON wh1.item_id = wh2.item_id
UNION
SELECT wh2.item_id AS item_id
, wh1.balance AS warehouse1_balance
, wh2.balance AS warehouse2_balance
FROM(
SELECT item_id
, SUM(`in` - `out`) AS balance
FROM warehouse1
GROUP BY item_id
) wh1
RIGHT JOIN (
SELECT item_id
, SUM(`in` - `out`) AS balance
FROM warehouse2
GROUP BY item_id
) wh2
ON wh1.item_id = wh2.item_id
;
```
I have deliberately used UNION instead of UNION ALL as both the LEFT JOIN and the RIGHT JOIN will contain the INNER JOIN. So we don't want to include the INNER JOIN twice.
Try it yourself: [db<>fiddle][1]
[1]: https://dbfiddle.uk/YN6aADlQ |
I developed a code parallelized in a hybrid way based on OpenMPI + OpenMP. It works as I expect if 'enough' number of MPI processors are given. So far based on tests, I would roughly say 'enough' means more than two MPI processors.
A problem I observe is that if the code is allocated only one or two MPI processors, then the multi-threading via OpenMP does not work as expected, but stuck by 200% CPU usage (i.e., uses only 2-threads), not more. It is very unclear why this happens.
Here is information about running environment;
Ubuntu 20.04.4 LTS,
gfortran 13.2.0,
openmpi 4.1.5
To provide reporduction of my issue, here is a toy code that replicates the same issue;
```
program parallel_example
use OMP_LIB
implicit none
include 'mpif.h'
integer :: i, j, k, n, ierror, size_Of_Cluster, process_Rank
real :: sum, x
call MPI_INIT(ierror)
call MPI_COMM_SIZE(MPI_COMM_WORLD, size_Of_Cluster, ierror)
call MPI_COMM_RANK(MPI_COMM_WORLD, process_Rank, ierror)
call omp_set_dynamic(.False.)
call omp_set_num_threads(5)
!$OMP PARALLEL
print *, 'hello from thread:', OMP_GET_THREAD_NUM(), &
& 'of proc=', process_Rank
!$OMP END PARALLEL
! Set the number of iterations
n = 100000
! Initialize the sum
sum = 0.0
!$omp parallel do collapse(3) default(none) private(i, j, k, x) shared(sum, n)
do i = 1, n
do j = 1, n
do k = 1, n
!print *, 'hello from thread:', OMP_GET_THREAD_NUM(), i, j, k
x = 1.0 / (real(i) + real(j) + real(k))
!$omp atomic
sum = sum + x
enddo
enddo
end do
!$omp end parallel do
print *, "The sum is: ", sum
call MPI_Finalize(ierror)
end program parallel_example
```
The number of threads per MPI processor is set to 5. So I expect 500% CPU usage of each MPI processor from 'top' command of my ubuntu.
This is compile and execution processes;
```
mpif90 -fopenmp test.F90 -o app.exe
mpirun -np 1 ./app.exe
```
If I use 'mpirun -np 1' or 'mpirun -np 2', the CPU usage is stuck by 200%, no more. But if I give more than 2, for example 'mpirun -np 3', I can finally see 500% CPU usage for each of those three MPI processors.
It is very unclear to me why I cannot get 500% CPU usage with one or two MPI processors. I am pretty sure I am missing something to setup the environment properly, but I really don't know what is wrong. So if anyone has knowledge on this, please consider sharing it with me.
|
I have viewpager on that two fragments,
the same adapter is attached to both the fragments. The click listener is getting attached only after scrolling the recycler view items.
Here is my code:
`
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ItemChargingHistoryListBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = historyList[position]
holder.itemView.setOnClickListener {
listener.onItemClickListener(position)
}
holder.binding.apply {
if (data.sessionStatus == Constants.COMPLETED) {
tvDownload.setOnClickListener {
listener.onClickInvoiceButton(position)
}
imgFavorite.setOnClickListener {
listener.onFavouriteClickListener(position = position)
}
}
tvTitle.text = data.name
imgFavorite.visibility= VISIBLE
if (data.isFavourite == true){
imgFavorite.setImageResource(R.drawable.ic_favorite_red)
}
else{
imgFavorite.setImageResource(R.drawable.ic_favorite_stroke)
}
if (!data.time.isNullOrEmpty()){
tvTime.visibility = VISIBLE
imgTimer.visibility = VISIBLE
tvTime.text = data.time.toString().split(":").first()+"h : "+data.time.toString().split(":").last()+"m"
}else{
tvTime.visibility = GONE
imgTimer.visibility = GONE
}
if (!data.unitsCharged.isNullOrEmpty()){
tvPower.visibility = VISIBLE
imgPower.visibility = VISIBLE
tvPower.text = data.unitsCharged+"/kWh"
}else{
tvPower.visibility = GONE
imgPower.visibility = GONE
}
if (!data.connector.isNullOrEmpty()){
tvType.visibility = VISIBLE
imgType.visibility = VISIBLE
tvType.text = data.connector
}else{
tvType.visibility = GONE
imgType.visibility = GONE
}
if (!data.date.isNullOrEmpty()){
tvDate.visibility = VISIBLE
val dateFormatted=AppUtils.INSTANCE?.convertDateFormat(
dateFormatToRead = "yyyy-MM-dd",
dateFormatToConvert = "dd-MM-yyyy",
dateToRead = data.date?:""
)
tvDate.text =
context.getString(R.string.check_in_date) + " : " + (if (!dateFormatted.isNullOrEmpty()) " ${dateFormatted}" else "")
}else{
tvDate.visibility = GONE
}
if (!data.amount.isNullOrEmpty()){
tvPriceKw.visibility = VISIBLE
tvPriceKw.text = "₹"+data.amount
}else{
tvPriceKw.visibility = GONE
}
if (data.sessionStatus==Constants.FAILED){
tvFailureReason.visibility= VISIBLE
tvFailureReason.text=AppUtils.INSTANCE?.getFormattedString(stringOne = context.getString(R.string.failure_reason), stringTwo = data.failureReason)
tvFeedback.visibility= VISIBLE
tvFeedback.text=AppUtils.INSTANCE?.getFormattedString(stringOne = context.getString(R.string.feedback), stringTwo = data.feedback)
imgFavorite.visibility= GONE
layoutInfo.visibility= GONE
tvPriceKw.visibility= GONE
}`
I tried request focus, nested scrolling, smooth scrolling |
Click event of the recycler working only after scrolling |
|android|kotlin| |
null |
{"Voters":[{"Id":13447,"DisplayName":"Olaf Kock"},{"Id":1297272,"DisplayName":"Javier"},{"Id":11002,"DisplayName":"tgdavies"}]} |
import pandas as pd
import netCDF4 as nc
for day_num in range(1, 2):
if day_num < 10:
file_path = r'F:\desktop\datebase\Carbon-emission-data\AK\Vulcan.v3.AK.hourly.1km.total.mn.2010.d00' + str(
day_num) + '.nc4'
else:
file_path = r'F:\desktop\datebase\Carbon-emission-data\AK\Vulcan.v3.AK.hourly.1km.total.mn.2010.d0' + str(
day_num) + '.nc4'
print(f"{file_path}")
file_obj = nc.Dataset(file_path)
lon_data = file_obj.variables['lon'][:]
lat_data = file_obj.variables['lat'][:]
data_all = None
try:
for hours in range(24):
air = file_obj.variables['carbon_emissions'][hours:hours + 1]
data = air.data
data = data[0, :, :]
data[data == -9999] = 0
if data_all is None:
data_all = data
else:
data_all += data
time = file_obj.variables['time']
y_m_r = nc.num2date(time[:], time.units)
dt_str = y_m_r[0].strftime("%Y%m%d")
lon_list = []
lat_list = []
data_list = []
for i in range(data_all.shape[0]):
for j in range(data_all.shape[1]):
# print(f"i: {i}, j: {j}")
lon_list.append(lon_data[i, j])
lat_list.append(lat_data[i, j])
data_list.append(data_all[i, j])
df = pd.DataFrame({
'Longitude': lon_list,
'Latitude': lat_list,
'Carbon Emissions': data_list
})
df_pivot = df.pivot(index='Latitude', columns='Longitude', values='Carbon Emissions')
out_file_name = 'D:\Python Project\Project2\date_bag\\test\\test2\\' + dt_str + '.csv'
df.to_csv(path_or_buf=out_file_name)
print(f"{out_file_name}")
except IndexError:
print(f"IndexError at i={i}, j={j}")
print(f"data_all[{i}, {j}] = {data_all[i, j]}")
print(f"lon_data[{i}, {j}] = {lon_data[i, j]}")
print(f"lat_data[{i}, {j}] = {lat_data[i, j]}")
print(f"data_all.shape={data_all.shape}, lon_data.shape={lon_data.shape}, lat_data.shape={lat_data.shape}")
print("over")
|
Subsetting rows with sequence of values and identifying columns where sequence begins |
|r|dataframe|dplyr| |
null |
I am trying to use `h2o.deeplearning` model to predict on raster data. It returns me the following error
> Error: Not compatible with requested type: [type=character; target=double].
Here is a minimal, reproducible, self-contained example
```
library(terra)
library(h2o)
library(tidyverse)
h2o.init()
# create a RasterStack or RasterBrick with with a set of predictor layers
logo <- rast(system.file("external/rlogo.grd", package="raster"))
names(logo)
# known presence and absence points
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85,
66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31,
22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9,
99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21,
37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2)
# extract values for points
xy <- rbind(cbind(1, p), cbind(0, a))
v <- data.frame(cbind(pa=xy[,1], terra::extract(logo, xy[,2:3]))) %>%
mutate(pa = as.factor(pa))
str(v)
#### Import data to H2O cluster
df <- as.h2o(v)
#### Split data into train, validation and test dataset
splits <- h2o.splitFrame(df, c(0.70,0.15), seed=1234)
train <- h2o.assign(splits[[1]], "train.hex")
valid <- h2o.assign(splits[[2]], "valid.hex")
test <- h2o.assign(splits[[3]], "test.hex")
#### Create response and features data sets
y <- "pa"
x <- setdiff(names(train), y)
### Deep Learning Model
dl_model <- h2o.deeplearning(training_frame=train,
validation_frame=valid,
x=x,
y=y,
standardize=TRUE,
seed=125)
dnn_pred <- function(model, data, ...) {
predict(model, newdata=as.h2o(data), ...)
}
p <- predict(logo, model=dl_model, fun=dnn_pred)
plot(p)
``` |
Error while using predict function for h2o.deeplearning model on raster stack |
|r|h2o|predict|terra| |
Just in case you use iOS 17+ you can use containerRelativeFrame:
struct ContentView: View {
let items = ["1", "2", "3", "4", "5", "6"]
var body: some View {
ScrollView(.horizontal) {
LazyHStack(spacing: 0) {
ForEach(items, id: \.self) { item in
Text("\(item)")
.containerRelativeFrame([.horizontal, .vertical])
.background { Color.green }
}
}
}
.scrollTargetBehavior(.paging)
}
} |
You could use [$switch](https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch/#-switch--aggregation-) for that.
Assuming the field name in the document is "department", that might look like:
```
{$project: {
department: { $switch: {
branches: [
{case: {$eq: ["$department", "1576996323453"]}, then: "QA"}
{case: {$eq: ["$department", "1874996373493"]}, then: "Dev"}
{case: {$eq: ["$department", "1374990372493"]}, then: "BA"}
{case: {$eq: ["$department", "1874926373494"]}, then: "Tech Support"}
],
default: "$department"
}}
``` |
How do I target a nested HTML element with PHP? |
|php|wordpress| |
null |
Why is phantom data not auto inferred? |