text
string | meta
dict |
|---|---|
Q: Puppeteer return value without eval So i have created a function that doesnt work as expected, im a completely newb in java script i appreciate any guidance given
current code is
async function bs(client){
const browser = await puppeteer.launch({headless: false, args: minimal_args});
const page = await browser.newPage();
page.setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1");
await page.goto('site');
await page.waitForSelector('#textCliente',{visible: true});
await page.type('#textCliente', client);
await page.waitForSelector('#loginCustomerBox > div.marginT15.Button-Area > a',{visible: true});
await page.click('#loginCustomerBox > div.marginT15.Button-Area > a')
await page.waitForNavigation();
const f = await page.$("[class='Nmero-de-cliente-o2 bold']")
const text = await f.getProperty('textContent').jsonValue();
await browser.close();
return text;
};
this code actually gets the value im expecting flawless as far as i use console.log(text) nevertheless im trying to get the response from an express route and im expecting to return the result after a request
app.post('/cliente',(req,res) => {
var obj = JSON.parse(req.body.cliente);
let value = bs(obj);
res.send(value);
});
app.listen(process.env.PORT, () => {
console.log("on";
});
however this doesnt work as im only getting promise pending as i have said im totally new to puppeteer, express and js i dont seem to find a proper way to resolve that promise in order to get the result when i make a requesst to the endpoint "/cliente" can someone tell me what can i do or what am i missing?
im expecting to get the value cliente from a post request -> then execute the puppeter function and -> return the result to the client
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Trouble formatting table extracted from HTML to CSV format using javascript in browser console I am trying to extract a table from an HTML format on this website (pick any item from the dropdown box) and I have managed to write a javascript console code that does a pretty good job at extracting the table. However, I can't seem to make it look like a .csv-format file, with space between each row. Now it's a long single row, instead of looking like the table from the website. I would therefore like to ask for help to make that HTML table be exportable in any csv-reading software in that exact form.
Here is the code that I write in the Chrome Console:
var x = document.querySelectorAll("div.container table tbody")
var y = x[0].querySelectorAll("tr")
var myarray = []
for (var i=0; i<y.length; i++){
var nametext = y[i].textContent;
var z = y[i].querySelectorAll("td")
for (var j=0; j<z.length; j++){
var columns = z[j].textContent
myarray.push([columns]);
};
};
function make_code() {
var code = '<p></p>';
for (var k=0; k<myarray.length; k++) {
code += myarray[k][0] +";"
};
var w = window.open("");
w.document.write(code);
}
make_code()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Adding color to histogram using ggplot and facet_wrap I need help adding color to the two histograms produced using ggplot and facet_wrap
What am I missing:
ObesityDataSet_raw_and_data_sinthetic %>%
ggplot(aes(x=Height)) +
geom_histogram(bins = 14)+
facet_wrap(~Gender)
It would look like this
A: To add color to the histograms in ggplot and facet_wrap, you can use the fill argument in the geom_histogram function to specify the color for each histogram. Here's an example code:
ObesityDataSet_raw_and_data_sinthetic %>%
ggplot(aes(x=Height, fill=Gender)) +
geom_histogram(bins = 14, alpha=0.5, position = "identity")+
facet_wrap(~Gender)
A: In order to manually specify the colours of the histogram add the last line to Ilia Tetin's code:
ObesityDataSet_raw_and_data_sinthetic %>%
ggplot(aes(x=Height, fill=Gender)) +
geom_histogram(bins = 14, alpha=0.5, position = "identity")+
facet_wrap(~Gender) +
scale_fill_manual(values=c("blue", "red"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selenium Unable to find text in webpage I want to locate the first result in the search of this page https://www.se.com/ww/en/search/rxm4ab2bd
with
:"RXM4AB2BD | Product"
<div dir="auto" class="result-card"><a class="link-area" href="https://www.se.com/ww/en/product/RXM4AB2BD"><uiaas-search-result-product imagecontain="" class="hydrated"><uiaas-search-result-basic imagecontain="" class="hydrated"><!----><div class=""><uiaas-search-result-card-generic-template class="hydrated"><div slot="search-result-ribbon"></div><uiaas-search-result-public-header-template slot="search-result-header" class="hydrated"><div class="result"><uiaas-search-result-title class="hydrated"><div><a class="result-title__link" href="https://www.se.com/ww/en/product/RXM4AB2BD" target="_self"><h3 class="result-title"><span>Miniature plug in relay, Harmony, 6A, 4CO, with LED, lockable test button, 24V DC</span></h3></a></div></uiaas-search-result-title><div class="result-details result-header__details"><div class="result-details-item result-details-sku"><span class="result-type"><span class="highlight">RXM4AB2BD</span></span><span class="result-details-item__vertical-bar">|</span></div><div class="result-details-item"><span class="result-type">Product</span><span class="result-details-item__vertical-bar">|</span></div></div></div></uiaas-search-result-public-header-template><div slot="search-result-content"><span class="result-description">Miniature plug in relay, Harmony, 6A, 4CO, with LED, lockable test button, 24V DC</span><div slot="search-result-additional-content" class="search-result-additional-content"></div></div></uiaas-search-result-card-generic-template><div slot="result-eshop" class="result-eshop"></div></div></uiaas-search-result-basic></uiaas-search-result-product></a></div>
No matter what I try I can't get even find RXM4AB2BD.
I tried:
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), 'RXM4AB2BD')]")))
I checked and there are no frame in the page
A: In order for 'contains()' to work you need to provide a partial string.. Here you have provided exact string. Provide a partial String like "RXM4" and try.
try using below code:
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), 'RXM4')]")))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React-native SvgUri how to send path for image? Hi i am making a small component for input and when i try to send data for icon prop i get error this error.
error: components\commonComponents\IconInput.js: components\commonComponents\IconInput.js:Invalid call at line 20: require("" + this.props.iconName)
This is my component.
return (
<View style={{flexDirection: 'row', height: 40, borderRadius: 8, borderWidth: 1, borderColor: '#D6D6D6', alignItems: 'center', backgroundColor: '#F5F5F5'}}>
<SvgUri width="16" height="16" style={{paddingLeft: 10, paddingRight: 5}} source={require(`${this.props.iconName}`)} />
<TextInput
style={{fontSize: 14, fontFamily: 'Archivo', color: '#424242'}}
value={this.props.value}
multiline={false}
placeholder={this.props.mainProps.language.email}
placeholderTextColor="#999"
editable={false}
/>
</View>
)
And this is my other component where i am calling this input component and send props.
<View style={{paddingHorizontal: 24, paddingVertical: 24}}>
<Text>input</Text>
<Input value={this.state.order.customerId?.email } mainProps={this.props.mainProps} iconName={'../../resources/Envelope.png'}/>
</View>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unrecognized function or variable 'plotGrid' I'm using MATLAB R2022b.
and I get the error :
Unrecognized function or variable 'plotGrid'.
when I use plotGrid. I thought I'm using it wrongly, so I copy pasted an example of MATLAB that is using it:
https://au.mathworks.com/help/5g/ug/nr-channel-estimation-using-csirs.html
But still get the same error. I have installed SImBiology and I have checked it. It is installed.
My machine is mac btw. And I have moved my code's folder to where the "Examples" in MATLAB is, just in case the path matters.
Thanks.
A: Uninstalled SimBiology and reinstalled. It works now. I think moving the folder to the same folder as MATLAB also have helped because I had tried uninstall/install before.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React single page Tengo un componente para el contenido de mi pagina... es el siguiente:
import React from 'react';
import '../styles/content.css';
import Home from './home';
const Content = ()=>{
return(
<div className='contain-content'>
<Home/>
</div>
);
}
export default Content;
Y tengo un sidebar con algunos divs que contienen "Botones":
const IcoMenu = () => {
return (
<div className="menu-contain" >
<div id="home" className="ico-menu">
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
fill="currentColor"
class="bi bi-house-fill"
viewBox="0 0 16 16"
>
<path d="M8.707 1.5a1 1 0 0 0-1.414 0L.646 8.146a.5.5 0 0 0 .708.708L8 2.207l6.646 6.647a.5.5 0 0 0 .708-.708L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.707 1.5Z" />
<path d="m8 3.293 6 6V13.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5V9.293l6-6Z" />
</svg>
</div>
Realmente soy nuevo en React y lo que quiero conseguir es que cuando le de click a un boton, este actualice el componente Content... y cambie el componente Home por otro.
|
{
"language": "es",
"url": "https://stackoverflow.com/questions/75639853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python code using While Loops to print the minimum number of quarters, dimes etc to produce the given amt of change Using While loops in Python I have to create a code that will give the minimum amount of quarters, dimes, nickels, pennies needed to produce the given amount of change. The change in this case is 49. The output should look like this:
quarters: 1
dimes: 2
nickels: 0
pennies: 4
I have no idea how to do this. please help. There is nothing before this that relates to a question like this
I tried to initialize each by quarters = 25 etc but don't know how to make it give minimum amount to add
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Rust Axum Get Full URI request Trying to get the full request URI (scheme + authority + path)
I have found the discussion: https://github.com/tokio-rs/axum/discussions/1149 which says that Request.uri() should have it.
So I tried the following:
use axum::body::Body;
use axum::http::Request;
use axum::routing::get;
use axum::Router;
async fn handler(req: Request<Body>) -> &'static str {
println!("The request is: {}", req.uri());
println!("The request is: {}", req.uri().scheme_str().unwrap());
println!("The request is: {}", req.uri().authority().unwrap());
"Hello world"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/test", get(handler));
axum::Server::bind(&"0.0.0.0:8080".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
And run curl -v "http://localhost:8080/test" but I get:
The request is: /test
thread 'tokio-runtime-worker' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:8:59
It seems like it only contains the path.
I also found the other discussion: https://github.com/tokio-rs/axum/discussions/858
which suggests that axum::http::Uri should be able to extract all the details, but I get the same issue:
use axum::http::Uri;
use axum::routing::get;
use axum::Router;
async fn handler(uri: Uri) -> &'static str {
println!("The request is: {}", uri);
println!("The request is: {}", uri.scheme_str().unwrap());
println!("The request is: {}", uri.authority().unwrap());
"Hello world"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/test", get(handler));
axum::Server::bind(&"0.0.0.0:8080".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
curl -v "http://localhost:8080/test"
The request is: /test
thread 'tokio-runtime-worker' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:7:53
> cargo -V
cargo 1.68.0-nightly (2381cbdb4 2022-12-23)
> rustc --version
rustc 1.68.0-nightly (ad8ae0504 2022-12-29)
Cargo.toml
[package]
name = "axum_test"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.6.10"
tokio = { version = "1.26.0", features = ["macros", "rt-multi-thread"] }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: After adding foreign key annotations, data is still null in Swagger, using Entity Framework Core I am having trouble fetching data from foreign key table.
It is recognised in swagger, but the JSON list returns null.
Here's a look at my Models:
public class User
{
[Key]
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int GroupForeignKey { get; set; }
[ForeignKey("GroupForeignKey")]
public Group Group { get; set; }
}
And the group class:
public class Group
{
[Key]
public int GroupID { get; set; }
public string GroupName { get; set; }
public List<User> Users { get; set; }
}
When I am fetching, I am just making a call to retrieve the entire table from the database. Should it automatically link all the info from the foreign User table too? That is to say, by retrieving the group table, it should also pull all the users into that list specified (if I am correct)?
public IEnumerable<Group> GetAllUserGroups()
{
IEnumerable<Group> groups = _dbContext.Group.ToList<Group>();
return groups;
}
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: If ctx.message.mentions != None always returns true with Discord.py Custom Bot I'm working on a custom Discord bot, and I'm currently trying to make a /spam (message) (amount) command as my first full Discord.py project, but I'm currently running into a problem where when I check if the (message) parameter contains an @ mention with this code:
@bot.command()
async def spam(ctx, arg, amount=None):
# If message contains @ mention send error message.
if ctx.message.mentions != None: # <-- Error here
await ctx.channel.send("**Whoops!** Sorry, you can't say roles in spam messages.")
print(f"{ctx.message.author} attempted to spam a spam-sensitive word.")
return
But it doesn't give me an error message, it just tells me:
"Whoops! Sorry, you can't say roles in spam messages." in Discord.
Also, I am aware that when I remove the "return" line it continues the script and does the /spam anyway, but when I do that it sends the error message first and then does the spam, which isn't exactly what I'm aiming for.
I tried a lot of different variations of this code, but each time it achieved the same result of either thinking there was an @mention every time the command was called, or thinking there was never an @mention ever.
I also tried using a list and checking over the list to see if it contained anything in the list, but that doesn't work exactly the same as what I'm trying to get to work, so I'm not going to do that I don't think.
Any help would be great! :D
A: Because ctx.message.mentions is always a list (empty list when there are no mentions) so you should replace your mentions check with this:
if ctx.message.mentions != []:
...
or
if len(ctx.message.mentions) != 0:
...
Any of these two would work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic menu using JSON script producing no results I'm trying to produce a menu system that will load buttons that go to a set of videos dynamically, I want to give the menu system button data via a JSON script however I'm having trouble getting the data to display, I have already confirmed my script works with a basic list before modifying it to take JSON data meaning there's no issues with my button prefab.
When I debug.log the json object it produces the file and when I run the game there are no filepath errors which means everything is being read properly. I've also confirmed the panelTransform gameObject is assigned correctly.
The JSON file:
{
"Albania":
[
{
"buttonId": 1,
"buttonText": "Tirana1"
},
{
"buttonId": 2,
"buttonText": "Tirana2"
},
{
"buttonId": 3,
"buttonText": "Tirana3"
},
{
"buttonId": 4,
"buttonText": "Tirana3"
}
]
}
The script attached to my canvas object (contains the panel object):
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Collections.Generic;
using TMPro;
public class ButtonsMenu1 : MonoBehaviour
{
//public List<ButtonData> buttonData;
public GameObject buttonPrefab;
public Transform panelTransform;
public string jsonFilePath;
void Start()
{
string json = File.ReadAllText(jsonFilePath);
Debug.Log(json);
List<ButtonData> buttonData = JsonUtility.FromJson<List<ButtonData>>(json);
Debug.Log("Panel object: " + panelTransform.name);
foreach (ButtonData data in buttonData)
{
GameObject buttonObj = Instantiate(buttonPrefab, panelTransform); //Instantiates the button within the Transform of the panel
Button button = buttonObj.GetComponent<Button>();
TMP_Text buttonText = buttonObj.GetComponentInChildren<TMP_Text>();
button.onClick.AddListener(() => { ButtonClicked(data.buttonId); });
buttonText.text = data.buttonText;
}
}
void ButtonClicked(int buttonId)
{
// Handle button click based on button ID
}
public class ButtonData
{
public int buttonId;
public string buttonText;
}
}
Any ideas as to why no buttons display in my game or in the hierarchy?
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django+PostgreSQL: creating user with UserCreationForm saves it to auth_user table, but not to the table created for the User model I'm learning Django and now developing a simple food blog app for practice, using Django 4.1 and PostgreSQL. Since I'm not quite good yet at understanding how some concepts work in practice, I started with creating the basic structure (models, views, etc.) as per MDN Django Tutorial, and then went on adding other things based on various Youtube tutorials. I also created some users with Django Admin to see if everything works, and work it did... until I implemented user registration.
I successfully registered several users via registration form and could log in as anyone of them, view their profile page, etc., but found out they were not displayed anywhere in the users list. At the same time, I couldn't log in to any of the accounts I created previously with Django Admin.
Having searched for errors through the code of my 'recipeblog' app, I finally went to check the database I used. There, I found two different tables with different users: the first one named recipeblog_user, containing users created with Django Admin, and the second one named auth_user, containing users created with registration form.
Thus I seem to have found the problem, but it got me stuck, for I don't know what to do with it. It seems to me that registration form should somehow be able to save new users to the table I defined first, but I can't yet see the way to implement it.
I found some suggestions to set AUTH_USER_MODEL in settings, but when I set
AUTH_USER_MODEL = recipeblog.models.User
I only got
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I also tried to point the User model to use auth_user table, but when I set
db_table = 'auth_user' in User's Meta class,
I got another error, this time it was
ERRORS:
auth_user: (models.E028) db_table 'auth_user' is used by multiple models: recipeblog.User, auth.User.
I guess I can't simply merge two tables anyway, because they are not identical.
Is there any way to make my app save newly registered users to the first table, recipeblog_user, and not to the auth_user? Am I missing something in the models or views? Any advice would be welcome.
As for the code I have:
*
*in models.py
class User(models.Model):
username = models.CharField(unique=True, max_length=25)
ACTIVE = 'AC'
BLOCKED = 'BL'
status_choices = [
(ACTIVE, 'Active'),
(BLOCKED, 'Blocked')
]
status = models.CharField(max_length=2, choices=status_choices, default=ACTIVE)
faves = models.TextField(default='', blank=True)
registration_date = models.DateTimeField(auto_now_add=True, editable=False)
update_date = models.DateTimeField(auto_now=True)
password = models.CharField(max_length=30)
email = models.EmailField()
class Meta:
ordering = ['registration_date']
db_table = 'auth_user'
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('user-detail', args=[str(self.id)])
*
*in views.py:
class UserListView(ListView):
model = User
context_object_name = 'user_list'
template_name = 'user-list.html'
class UserDetailView(generic.DetailView):
model = User
template_name = 'user-detail.html'
def register_user(request):
if request.method == 'POST':
form = RegisterUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
return redirect('login')
else:
form = RegisterUserForm
return render(request, 'registration/register_user.html', {'form': form})
*
*in forms.py:
class RegisterUserForm(UserCreationForm):
email = forms.EmailField(max_length=50)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
A: In your User class file instead of using a standard User class inheriting from
models.User do the following:
Import:
from django.contrib.auth.models import AbstractUser
Then replace class User(models.Model):
with class User(AbstractUser): so it becomes
class User(AbstractUser):
username = models.CharField(unique=True, max_length=25)
ACTIVE = 'AC'
BLOCKED = 'BL'
status_choices = [
(ACTIVE, 'Active'),
(BLOCKED, 'Blocked')
]
status = models.CharField(max_length=2,
choices=status_choices,
default=ACTIVE)
faves = models.TextField(default='', blank=True)
registration_date = models.DateTimeField(auto_now_add=True,
editable=False)
update_date = models.DateTimeField(auto_now=True)
password = models.CharField(max_length=30)
email = models.EmailField()
class Meta:
ordering = ['registration_date']
db_table = 'auth_user'
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('user-detail', args=[str(self.id)])
Also make sure in your settings.py that AUTH_USER_MODEL is set to your new custom model inheriting from AbstractUser.
Once done, run your migrations and it should generate or update the table for you. It will use the same Postgres table as the original Django user, but the model it will use will be your custom model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What causes: Xcode "No such module 'exp_lib' error for my pure swift app's statement: "import exp_lib"? Created static lib Swift project exp_lib and built its exp_lib.a file.
Created Swift app and dragged in .a file.
Put .a is in Build Phases > Link Binary With Libraries
I put absolute path to .a in Build Settings > Library Search Paths
In ViewController, I put "import exp_lib" and get the error.
I tried Frameworks Search Path.
I tried dragging .a to Proj nav and to Link Binary With Libraries.
Started from scratch (ie. new projects).
What am I missing?
Should "import" statement have project name or something else?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ERROR TypeError: undefined is not an object (evaluating 'date.toISOString') While working on a React Native project ,I encountered the following error:
TypeError: undefined is not an object (evaluating 'date.toISOString')
As I am practicing as a newbie with 'academind' course, my code is quite similar to his code on github. Please refer to the link below:
https://github.com/academind/react-native-practical-guide-code/tree/09-user-input/code/09-adding-error-styling
His code(academind) is working fine but it's not working for me. Please check my code with his code (on github).
ERROR TypeError: undefined is not an object (evaluating 'date.toISOString')
This error is located at:
in ExpenseItem (created by CellRenderer)
in RCTView (created by View)
in View (created by CellRenderer)
in VirtualizedListCellContextProvider (created by CellRenderer)
in CellRenderer (created by VirtualizedList)
in RCTView (created by View)
in View (created by ScrollView)
in RCTScrollView (created by ScrollView)
in ScrollView (created by ScrollView)
in ScrollView (created by VirtualizedList)
in VirtualizedListContextProvider (created by VirtualizedList)
in VirtualizedList (created by FlatList)
in FlatList (created by ExpensesList)
in ExpensesList (created by ExpensesOutput)
in RCTView (created by View)
in View (created by ExpensesOutput)
in ExpensesOutput (created by AllExpenses)
in AllExpenses (created by SceneView)
in StaticContainer
in EnsureSingleNavigator (created by SceneView)
in SceneView (created by BottomTabView)
in RCTView (created by View)
in View (created by Screen)
in RCTView (created by View)
in View (created by Background)
in Background (created by Screen)
in Screen (created by BottomTabView)
in RNSScreen (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by InnerScreen)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by InnerScreen)
in InnerScreen (created by Screen)
in Screen (created by MaybeScreen)
in MaybeScreen (created by BottomTabView)
in RNSScreenContainer (created by ScreenContainer)
in ScreenContainer (created by MaybeScreenContainer)
in MaybeScreenContainer (created by BottomTabView)
in RCTView (created by View)
in View (created by SafeAreaInsetsContext)
in SafeAreaProviderCompat (created by BottomTabView)
in BottomTabView (created by BottomTabNavigator)
in PreventRemoveProvider (created by NavigationContent)
in NavigationContent
in Unknown (created by BottomTabNavigator)
in BottomTabNavigator (created by ExpensesOverview)
in ExpensesOverview (created by SceneView)
in StaticContainer
in EnsureSingleNavigator (created by SceneView)
in SceneView (created by SceneView)
in RCTView (created by View)
in View (created by DebugContainer)
in DebugContainer (created by MaybeNestedStack)
in MaybeNestedStack (created by SceneView)
in RCTView (created by View)
in View (created by SceneView)
in RNSScreen (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by InnerScreen)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by InnerScreen)
in InnerScreen (created by Screen)
in Screen (created by SceneView)
in SceneView (created by NativeStackViewInner)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by ScreenStack)
in RNSScreenStack (created by ScreenStack)
in ScreenStack (created by NativeStackViewInner)
in NativeStackViewInner (created by NativeStackView)
in RNCSafeAreaProvider (created by SafeAreaProvider)
in SafeAreaProvider (created by SafeAreaInsetsContext)
in SafeAreaProviderCompat (created by NativeStackView)
in NativeStackView (created by NativeStackNavigator)
in PreventRemoveProvider (created by NavigationContent)
in NavigationContent
in Unknown (created by NativeStackNavigator)
in NativeStackNavigator (created by App)
in EnsureSingleNavigator
in BaseNavigationContainer
in ThemeProvider
in NavigationContainerInner (created by App)
in ExpensesContextProvider (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
ExpenseItem.js
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { getFormattedDate } from '../../util/date';
function ExpenseItem({ id, description, amount, date }) {
const navigation = useNavigation();
function expensePressHandler() {
navigation.navigate('ManageExpense', {
expenseId: id
});
}
return (
<Pressable
onPress={expensePressHandler}
style={({ pressed }) => pressed && styles.pressed}
>
<View style={styles.expenseItem}>
<View>
<Text style={[styles.textBase, styles.description]}>
{description}
</Text>
<Text style={styles.textBase}>{getFormattedDate(date)}</Text>
</View>
<View style={styles.amountContainer}>
<Text style={styles.amount}>{amount.toFixed(2)}</Text>
</View>
</View>
</Pressable>
);
}
Date.js
export function getFormattedDate(date){
return date.toISOString().slice(0, 10);
}
export function getDateMinusDays(date,days){
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - days);
//we can get a date, number of days in the past.
}
A: This error occurs when you are trying to use the toISOString method on an undefined or null object.
To fix this error, you need to ensure that the date object is defined before calling the toISOString method on it. Here are some steps you can take:
Check that the date object is being initialized properly. Make sure that you are passing a valid date object to the function or component that is using it.
Use an if statement to check if the date object is defined before calling the toISOString method. Here's an example:
if (date) {
const dateString = date.toISOString();
// Do something with the dateString
}
This will prevent the toISOString method from being called if the date object is undefined or null.
Use optional chaining to call the toISOString method. This is a newer feature in JavaScript that allows you to safely access nested properties or methods on an object without having to check if they are defined first. Here's an example:
const dateString = date?.toISOString();
The ?. operator checks if date is defined before calling the toISOString method. If date is undefined or null, then dateString will be undefined as well.
By taking these steps, you should be able to fix the undefined is not an object (evaluating 'date.toISOString') error in your React Native project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 'Object is currently in use elsewhere.' while calling draw string when new bitmap is created in each thread I'm trying to make a paint operation where each thread creates a bitmap and a new graphics. That thread draws onto the bitmap until finished then finally draws the bitmap to the control surface which gets locked to avoid the same error. The problem that I'm having is that the DrawString method throws that the object is already in use when it's a completely new bitmap and graphics for each thread. Commenting out that second draw operation also avoids the issue. Can only one DrawString operation be used at once?
Parallel.ForEach(rectangles, new ParallelOptions() { MaxDegreeOfParallelism = Threads }, rect =>
{
using Bitmap bitmap = new((int)(tileSize.Width * ChunkSize.Width), (int)(tileSize.Height * ChunkSize.Height));
using Graphics graphics = Graphics.FromImage(bitmap);
for (int i = rect.X; i < rect.Right; i++)
{
for (int j = rect.Y; j < rect.Bottom; j++)
{
PointF Location = new PointF(tileSize.Width * (i - rect.Width), tileSize.Height * (j - rect.Height));
lock (bitmap) // This lock does nothing
{
graphics.FillRectangle(renderTiles[i, j].BackBrush, new Rectangle(Location.ToPoint().Add(new Point(5, -1)), tileSize.ToSize().Add(new Size(1, 1))));
// graphics.DrawString causes error
graphics.DrawString(renderTiles[i, j].Ico.ToString(), Font, renderTiles[i, j].ForeBrush, Location.ToPoint());
}
}
}
lock (pe.Graphics)
{
pe.Graphics.DrawImage(bitmap, rect.Location.Multiply(tileSize.ToPoint()));
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why I'm I getting a 405 Method Not Allowed when submitting forms - Laravel I'm working on a countdown website where I have 2 forms in the same view, every time I submit 1 of those forms I'm getting a error that says:
"message": "The POST method is not supported for route /. Supported methods: GET, HEAD."
The method that I'm using in the view is a GET method and the method that I'm using in the action route of the forms are POST method.
Now, I'll show you the routes and the HTML:
My routes:
HTML Form 1:
HTML Form 2:
I've tried by setting the hidden method with Laravel using @method('POST') in the form, but it doesn't even works, I've also tried setting the same route to the routes on the web.php file like this:
Route::get('/', function () {
return view('welcome');
});
Route::post('/', [App\Http\Controllers\EmailController::class, 'sendEmail'])->name('send.email');
Route::post('/', [App\Http\Controllers\EmailController::class, 'saveEmail'])->name('save.email');
, but doesn't works too, every time I tried it, I was getting this error:
and other things that I have tried by watching YouTube tutorials and StackOverflow posts, but how I said before nothing works
I would be very grateful if you could help me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript dynamic import returning promise instead of object I'm having an issue coding a dynamic list in JavaScript. I basically have a simple two-layer system that will dynamically generate each list item and pair it with a object which will then be returned to the list with some basic properties. In short each list item is built as follows:
The Skeleton
An object that contains reusable properties and functions that will be common between items. In the future I plan on this containing a large amount of data I do not want to keep on my server to have to send to each user every time they view the component.
export default {
name: 'Default',
chapters: []
}
The Meat Adds specific data to the skeleton which is then exported. Again, this is going to add a decent amount of data to the object that will be paired with the list item.
import Book from '@/book.js'
Book.name = 'The Almanac'
Book.chapters = ['Chapter 1', 'Chapter 2', ...]
export default Book
Populating The List
The list is populated when the component mounts, retrieving information on what the user can access from the server.
get (list) {
DataService.getBooks(localStorage.getItem('Username')).then((res) => {
res.data.forEach(function (item) {
list.push({
title: item,
obj: import('@/TheAlmanac/book.js')
.then(function (res) {
return res.default
})
})
})
})
}
The issue I'm having is that when I attempt to assign the result of the promise from the dynamic import statement to obj using the following line of code:
this.items = this.items[index].obj.chapters
Im getting:
Uncaught TypeError: Cannot read properties of undefined (reading 'obj')
I've also tried arrow functions but it returns the same.
Can someone please point out what I'm doing incorrectly or let me know if what I would like to do is possible / good JavaScript practice?
A: It is much easier to use async/await here.
async get(list) {
const res = await DataService.getBooks(localStorage.getItem('Username'));
res.data.forEach(item => {
list.push({title: item, obj: (await import('@/TheAlmanac/book.js')).default});
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GCP pubsub topic metadata not being delivered I have a Google cloud storage bucket that in projectA that I am trying to configure to send notifications on object creation to a topic in projectB. I do this by the following terraform:
resource "google_storage_notification" "my_bucket_notification" {
bucket = "my_bucket"
payload_format = "JSON_API_V1"
topic = "projects/projectB_id/topics/my-topic"
event_types = ["OBJECT_FINALIZE"]
object_name_prefix = "folderA/"
}
Over in projectB I create the binding to allow projectA to publish to a topic:
resource "google_pubsub_topic" "my-topic" {
name = "my-topic"
}
resource "google_pubsub_subscription" "my-top-subscription" {
name = "my-subscription"
topic = google_pubsub_topic.my-topic.name
}
resource "google_pubsub_topic_iam_member" "my_bucket_iam" {
role = "roles/pubsub.publisher"
topic = google_pubsub_topic.my-topic.id
member = "serviceAccount:${var.projectAEmail}"
}
Whenever an object gets created in folderA a message is published over to my subscription in projectB. However, I notice that any metadata on the objects in folderA are missing from the notification. Looking at the documentation for terraform, there doesn't seem to be any setting that suggests excluding blob metadata. Is there a specific configuration I need to set to allow blob metadata to be passed in a pubsub notification from google cloud storage?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why dataloader is grouping the captions in wrongly manner? When checked with my __getitem__ function, it is giving an image, caption, and class_id properly. An Image is a tensor of size [3, 256, 256] and a caption is a list of 20 elements.
But when I observed the dataloader, it is grouping captions in the wrong way. The batch size is 32. So, for a batch of data, the expected components of dataloader are 32 images, 32 captions and 32 class_ids.
But the dataloader is giving 32 images, 20 captions and 32 class_ids. Where 20 is the max length of a caption.
Instead of giving 32 captions of each length 20, dataloader is giving a list of 20 tuples, each of length 32.
Here is the code for the dataloader, I am presenting only the relevant parts of the code.
class Load_Dataset(data.Dataset):
def __init__(self, data_dir, split='train',
base_size=64,
transform=None, target_transform=None):
self.transform = transform
.......
def get_caption(self, sent_ix):
# a list of strings for a sentence
sent_caption = self.captions[sent_ix]
if sent_caption[-1] == '<end>':
print('ERROR: do not need END token', sent_caption)
num_words = len(sent_caption)
# pad with '<end>' tokens
x = ['<end>'] * 20
x_len = num_words
if num_words <= 20:
x[:num_words] = sent_caption
else:
ix = list(np.arange(num_words))
np.random.shuffle(ix)
ix = ix[:20]
ix = np.sort(ix)
x[:] = [sent_caption[i] for i in ix]
x_len = 20
return x, x_len
def __getitem__(self, index):
#
key = self.filenames[index]
cls_id = self.class_id[index]
#
.....
#
img_name = '%s/images/%s.jpg' % (data_dir, key)
imgs = get_imgs(img_name, self.imsize,
bbox, self.transform, normalize=self.norm)
# random select a sentence
sent_ix = random.randint(0, self.embeddings_num)
new_sent_ix = index * self.embeddings_num + sent_ix
caps, cap_len = self.get_caption(new_sent_ix)
return imgs, caps, cap_len, cls_id, key
def __len__(self):
return len(self.filenames)
How to handle this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use tailwindCSS in .hbs file I am facing issues while using tailwindCss in hbs file . Can someone tell me the procedure of integrating the tailwindCss in .hbs file?
I have tried many things but the inline property of tailwindcss is not applying to any element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tensorflow is installed in the conda environment, but I can't access any of its attribute functions I have set up a virtual environment using anaconda, and I have successfully installed the relevant libraries to set up tensorflow.
The commands that I ran are:
conda activate tf
conda install -c anaconda tensorflow
The code that I am trying to run is:
import tensorflow as tf
print("Hello, Tensorflow!")
print(tf.__version__)
And I get the following error:
Hello, Tensorflow!
Traceback (most recent call last):
File "c:\Users\cocoh\OneDrive\Documents\Coding\MI\ForestCover\TensorflowTest.py", line 3, in
print(tf.version)
AttributeError: module 'tensorflow' has no attribute 'version'
Calling pip show tensorflow shows that tensorflow is in fact, installed in the environment:
Name: tensorflow
Version: 2.11.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: c:\users\cocoh\anaconda3\envs\tf\lib\site-packages
Requires: tensorflow-intel
Required-by:
I'm not sure what the issue is, and any help would be greatly appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flink complains Sort on a non-time-attribute field is not supported when group by proctime I am using Flink 1.12,
I write a simple flink code as follows, it reads Stock record from StockSource, each Stock consists of three fields: id,trade_date,price. pt is the proctime.
When I run the sql as follows, flink complains that Sort on a non-time-attribute field is not supported. I would like to know where the problem is.
The sql is:
val sql =
"""
select pt, sum(price) from sourceTable
group by pt
order by pt
""".stripMargin(' ')
tenv.sqlQuery(sql).toRetractStream[Row].print()
The flink code is:
object OrderByProctime {
def main(args: Array[String]) {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
env.setParallelism(1)
val ds: DataStream[Stock] = env.addSource(new StockSource())
val tenv = StreamTableEnvironment.create(env)
tenv.createTemporaryView("sourceTable", ds, $"id", $"price", $"pt".proctime())
//ERROR:
//Sort on a non-time-attribute field is not supported. org.apache.flink.table.api.TableException: Sort on a non-time-attribute field is not supported.
val sql =
"""
select pt, sum(price) from sourceTable
group by pt
order by pt
""".stripMargin(' ')
tenv.sqlQuery(sql).toRetractStream[Row].print()
env.execute()
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Building a Form Here is my situation:
Company A hire new agents and has them fill out a form. Company B is the marketing agency that also needs the data inputed in that original form. Currently they are having to fill out 2 forms.
Is it possible for me to create a JS form that the new agent fills out and the data inputed is sent to both company A and company B? is so how , API, React, fetch() How?
I'm trying to learn first if its even possible
A: That is a somewhat broad question. Depending on how the 2 forms are implemented, you could have a singular form on a web page that uses the same submit API of both forms A and B. Provided these 2 forms are regular HTTP forms, one plan of action could be the following:
*
*React is great, but it's hard to learn and definitely overkill, especially for a beginner and a simple form page
*find and download a form website template (as HTTP/CSS). Here's also the part where you could watch a 1/2 hours crash course on these 2 if you're not familiar. You won't learn everything, but should be enough for you to get going.
*customize the form. You should use the "Inspect element" tool of your browser to analize the forms on the company A and B form pages and you should be able to shape your downloaded http form into having the same fields/parameters
*analize how the original forms are submitted. Do some research on the form element and how submitting works. Use inspect element on the 2 websites. In general you're looking for the URL and method (GET/POST/...).
*instead of using the standard form submission, you're going to use JavaScript to handle 2 submissions at the same time. You can accomplish this by, instead of having a submit button, having a "button button" (<button type="button" onclick="...">), which executes JS code on-click. This code can then change your form's URL and method to the ones used on Company A's site, submit the form, then change the URL & method for Company B and submit again. You can find an example on how to do this here.
*handle CORS. To prevent websites from telling your browser to do malicious stuff, in short, JavaScript isn't usually allowed to send requests to other websites (such as Company A or B's website). In general, only reading the response data is prohibited (which you won't need; it should work, but I'm not entirely sure), but you can find more information on this other question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Can't put another gif aside on video using ffmpeg I want to put 2 gifs side by side onto a video. I use code:
ffmpeg -i tt108_5.mp4 -ignore_loop 0 -i e:\gals\flags\Russie.gif -ignore_loop 0 -i e:\gals\flags\Ukraine.gif -filter_complex \
"[1:v][0:v]scale2ref=oh*mdar:ih/5[ua][b];[ua]setsar=1,format=yuva420p,colorchannelmixer=aa=0.75[u];[b][u]overlay=shortest=1;\
[2:v][0:v]scale2ref=oh*mdar:ih/5[ua2][b2];[ua2]setsar=1,format=yuva420p,colorchannelmixer=aa=0.75[u2];[b2][u2]overlay=0:200:shortest=1"\
-c:a copy -y -r 30 -b:v 2000k tt108_5f.mp4
It works only for 1st gif, but the second is missing in the result. I also would like to know how to address the first gif's size to use some variables instead of arbitrary number overlay=0:200, to put them in vstack mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you implement a speech-to-text application with Speech Framework without the AVAudioSession class on MacOS? How do you implement a speech-to-text application with Speech Framework without the AVAudioSession class on MacOS?
This example for iOS uses AVAudioSession but doesn't work for MacOS without using Catalyst. I don't want to use Catalyst. How do I make it work? There isn't any boilerplate code on the Internet as far as I know.
iOS link to speech-to-text using Speech framework: https://developer.apple.com/tutorials/app-dev-training/transcribing-speech-to-text
AVAudioSession (iOS): https://developer.apple.com/documentation/avfaudio/avaudiosession
Someone said that you can use an alternative class or framework for recording the audio from the mic in MacOS but the implementation boilerplate is unclear and the devil's details are unavailable. It is called AVAudioCapture or AVCaptureSession for MacOS.
See: AVAudioSession on desktop?
Please let me know if you need any clarifications.
I tried AVAudioSession but I need to use a MacOS compatible library for MacOS under the technologies API exposed under the Apple Developer tools.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Im trying to make a roblox game where you gain jump power each jump, and im having some errors the error i received when code entered [my code]
(https://i.stack.imgur.com/OKOzW.png)
A: your script looks good, when i first started lua roblox a got the same error while trying to check the players.
Your script runs before your char load. So you first need to check if he is in the game.
or instead use the player added function then check if the character is there using if player(setting passed in the player added).character then ...
I hope that it was helpful
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Students to record, name-space-score and prints the score in decreasing order enter image description here
Our lesson is about array, methods and for loop
Help me solve this problem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: How to add another Android App store to an App in admob with an Android store already I wish to know how, if it is possible to add another App from a supported App store to an App on admob that already have an Android store linked to it. The Apps in the two stores have same App package name and ads ID.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how do I make this program short and sweet? <html>
<body>
<h3>Java Script fPGM\<\h3>
<script>
var lamb = "Mary";
var array1 = ["handy","Lightweight",18,"Handsome"];
document.write("HELLO WORLD\n");
document.write("\n");
alert(array1);
for (var i = 0; i<5; i++) {
document.write("<br>");
document.write("hi");
}
<\script>
<\body>
<\html>
I wanna Make this program very short. As I am a beginner to JS I don ot know to make this program short.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Creating a constrained 3D Random Walk [Python] I have an implementation of a random walk in 3D that can move in 6 directions at random to create random looking 3D points. Currently this approach creates purely random surface plots. I am trying to add the following constraints to the random walk 1) Make it symmetrical 2) make it closed. Is it possible to add the following constraints to the random walk process so that the random walk will create symmetrical and closed point clouds.
My current implementation to create 3D random walk is below
N = 100 # choose number of steps, granularity
R = (np.random.rand(N) * 6).astype("int") # randomly intialize 1 array with 6 moves: 0,1,2,3,4,5 and 100 steps, combinations
x = np.zeros(N) # 100 x steps
y = np.zeros(N) # 100 y steps
z = np.zeros(N) # 100 z steps
# define the random moves
x[ R==0 ] = -1 # left
x[ R==1 ] = 1 # right
y[ R==2 ] = -1 # down
y[ R==3 ] = 1 # up
z[ R==4 ] = -1 # back
z[ R==5 ] = 1 # front
x = np.cumsum(x) # cumulative sums the steps across for each axis of the plane
y = np.cumsum(y)
z = np.cumsum(z)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why did activating the Conda environment fail? Window11;
Default terminal is git-bash,
with zsh and oh-my-zsh;
https://dominikrys.com/posts/zsh-in-git-bash-on-windows/
But conda activate faild,
~/Desktop conda activate
__conda_exe:1: no such file or directory: /cygdrive/d/Anaconda3/Scripts/conda.exe
I dont know what is cygdrive and where it from?
Please.
I use conad init --all
cmd is ok;
enter image description here
but git-bash still not ok;
I use where bash & where conda, output:
~/Desktop where python
/d/Anaconda3/python
/c/Users/xhang/AppData/Local/Microsoft/WindowsApps/python
~/Desktop where conda
conda () {
\local cmd="${1-__missing__}"
case "$cmd" in
(activate | deactivate) __conda_activate "$@" ;;
(install | update | upgrade | remove | uninstall) __conda_exe "$@" || \return
__conda_reactivate ;;
(*) __conda_exe "$@" ;;
esac
}
/d/Anaconda3/Scripts/conda
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django - Authentication credentials were not provided for magiclink I am trying to create authenticaiton sytem where a user can loging using a magic link.
i am usign a custom user mode.
class UserAuthView(CreateAPIView):
http_method_names = ['post']
serializer_class = TestUserListSerializer
permission_classes = (IsAuthenticatedTestUserPermissionAdmin,)
def post(self, request, name, *args, **kwargs):
serializer = self.serializer_class(
data=request.data, context={'request': request}
)
if serializer.is_valid():
email_id = serializer.validated_data['email']
try:
user = TestUser.objects.filter(email=email_id).first()
if user:
company = str(user.company)
user_id = user.id
# Add the random string here
random_string = get_random_string(16)
request.session["login_state"] = random_string
token = signing.dumps({"email": email_id, "login_state": random_string})
qs = urlencode({'token': token})
magic_link = request.build_absolute_uri(
location=reverse('api-magiclink'),
) + f"?{qs}"
return Response({
'success': True,
'message': 'magiclink created .',
'data': {
'access_token': magic_link,
}
})
else:
return Response({
'message': 'User does not exist',
})
except TestUser.DoesNotExist:
return Response({
'message': 'Unable to login user'
})
else:
return Response(serializer.errors)
Then tryin to validate this using the following code
class PartnerUserMagicLink(CreateAPIView):
http_method_names = ['get']
permission_classes = (IsAuthenticatedTestUserPermissionAdmin,)
def get(self, request, token, **kwargs):
token = request.GET.get("token")
if not token:
# Go back to main page; alternatively show an error page
return redirect("/")
# Max age of 15 minutes
data = signing.loads(token, max_age=900)
email = data.get("email")
if not email:
return redirect("/")
user = TestUser.objects.filter(username=email, is_active=True).first()
if not user:
# user does not exist or is inactive
return redirect("/")
# validate token and check for expiry; we want to make sure
# it's only been generated since the last login
delta = timezone.now() - user.last_login
try:
data = signing.loads(token, max_age=delta)
except signing.SignatureExpired:
# signature expired, redirect to main page or show error page.
return redirect("/")
# Check for the random string
login_state = data.get("login_state")
session_login_state = request.session.get("login_state")
if not login_state or not session_login_state:
return redirect("/")
if login_state != session_login_state:
return redirect("/")
# Everything checks out, log the user in and redirect to dashboard!
login(request, user)
return redirect("/dashboard/")
I am getting Unauthorized: /v1/magiclink . Can anyone help please?
My url with token looks like http://127.0.0.1:8000/v1/magiclink?token= XXX
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Broken image path on Vercel deployment I'm deploying an app on Vercel and everything builds correctly except for my header image. I just get the name of the image file. When I open the app through react on the local server, the logo image shows up as it should. Any ideas? Right now the image in just in the public folder in react. I have another image in the same folder and it is showing up just fine on the page. The logo is also a link to the main page, and if I click on the broken file name, the link works. I am using router.
I tried changing the file name, I tried putting the images in a folder and doing a path instead of the image name, and I changed the Navlink to a Link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: error C2678 binary '==': no operator found which takes a left-hand operand of type 'const _Ty' (or there is no acceptable conversion) When I compile my c++ code, my visual studio 2022 jumps out an error, the error does not appear in my cpp file but in the xutility file.
template <class _InIt, class _Ty>
_NODISCARD constexpr _InIt _Find_unchecked1(_InIt _First, const _InIt _Last, const _Ty& _Val, false_type) {
// find first matching _Val
for (; _First != _Last; ++_First) {
if ( *_First == _Val) {
break;
}
}
return _First;
}
and i compile the code in window 10 computer.
this is the source code i have.
for (auto const &entry : all_cards){
std::cout << '\n';
std::cout << std::quoted(entry.first.get_name()) << " card stats:" << '\n';
std::cout << " Total number of cards: " << entry.second.size() << '\n';
std::vector<std::set<playing_card>> decks;
for (const auto& card : entry.second){
for (auto const &entry : decks){
if (std::find(decks.begin(), decks.end(), card) != decks.end()){
decks.push_back({});
decks.back().insert(card);
} else {
decks.insert(card);
}
}
}
my original source code have error or ? how can i fix it.
A: playing_card class doesn't have the const == operator
Here are some examples of the required operators with the differences between them:
*
*Here the object itself (left side) isn't const and accept const object (right side)
*
*bool operator == (const playing_card &);
*Here the object itself is const and accept const object
*
*bool operator == (const playing_card &) const;
You need to add the second method (bool operator == (const playing_card &) const;) to your class or remove the const word before auto in you for loop
for (auto& card : entry.second){
for (auto const &entry : decks){
if (std::find(decks.begin(), decks.end(), card) != decks.end()){
decks.push_back({});
decks.back().insert(card);
} else {
decks.insert(card);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to return amount of a certain letters from a text file using a method Assuming I have a text file filled with random words or letters, I need to be able to increment the amount of times a letter is seen. For this example, I am trying to find the letter 'a'. While the program does compile and return a number, the number can either be too high or low concerning the amount of the certain letter I'm looking for. Changing my code around, how can I fix this?
Oh! I should mention that the person I'm sending this code in for wants it to be structured in the form of having a method whereas Problem9 only has the parameters (File, file) and must be constructed into the form of a method
package module4labs;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;
public class Module4Labs {
public static void main(String[] args) {
new Module4Labs();
}
public Module4Labs() {
double problemSolution = Problem9(new File("Problem9.txt"));
System.out.println(problemSolution);
}
//Problem 9: Find 'a'
public int Problem9(File file) {
int counter =0;
try {
Scanner input = new Scanner(file);
ArrayList<String> list = new ArrayList<String>();
while(input.hasNext()) {
list.add(input.next());
}
for (int x=0; x<list.size()-1;x++) {
if (list.subList(x,x+1).equals('a'));
counter++;
}
input.close();
} catch (FileNotFoundException e) {
System.out.println(file + "File Not Found.");
}
return counter;
}
Currently, I'm getting a warning from Eclipse saying "Unlikely argument type for equals(): char seems to be unrelated to List"
Unsure on how to continue with this
A: the person I'm sending this code in for wants it to look similar to this No they don't. This code violates several coding conventions in Java; Problem9 is a terrible and undescriptive method name. You are counting the appearance of a char. Don't hardcode that char - pass it to the method and give the method a proper name, like countChar. Iterate the lines of your file and then iterate the contents of the line looking for the char. Next, don't calculate the result and print it in the constructor. I would make countChar static, but assuming you must instantiate your class I would do so in main and then invoke the method. Like,
public static void main(String[] args) {
Module4Labs m4l = new Module4Labs();
double problemSolution = m4l.countChar(new File("Problem9.txt"), 'a');
System.out.println(problemSolution);
}
public int countChar(File file, char ch) {
int counter = 0;
// This is a try-with-Resources, don't hard code input.close();
try (Scanner input = new Scanner(file)) {
while (input.hasNextLine()) {
String line = input.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == ch) {
counter++;
}
}
}
} catch (FileNotFoundException e) {
System.out.println(file + " File Not Found.");
}
return counter;
}
A: We can also use the java.nio.file package to accomplish this task. For example,
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class CharacterFrequency {
private String str;
public CharacterFrequency(File file) {
try {
this.str = Files.readString(file.toPath());
} catch (IOException e) {
System.err.println(e);
}
}
public int getFrequency(char a) {
int frequency = 0;
for (char b : str.toCharArray()) {
if (a == b) {
frequency++;
}
}
return frequency;
}
public void showFrequency(char a) {
int frequency = getFrequency(a);
System.out.printf("The character %c appears %d times\n", a, frequency);
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java CharacterFrequency.java path/to/file");
return;
}
File f = new File(args[0]);
CharacterFrequency cf = new CharacterFrequency(f);
cf.showFrequency('a');
cf.showFrequency('z');
cf.showFrequency('g');
cf.showFrequency('p');
}
}
I created a file example.txt that has these contents:
The soccer player scored a goal.
I saved the file example.txt to the same directory as CharacterFrequency.java.
Then I ran the command:
% java CharacterFrequency.java example.txt
The character a appears 3 times
The character z appears 0 times
The character g appears 1 times
The character p appears 1 times
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a way to transform a dataframe to latex codes generating table with multiple panels? Is there a way to transform a multi-indexed dataframe to latex codes generating table with multiple panels correspongding to the first-level index?
multi_index = pd.MultiIndex.from_product([["A", "B"], ["a", "b"]])
df=pd.DataFrame([1,2,3,4],index=multi_index)
The original dataframe.
The expected output from latex code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: LSTM Layer Longer Than Sequence Length I have been reading and watching videos on LSTM networks and how they interact with a sequence of input. In the examples I have found the number of LSTM nodes equals the input sequence length. For example, a sequence of 5 is fed into an LSTM layer of 5 nodes. This makes intuitive sense to me as the first input is fed into the first LSTM node. The long and short term memory from node 1 is then fed into node 2 along with the second input. This goes on for each node until the final node's output.
I dont understand how the input is fed into a network where there are less LSTM nodes than the sequence length. Is the input sequence truncated? Also, what are the last nodes of an LSTM layer doing when the sequence is shorter than the LSTM Node length. Are those nodes simply unused?
For example, I think that the keras code: tf.keras.layers.LSTM(4) corresponds to a layer where 4 lstm nodes are feeding into each other. Is that an incorrect understanding?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Get the Size of a Table in CnosDB The new version of CnosDB seems to be compatible to SQL. I am able to create a table as follows according to the manual:
CREATE TABLE air (
visibility DOUBLE,
temperature DOUBLE,
presssure DOUBLE,
TAGS(station)
);
But how could I get the size of each table? Is there anything similar to infomation_schema in the MySQL world?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with LST image downlad from Google Earth Engine I am not able to solve the issue with my code chunk here in Google Earth Engine.
The error I encounter are:
Unknown element type provided: object. Expected: ee.Image, ee.ImageCollection, ee.FeatureCollection, ee.Element or ee.ComputedObject.
LST: Layer error: Parameter 'right' is required.
Editing the code would be most helpful.
Here is my code
`var imageVisParam = {min: 303, max: 323, palette: ['yellow', 'red', 'purple', 'blue']};
var imageVisParam2 = {min: 0.96, max: 1, palette: ['white', 'orange', 'brown']};
//cloud mask
function maskL8sr(image) {
// Bits 3 and 5 are cloud shadow and cloud, respectively
var cloudShadowBitMask = (1 << 3);
var cloudsBitMask = (1 << 5);
// Get the pixel QA band.
var qa = image.select('pixel_qa');
// Both flags should be set to zero, indicating clear conditions.
var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
.and(qa.bitwiseAnd(cloudsBitMask).eq(0));
return image.updateMask(mask);
}
//vis params
var vizParams = {
bands: ['B5', 'B6', 'B4'],
min: 0,
max: 4000,
gamma: [1, 0.9, 1.1]
};
var vizParams2 = {
bands: ['B4', 'B3', 'B2'],
min: 0,
max: 3000,
gamma: 1.4,
};
//load the collection:
{
var col = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
.map(maskL8sr)
.filterDate('2018-01-01','2018-12-31')
.filterBounds(geometry);
}
print(col, 'coleccion');
//median
{
var image = col.median();
print(image, 'image');
Map.addLayer(image, vizParams2);
}
// NDVI:
{
var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
var ndviParams = {min: -1, max: 1, palette: ['blue', 'white', 'green']};
print(ndvi,'ndvi');
Map.addLayer(ndvi, ndviParams, 'ndvi');
}
//
//select thermal band 10(with brightness tempereature), no BT calculation
var thermal= image.select('B10').multiply(1000);
Map.addLayer(thermal, imageVisParam, 'thermal');
// find the min and max of NDVI
{
var min = ee.Number(ndvi.reduceRegion({
reducer: ee.Reducer.min(),
geometry: geometry,
scale: 30,
maxPixels: 1e9
}).values().get(0));
print(min, 'min');
var max = ee.Number(ndvi.reduceRegion({
reducer: ee.Reducer.max(),
geometry: geometry,
scale: 30,
maxPixels: 1e9
}).values().get(0));
print(max, 'max')
}
//fractional vegetation
{
var fv = ndvi.subtract(min).divide(max.subtract(min)).rename('FV');
print(fv, 'fv');
Map.addLayer(fv);
}
/////////////
//Emissivity
var a= ee.Number(0.004);
var b= ee.Number(0.986);
var EM=fv.multiply(a).add(b).rename('EMM');
Map.addLayer(EM, imageVisParam2,'EMM');
//LST c,d,f, p1, p2, p3 are assigned variables to write equaton easily
var c= ee.Number(1);
var d= ee.Number(0.00115);
var f= ee.Number(1.4388);
var p1= ee.Number(thermal.multiply(d).divide(f));
var p2= ee.Number(Math.log(EM));
var p3= ee.Number((p1.multiply(p2)).add(c));
var LST= (thermal.divide(p3)).rename('LST');
var LSTimage = ee.Image(LST)
Map.addLayer(LSTimage, {min: 0, max: 350, palette: ['FF0000',
'00FF00']},'LST');
// Define the export region
var exportRegion = geometry;
// Export the LST image to Google Drive
Export.image.toDrive({
image: LSTimage,
description: 'LST_image1',
region: exportRegion,
scale: 30,
crs: 'EPSG:4326'
}, 'LST_image1');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create generative art circle pattern I have been teaching myself JavaScript, and I like the idea of code-generated art. I came across this design that is made up of circles changing in size and overlapped by different colors.
How would something like this reference image be coded in JavaScript? I'm guessing for loops? But I am not sure how to set them to gradually change sizes throughout the line.
I'm imagining something like this?
let spaceX = 25,
spaceY = 25,
dial = 20;
function setup() {
createCanvas(400, 400);
noStroke();
}
function draw() {
background(220);
// horizontal row
for (let x = 0; x <= width; x += spaceX) {
// vertical column
for (let y = 0; y <= height; y += spaceY) {
ellipse(x, y, diam);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
A: Here's the pseudo-code translated to JavaScript with Canvas
const spaceX = 25,
spaceY = 25,
dial = 20,
width = 400,
height = 400;
const canvas = document.createElement('canvas');
document.body.append(canvas);
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
function circle(x, y, diam = 10) {
ctx.beginPath();
ctx.arc(x, y, diam / 2, 0, 2 * Math.PI);
ctx.fill();
}
function draw() {
for (let x = 0; x <= width; x += spaceX)
for (let y = 0; y <= height; y += spaceY)
circle(x, y);
}
draw()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is Pandas converting an existing column from int to float when running apply? I am doing some operations on a pandas dataframe, specifically:
*
*Dropping a column
*Using the dataframe.apply() function to add a column based on an existing one
Here's the simplest test-case I've been able to create:
import pandas as pd
df = pd.DataFrame(
[["Fred", 1, 44],
["Wilma", 0, 39],
["Barney", 1, None]],
columns=["Name", "IntegerColumn", "Age" ])
def translate_age(series):
if not np.isnan(series['Age']):
series["AgeText"] = "Over 40" if series["Age"] > 40 else "Under 40"
else:
series["AgeText"] = "Unknown"
return series
df = df.drop('Name', axis=1)
print('@ before', df['IntegerColumn'].dtypes)
df = df.apply(func=translate_age, axis=1)
print('@ after', df['IntegerColumn'].dtypes)
The print() output shows the change in the IntegerColumn's type. It started as an integer:
@ before int64
... and then after the apply() call, it changes to a float:
@ after float64
Initially, the dataframe looks like this:
Name IntegerColumn Age
0 Fred 1 44.0
1 Wilma 0 39.0
2 Barney 1 NaN
... after the apply() call, it looks like this:
IntegerColumn Age AgeText
0 1.0 44.0 Over 40
1 0.0 39.0 Under 40
2 1.0 NaN Unknown
Why is the IntegerColumn changing from an integer to a float in this case? And how can I stop it from doing so?
A: When you do the apply, the rows get converted to a common dtype, i.e. float. If you didn't drop the string column, that wouldn't be possible, so the conversion wouldn't happen.
What you're doing is recommended against in the docs for DataFrame.apply():
Notes
Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details.
Instead, assign the whole column at once, for example like this:
def translate_age(age):
n = 40
if np.isnan(age):
return "Unknown"
elif age > n:
return f"Over {n}"
else:
return f"Under {n}"
df['AgeText'] = df['Age'].apply(translate_age)
(I'm also using a variable n for the number, but only to avoid having a magic number.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find the most similar git commit based on a none-git repo? I'm a researcher. I have found that one paper using a modified version of angr. He doesn't fork the official angr repo. I'd like to compare it from the official repo to see what code he added for the paper.
I have done the following:
*
*the python package has version info(8.18.10.25), but the angr's official repo don't have tag for v8.*. I also try to find the relevant commit, but it seems still to be very different from modified angr.
*using pip download --no-binary :all: angr==8.18.10.25 --no-deps to get source code. But still very different.
I'd like to find a tool to traverse all the git commit, compare the dir to my target dir, then output the most similar git commit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hosting a React website on Hostinger - error 403 I am trying to create a React website and get it hosted. I've built the website and it works fine on LocalHost:3000, however, problems arrise when I try to host it. I've used commands such as npm run build as well as yarn run build (hoping that it would change something, it didn't.). Additionally, I pasted the following code in my .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
I've attached a picture here showing the error on the right and my public_html folder where I unzipped the build file:Contents of public_html directory public_html directory
Nothing seems to be working and my website is simply showing error 403.
A few more random pieces of information:
*
*My domain/website works fine as I was able to run a WordPress website on it beforehand with no issues
*I'm using the "Premium Web Hosting" from Hostinger
*I've made my website using React as well as NextUi
If anyone could provide some assistance as to what I might be doing wrong here and how to fix it, it would be greatly appreciated!! Do LMK if more information is needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where can I find the error log for CnosDB v2.2 (Docker version)? I am currently deploying a Docker version for CnosDB v2.2. After deploying the instance, I restart the CnosDB server. Some requests work but others don't.
Where can I find the error log file?
I tried these places: logs/debug.log, messages.log and logs/http.log without any luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot install PHPExcel in Laravel 10 by psr-0 error I have tried to install Laravel Excel in Laravel 10, but I cannot install it.
I am using
composer require maatwebsite/excel
but when I install it, it give an error like this.
> Class PHPExcel_Properties located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Chart\Properties.php
> does not comply with psr-0 autoloading standard. Skipping. Class
> PHPExcel_Best_Fit located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\bestFitClass.php
> does not comply with psr-0 autoloading standard. Skipping. Class
> PHPExcel_Exponential_Best_Fit located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\exponentialBestFitClass.php
> does not comply with psr-0 autoloading standard. Skipping. Class
> PHPExcel_Linear_Best_Fit located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\linearBestFitClass.php
> does not comply with psr-0 autoloading standard. Skipping. Class
> PHPExcel_Logarithmic_Best_Fit located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\logarithmicBestFitClass.php
> does not comply with psr-0 autoloading standard. Skipping. Class
> PHPExcel_Polynomial_Best_Fit located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\polynomialBestFitClass.php
> does not comply with psr-0 autoloading standard. Skipping. Class
> PHPExcel_Power_Best_Fit located in
> D:/project/real/laravel/testexcel/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\powerBestFitClass.php
> does not comply with psr-0 autoloading standard. Skipping.
Please help. I still don’t understand why.
I am using php 8.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Combination of two word into a double word in TwinCAT 3? I am using TwinCAT 3.
I am trying to read the floating variable via MODBUS TCP.
The read variables are in a word array. How can I convert 2 word into float/real? I mean both word first want to combine and then save as another variable as DWORD.
Moreover when I have to do swapping?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting specific Season and Episode info from OMDBAPI.com using PowerShell Getting a specific Season and Episode back for a Series.
I am getting the data back I want but I think it's in the wrong format.
Here is my code
$Result = [xml] (Invoke-WebRequest "http://www.omdbapi.com/?Season=1&Episode=2&t=Reacher&apikey=$ApiKey")
Here is my result:
Cannot convert value "{"Title":"First Dance","Year":"2022","Rated":"TV-MA","Released":"04 Feb 2022","Season":"1","Episode":"2","Runtime":"52
min","Genre":"Action, Crime, Drama","Director":"Sam Hill","Writer":"Lee Child, Nick Santora, Scott Sullivan","Actors":"Alan Ritchson, Malcolm Goodwin,
Willa Fitzgerald","Plot":"When more victims are discovered, Reacher attempts to get answers but is set up. Roscoe discovers a threatening message.","Langu
age":"English","Country":"N/A","Awards":"N/A","Poster":"https://m.media-amazon.com/images/M/MV5BMjYxOWZhZGEtMTRiMy00NWYzLWJmYjYtOTkxZDlkMGZmM2QxXkEyXkFqcG
deQXVyMTM3MTQxNzk@._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"8.1/10"}],"Metascore":"N/A","imdbRating":"8.1","imdbVotes":"3639
","imdbID":"tt14503476","seriesID":"tt9288030","Type":"episode","Response":"True"}" to type "System.Xml.XmlDocument". Error: "The specified node cannot
be inserted as the valid child of this node, because the specified node is the wrong type."
At H:_mydocs\MovieCapture\Untitled19.ps1:5 char:1
*
*$Result = [xml] (Invoke-WebRequest "http://www.omdbapi.com/?Season=1& ...
*
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastToXmlDocument
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extract google's first pages' all href links of any keywords listed in our excel sheet Option Explicit
Private chr As Selenium.ChromeDriver
Sub Test()
Dim i As Long
Dim lastrow As Long
lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).row
For i = 2 To lastrow
Dim mykeyword As String
mykeyword = Sheet1.Cells(i, 1).Value
Set chr = New Selenium.ChromeDriver
chr.Start
chr.Get "https://www.google.com/search?q=" & mykeyword
chr.Wait 1000
Dim Mylinks As Selenium.WebElements
Dim Mylink As Selenium.WebElement
Set Mylinks = chr.FindElementsByCss("div.yuRUbf.a")
For Each Mylink In Mylinks
If LCase(Mylink.Attribute("data-ved")) = "2ahUKEwjSuvfI1MP9AhWu-TgGHRNrAB4QFnoECAkQAQ"
Then
Debug.Print Mylink.Attribute("href")
Exit For
End If
Next Mylink
If i = lastrow Then
chr.Quit
End If
Next i
End Sub
With the above code I tried to fetch all the href links after google page loads of that particular keyword. The macro is running and it is taking all the keywords also from the excel sheet, but it is not fetching the href links as expected. I tried to run this for this keyword just for an instance "608-2Z site:fagbearing.cc AND filetype:pdf" and that opened the link also i.e.
"https://www.google.com/search?q=608-2Z+site%3Afagbearing.cc+AND+filetype%3Apdf&rlz=1C1JJTC_enIN1044IN1044&oq=608-2Z+site%3Afagbearing.cc+AND+filetype%3Apdf&aqs=chrome.0.69i59.735j0j7&sourceid=chrome&ie=UTF-8"
and after that, it needed to be fetching those 2 resulting links that come after loading but it dint. They are these links...
*
*https://www.fagbearing.cc/PDF-bearings/SKF-Rolling-Bearings-PDF.pdf
*https://www.fagbearing.cc/PDF-bearings/KOYO-Ball-Roller-Bearings-PDF.pdf...
Kindly advise me on what needs to be corrected here. It would be of great help, if you help me out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can Chromium print JS source code before it's parsed? I want to print or log JS source before it's compiled into bytecode. I've tried various js-flags without success so far. Is it possible? If so, what's the process?
Example HTML/JS:
<html> <head>
<script type="text/javascript"> alert('newtext'); </script>
</head></html>
I'd like to expose "alert('newtext')".
I've made a number of attempt but can only get downstream code:
chromium --no-sandbox file:///...html --js-flags="--log-source-code" -> byte code
chromium --no-sandbox file:///...html --js-flags="--log-source-code" -> memory chunk addresses
I'm also trying to compile chromium with debugging enabled without success so far.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why am I getting → error: no matching function for call to 'Date::Date()'? I have 2 classes, each holding private variables and initialized in their own respective constructors that use an initializer list.
The instructions for class Date states that:
In the public part of Date, add a constructor that takes a day, month, and year as input, and uses an initializer list to initialize the private variables with the passed-in values.
The instructions for class Todo_item states that:
In the public part of To_do_item, add a constructor that takes a string description and Date due date as input. Use those to initialize the variables in the private part using an initializer list. The item should always be initialized as not done.
After trying to run my program, however, I ran into an error and another problem:
cpp: In constructor ‘Todo_item::Todo_item(const string&)’:
cpp:277:32: error: no matching function for call to ‘Date::Date()’
277| Todo_item(const string& s) {
And in the "Problems" section:
no default constructor exists for class "Date"
These problems only appeared after I created the constructor Todo_item(const string& s).
Here is my code:
1st class = class Date
class Date : public Date_base {
private:
int day;
int month;
int year;
public:
Date(int d, int m, int y) : day(d), month(m), year(y) {
if (d >= 1 && d <=31) {
day = d;
} // from 1 to 31 days
if (m >= 1 && m <=12) {
month = m;
} // from 1 to 12 months
if (y >= 0) {
year = y;
} // 0 or higher year(s)
} // initialize private Date variables using an initializer list
// other methods...
};
2nd class = class Todo_item
class Todo_item : public Todo_item_base {
private:
string description;
Date due_date;
bool done;
public:
Todo_item(const string& desc, Date due) : description(desc), due_date(due) {
done = false;
} // initialize private Todo_item variables using an initializer list
Todo_item(const string& s) {
string due_date_str, state_str, description_str;
int count = 0;
// ... other lines of code
}
};
I have tried to remove the const string& from Todo_item(const string& s) and just passed it without a reference (string s). I hoped that making this change in the parameter was the simple solution to this error, but this was to no avail.
What can be done to tackle those errors/problems? If you can, please include an example in your answer (it would be greatly appreciated!).
Also, let me know if further info is required.
Another note:
This is what the Todo_item(const string& s) is expected to do: "Add another constructor to Todo_item that takes a string as input. The string is formatted exactly the same as the output of Todo_item::to_string. For example, Todo_item("25/12/2018! Buy gifts") creates a Todo_item with the due date 25/12/2018, the description "Buy gifts", and a completion status of not done". So should I be using two initializer lists in that case?
A: Your Date class does not have a default constructor (a constructor that can be called without passing any parameter values to it).
However, the Todo_item(const string&) constructor does not have an initializer list to construct the due_date member with input values, like the Todo_item(const string&, Date) constructor does. So, the compiler needs to default-construct the due_date member instead, but it can't, hence the error.
To fix this, you need to either:
*
*add a default constructor to Date, eg:
Date() : day(0), month(0), year(0) {}
Alternatively, update the Date(int, int, int) constructor to also act as a default constructor, eg:
Date(int d = 0, int m = 0, int y = 0) : day(d), month(m), year(y) {
...
}
*add an initializer list to Todo_item(const string&) to construct the due_date member with input values, eg:
Todo_item(const string& desc) : description(desc), due_date(0,0,0), done(false) {
...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making computer attempt to "reread" usb port device Windows 10 This is a very short question but i just wanted to know if there was any way to make a program that would make my computer (windows 10) "reread" a USB port, bu "reread" i mean simulate the same process that would happen when unplugging and replugging a device into a usb port. if possible, would it also be possible to specify a specific port to do this on. The language the program is written in doesn't really matter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I find a specific word that does not start with hyphen or a dot I'm in Visual Studio and want to search trough my CSS files to match a whole word that does not have a hyphen or dot or whitespace at the beginning or the end
For instance just I want to find the word table.
I don't want to get matches for words like
.help-page-table
.table
I tried this expression and other variations. I'm out of my depth.
(?:[^.]|^)(?:[^-]|^)(table)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I use an IEnumerable with different properties for each entry as a method argument? I'm relatively new to C#. I'm trying to use an IEnumerable collection as an argument to a C# function, but I want to define the properties that I want to return as well.
Suppose I have a car IEnumerable with properties such as color and brand. Each entry has a color and a brand, of course.
I'm trying to split the enumerable information on the function below.
Is something like this possible?
public string stringforeach(IEnumerable coll, <<color>>, <<brand>>)
{
string write = "";
int i = 0;
foreach (var element in coll)
{
write += string.Concat(i.ToString() + ";" + element.color+ ";" + element.bramd + "\n");
i++;
}
return write;
}
A: Use two separate features of C#:
Use generics so that the method can accept collections of a specific type with the compiler knowing about the specific type being used for a specific call of the method.
Use delegates as parameters to be able to pass functions (or lambda expressions) to specify which property of an object to access.
public string StringForeach<T>(IEnumerable<T> coll, Func<T, string> property1, Func<T, string> property2)
{
string write = "";
int i = 0;
foreach (var element in coll)
{
write += i + ";" + property1(element) + ";" + property2(element) + "\n";
i++;
}
return write;
}
Given the following Car class
public class Car
{
public string Color { get; set; }
public string Brand { get; set; }
}
you can call the method like this:
List<Car> cars = new List<Car>();
cars.Add(new Car { Color = "Red", Brand = "BMW" });
cars.Add(new Car { Color = "Black", Brand = "Mercedes" });
string text = StringForeach<Car>(cars, c => c.Color, c => c.Brand);
Some explanations:
public string StringForeach<T>(IEnumerable<T> coll, Func<T, string> property1, Func<T, string> property2)
This declares a generic method which can be called with a specific type T. It accepts three parameters:
*
*IEnumerable<T> coll: A collection of objects of type T
*Func<T, string> property1: A delegate to a function that accepts an argument of type T and returns a string
*Func<T, string> property2: See above.
When calling the method
string text = StringForeach<Car>(cars, c => c.Color, c => c.Brand);
we specify that we call the method with type T being the concrete type Car.
The lambda expression
c => c.Color
is a short form of writing a function delegate for this function:
string SomeFunc(Car c)
{
return c.Color;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Access Complex Json value from URL I am trying to access the JSON content from the below URL and parse to extract and print the date value of "data.content.containers.container.locationDateTime"
iff the
"data.content.containers.container.label " has been set as "Empty Equipment Returned"
$url = 'https://elines.coscoshipping.com/ebtracking/public/containers/FCIU5238624';
$datax = file_get_contents($url);
$x = json_decode($datax);
could anyone help me please
A: This is work for me to extract and print the date value
$url = 'https://elines.coscoshipping.com/ebtracking/public/containers/FCIU5238624';
$datax = file_get_contents($url);
$x = json_decode($datax);
$dataTime = $x->data->content->containers[0]->container->locationDateTime;
print $dataTime;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Forgot user password for the command line - Using code server on NAS I have code server running in a docker container on a Synology box. Everything works great but I need to install pip. So, I ran the command sudo apt-get install python3-pip, however to execute this I need my passord for the user 'abc' I don't remember setting a password but I was wondering if anyone could help me out. Any help would be greatly appreciated. Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to filter a trasaction model in django I am trying to make transctions between two users.
models.py
class Trasaction(models.Model):
sender = models.ForeignKey(
Account, on_delete=models.PROTECT
)
receiver = models.ForeignKey(
Account, on_delete=models.PROTECT
)
amount = models.IntegerField()
purpose = models.CharField(max_length=100, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.sender.username}"
I want to query for all transactions where a user is either a sender or a receiver.
views.py
def transactions_log(request):
user = request.user
transactions = Transactions.objects.filter #am stuck
return render(request, "trasaction.html")
A: Try to use Q objects, like so:
from django.db.models import Q
def transactions_log(request):
user = request.user
transactions = Transaction.objects.filter(Q(sender=user) | Q(receiver=user))
return render(request, "transaction.html", {"transactions": transactions})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Alert when color changes_Code in Pine Script on Tradingview I want to get alert on tradingview when color changes to green, it pop-up an alert "Buy" and when color changes to orange it goes with alert "Sell".
But the script keeps showing up "Script could not be translated from: , title="Buy", message="green buy")"
Please help me!
Study("Impulse MACD]", shorttitle="IMACD_LB", overlay=false)
lengthMA = input(34)
lengthSignal = input(9)
calc_smma(src, len) =>
smma=na(smma[1]) ? sma(src, len) : (smma[1] * (len - 1) + src) / len
smma
calc_zlema(src, length) =>
ema1=ema(src, length)
ema2=ema(ema1, length)
d=ema1-ema2
ema1+d
src=hlc3
hi=calc_smma(high, lengthMA)
lo=calc_smma(low, lengthMA)
mi=calc_zlema(src, lengthMA)
md=(mi>hi)? (mi-hi) : (mi<lo) ? (mi - lo) : 0
sb=sma(md, lengthSignal)
sh=md-sb
mdc=src>mi?src>hi?lime:green:src<lo?red:orange
plot(0, color=gray, linewidth=1, title="MidLine")
plot(md, color=mdc, linewidth=2, title="ImpulseMACD", style=histogram)
plot(sh, color=blue, linewidth=2, title="ImpulseHisto", style=histogram)
plot(sb, color=maroon, linewidth=2, title="ImpulseMACDCDSignal")
ebc=input(false, title="Enable bar colors")
barcolor(ebc?mdc:na)
*alertcondition(src>mi?src>hi?lime:green , title="Buy", message="green buy")
alertcondition(src<lo?red:orange , title="Sell", message="red sell")
I tried to add the alertcondition but it didn't work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a GUI for Undirected graph For the classes below, I want to go through a file called file.txt of type: 0 1 {'weight': 7} in which 0 and 1 are nodes ID. I want a GUI class that iterates through the file and displays the nodes and edges (for the connected nodes only). I want the nodes to be clickable items (like buttons), and edges as linked lines
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
class Node {
int id;
List<Edge> edges;
boolean visited;
int distance;
Node previous;
public Node(int id) {
this.id = id;
edges = new ArrayList<>();
visited = false;
distance = Integer.MAX_VALUE;
previous = null;
}
public void addEdge(int to, int weight) {
edges.add(new Edge(to, weight));
}
}
class Edge {
int to;
int weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
class Graph {
Map<Integer, Node> nodes;
public Graph() {
nodes = new HashMap<>();
}
public void addNode(int id) {
nodes.put(id, new Node(id));
}
public void addEdge(int from, int to, int weight) {
Node node = nodes.get(from);
if (node == null) {
node = new Node(from);
nodes.put(from, node);
}
node.addEdge(to, weight);
}
public int shortestPath(int startNode, int endNode) {
// Create a priority queue to hold nodes to be visited
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(n -> n.distance));
// Initialize all nodes as unvisited and with infinite distance from start node
for (Node n : nodes.values()) {
n.visited = false;
n.distance = Integer.MAX_VALUE;
}
// Set distance of start node to 0 and add to priority queue
Node start = nodes.get(startNode);
if (start == null) {
return -1;
}
start.distance = 0;
pq.add(start);
// Visit nodes in priority queue until end node is found or queue is empty
while (!pq.isEmpty()) {
// Remove node with smallest distance from priority queue
Node current = pq.poll();
// Check if current node is end node
if (current.id == endNode) {
return current.distance;
}
// Visit neighbors of current node
for (Edge e : current.edges) {
Node neighbor = nodes.get(e.to);
if (neighbor == null) {
continue;
}
int distance = current.distance + e.weight;
// Update neighbor's distance if shorter path is found
if (!neighbor.visited && distance < neighbor.distance) {
neighbor.distance = distance;
neighbor.previous = current;
pq.add(neighbor);
}
}
// Mark current node as visited
current.visited = true;
}
// End node not found, return -1 to indicate failure
return -1;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: html anchor href download sees network failure but same line works sans download and pasted in address bar Until the lastest disaster from the Chromium team the following worked perfectly
<td valign="top">
<a href="https://chrysalis-systems.net/shared/tmp/dfmapbCNAPQ1.dot" download="">
<button type="button" title="download graph specification (graphViz:dot)">
<img src="/dflibg/sdk/images/downloadA32.png">
</button>
</a>
</td>
<td valign="top">
<a href="https://chrysalis-systems.net/shared/tmp/dfmapbCNAPQ1.png" print="" target="_blank">
<button type="button" title="print or save graph">
<img src="/dflibg/sdk/images/printerC.png">
</button>
</a>
</td>
Now, however,
1) although the href for opening the image in a new blank window works fine,
2) the href for downloading the dot-spec text file does not work any longer,
the infamous "Failed Network Error" [Never used to happen in many years!!!!!]
BUT
3) works if pasted into an address bar.
The files are there; same ownership; same permissions:
[root@amauris4 logs]# ls -lt $DOCUMENT_ROOT/shared/tmp/dfmapbCNAPQ1*
-rw-r--r--. 1 apache apache 478 Mar 4 20:04 /mnt/sr/web/html/shared/tmp/dfmapbCNAPQ1.map
-rw-r--r--. 1 apache apache 6792 Mar 4 20:04 /mnt/sr/_web/html/shared/tmp/dfmapbCNAPQ1.png
-rw-r--r--. 1 apache apache 843 Mar 4 20:04 /mnt/sr/_web/html/shared/tmp/dfmapbCNAPQ1.dot
Hence it is not a problem with the 'referrer' as some have postulated...same referrer in 1 and 2.
The server log ONLY shows the image request...
192.168.2.254 - - [04/Mar/2023:20:42:14 -0500] "HEAD /shared/tmp/dfmapbCNAPQ1.png HTTP/1.1" 200 -
192.168.2.254 - - [04/Mar/2023:20:42:14 -0500] "GET /shared/tmp/dfmapbCNAPQ1.png HTTP/1.1" 200 6792
It's as if the browser never even tried. Firewall? Really? [Disabled, same result.] Same url path.
No error messages in the console log of dev tools for the requesting process.
So, I'm at a loss.
The 'host' of the above html is a foreground page of an extension.
The 'host' can access the image url shown above (the .png file) with <img src='...>
without any problem. The print button (open the image) button works fine. Its just the download that no longer (I repeat no longer) works.
Attached is a snippet of the screen shot show that you can visualize what I'm referencing.
And I am now getting this result from both google chrome and edge- firefox is kinda like 'give up all hope ye who enter here' so I don't have an example (anymore)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to scroll up animation in backLayerContent in jetpack compose I want to scroll first backLayerContent with frontLayerContent in BackdropScaffold. I want to Scroll Up animation inside my backLayerContent in Icon & Text. I am trying to learning from this article about AnimatedContent, but it is very hard to understand. Right now I used AnimatedContent content but it's going to fast and I didn't understand which direction is going the animation.
@OptIn(ExperimentalMaterialApi::class, ExperimentalAnimationApi::class)
@Composable
fun CollapsingTopAppBarStylingScreen() {
val context = LocalContext.current as ComponentActivity
val scaffoldState = rememberBackdropScaffoldState(BackdropValue.Revealed)
var isScrollAtTopYPosition by remember {
mutableStateOf(false)
}
LaunchedEffect(scaffoldState.progress) {
context.logE(">> --------Start-------")
context.logE(">> progress --> ${scaffoldState.progress}")
context.logE(">> --------End-------")
}
BackdropScaffold(
scaffoldState = scaffoldState,
appBar = {},
persistentAppBar = false,
backLayerContent = {
AnimatedContent(
targetState = isScrollAtTopYPosition,
) {
Column(
modifier = Modifier.padding(
top = 20.dp,
start = 16.dp,
bottom = 24.dp
),
) {
Icon(
imageVector = Icons.Default.ShoppingCart,
tint = Color.White,
contentDescription = null,
)
Text(
text = "Hello!! How are you?",
fontSize = 24.sp,
color = Color.White,
)
}
}
},
backLayerBackgroundColor = Color.Green,
frontLayerBackgroundColor = Color.White,
frontLayerScrimColor = Color.Transparent,
frontLayerContent = {
LazyColumn(
contentPadding = PaddingValues(horizontal = 24.dp, vertical = 24.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..40).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp),
color = Color.Black,
)
}
}
}
)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use GeoDataframe Points and Linestrings to build a Networkx graph? I have 2 GeoDataframes, one is points object, the other is Linestrings. Points are on Linestrings. How can I use these 2 gdfs to build a networkx graph?
I hope when I plot the graph, it will be consistent with realistic locations of GeoDataframes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nextjs app is not recognizing the js and styling of tw-elements library I want to use tw-elemts library with my Nextjs application, but every time I copy a code of some random components its styling and behavior is not working. I have followed all the steps int he quickstart and additionally I put an useEffect for importing the 'tw-elemts"int the _app.js as recommended by https://github.com/mdbootstrap/Tailwind-Elements/issues/1058
This is my component and inside there's the code from tw-elemts for a datepicker. What am i doing wrong?
Obviously my component is not seening any js file. Why? Thanks in advance
function DatePicker() {
return (
<div>
<div className="relative mb-3 xl:w-96" data-te-timepicker-init data-te-input-wrapper-init>
<input
type="text"
className="peer block min-h-[auto] w-full rounded border-0 bg-transparent py-[0.32rem] px-3 leading-[2.15] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 data-[te-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-neutral-200 dark:placeholder:text-neutral-200 [&:not([data-te-input-placeholder-active])]:placeholder:opacity-0"
id="form1"
/>
<label
for="form1"
className="pointer-events-none absolute top-0 left-3 mb-0 max-w-[90%] origin-[0_0] truncate pt-[0.37rem] leading-[2.15] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[1.15rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[te-input-state-active]:-translate-y-[1.15rem] peer-data-[te-input-state-active]:scale-[0.8] motion-reduce:transition-none dark:text-neutral-200 dark:peer-focus:text-neutral-200"
>
Select
</label>
</div>
</div>
)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FuncAnimation: Cannot animate a point and a line at the same time I am trying to make an animated plot to show the behavior of a simple harmonic oscillator. I would like for this animation to be a combination of the following two plots. That is, I would like the red square to go up and down, and on the same plot I would like the blue line to progressively be displayed.
Red square
Line
that is what I am having issues with. I cannot get my code to animate them both at the same time
This is the code I used to get the square to move up and down
%matplotlib notebook
import itertools
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["figure.figsize"] = 9,6
x_0, v_0, k, m = 1,2,1,2
omega = np.sqrt(k/m)
def HA(t):
xt = x_0*np.cos(omega*t) + (v_0/omega)*np.sin(omega*t)
return np.array([t, xt])
# create a figure with an axes
fig, ax = plt.subplots()
# set the axes limits
ax.axis([0.0,50,-4,4])
# create a point in the axes
point, = ax.plot(0,x_0, marker="s", color = 'red', markersize=20)
t_vector = np.linspace(0,50, 100)
xt_vector = x_0*np.cos(omega*t_vector) + (v_0/omega)*np.sin(omega*t_vector)
# Updating function, to be repeatedly called by the animation
def update(t):
#Point coordinates
t,xt = HA(t)
point.set_data([0],[xt])
return point
ani = animation.FuncAnimation(fig, update, interval=500, blit=True, repeat=True,frames=t_vector.size)
plt.axhline(y=0.0, color='black', linestyle='--', label = "Equilibrium")
plt.xlabel(r'$t$', fontsize=18)
plt.ylabel(r"$x(t)$", fontsize=16)
plt.legend()
#ani.save('Square.mp4', writer = 'ffmpeg', fps = 10)
plt.show()
And this is the code I used for the line
plt.rcParams["figure.figsize"] = 9,6
x_0, v_0, k, m = 1,2,1,2
omega = np.sqrt(k/m)
def HA(t):
xt = x_0*np.cos(omega*t) + (v_0/omega)*np.sin(omega*t)
return np.array([t, xt])
# create a figure with an axes
fig, ax = plt.subplots()
# set the axes limits
ax.axis([0.0,50,-4,4])
line, = ax.plot([], [], color="blue")
t_vector = np.linspace(0,50, 100)
xt_vector = x_0*np.cos(omega*t_vector) + (v_0/omega)*np.sin(omega*t_vector)
# Updating function, to be repeatedly called by the animation
def update(t):
line.set_data(t_vector[:t], xt_vector[:t])
return line
ani = animation.FuncAnimation(fig, update, interval=500, blit=True, repeat=True,frames=t_vector.size)
plt.axhline(y=0.0, color='black', linestyle='--', label = "Equilibrium")
plt.xlabel(r'$t$', fontsize=18)
plt.ylabel(r"$x(t)$", fontsize=16)
plt.legend()
#ani.save('Line.mp4', writer = 'ffmpeg', fps = 10)
plt.show()
I tried to just combine them both, but although this does not give any error, the resulting plot does not move. I am a rookie when it comes to animations with matplotlib, I checked the similar questions I could find, but none helped me. I could not extend their answers to get something useful for me.
plt.rcParams["figure.figsize"] = 9,6
x_0, v_0, k, m = 1,2,1,2
omega = np.sqrt(k/m)
def HA(t):
xt = x_0*np.cos(omega*t) + (v_0/omega)*np.sin(omega*t)
return np.array([t, xt])
# create a figure with an axes
fig, ax = plt.subplots()
ax.axis([0.0,50,-4,4])
# create a point in the axes
point, = ax.plot(0,x_0, marker="s", color = 'red', markersize=20)
line, = ax.plot([], [], color="blue")
t_vector = np.linspace(0,50, 100)
xt_vector = x_0*np.cos(omega*t_vector) + (v_0/omega)*np.sin(omega*t_vector)
# Updating function, to be repeatedly called by the animation
def update(t):
t,xt = HA(t)
line.set_data(t_vector[:t], xt_vector[:t])
point.set_data([0],[xt])
return line, point
ani = animation.FuncAnimation(fig, update, interval=500, blit=True, repeat=True,frames=t_vector.size)
plt.axhline(y=0.0, color='black', linestyle='--', label = "Equilibrium")
plt.xlabel(r'$t$', fontsize=18)
plt.ylabel(r"$x(t)$", fontsize=16)
plt.legend()
plt.show()
Could you help me, please?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you remove unused imports using GolangCI I enabled goimports in my GolangCI tool using my makefile and it's able to spot unused imports but is not automatically remove them. How do I enable my golangCI tool to remove the unused imports automatically?
Below is my makefile command for the golangci linting, I am using the --fix tag:
##@ Linting
lint:
@echo "lint via golangci-lint in " $(OUTPUT_DIR)/src
docker run --rm -v $(PWD):/local \
-w /local golangci/golangci-lint:latest \
golangci-lint run --fix --config .golangci.yaml $(OUTPUT_DIR)/src/*.go
Below is my golangci.yaml file, I am setting remove-unused to true :
run:
timeout: 5m
modules-download-mode: readonly
linters:
enable:
- errcheck
- goimports
- revive
- govet
- staticcheck
# Configuration for the goimports linter
goimports:
# Set to true to remove unused imports automatically
remove-unused: true
# Configuration for the revive linter
revive:
# Add any custom rules you want to use
rules:
- id: 'import-shadowing'
severity: warning
match: '\bimport\s+\.\s+\S+'
message: 'Importing packages using dot notation (.) is discouraged.'
issues:
exclude-use-default: false
max-issues-per-linter: 0
max-same-issues: 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to reference resources in the default value of a Terraform variable(type: tuple(object))? I'm trying to deploy multiple ec2 instances. This requires a variable below.
Post my variables:
variable "configuration" {
#description = "The total configuration, List of Objects/Dictionary"
default = [
{
"application_name" : "GritfyApp-dev",
"ami" : "ami-0263e4deb427da90e",
"no_of_instances" : "2",
"instance_type" : "t2.medium",
"subnet_id" : "subnet-0dd2853d1445a9990",
"vpc_security_group_ids" : ["sg-00e9778636a7aee5e","sg-082e93cadbd35fd8b"]
# "vpc_security_group_ids" : [aws_security_group.ssh-sg.id]
},
{
"application_name" : "ssh-dev",
"ami" : "ami-0747bdcabd34c712a",
"instance_type" : "t3.micro",
"no_of_instances" : "1"
"subnet_id" : "subnet-0dd2853d1445a9990"
"vpc_security_group_ids" : ["sg-00e9778636a7aee5e","sg-082e93cadbd35fd8b"]
# "vpc_security_group_ids" : [aws_security_group.ssh-sg.id]
},
{
"application_name" : "OpsGrit-dev",
"ami" : "ami-0747bdcabd34c712a",
"instance_type" : "t3.micro",
"no_of_instances" : "3"
"subnet_id" : "subnet-0dd2853d1445a9990"
"vpc_security_group_ids" : ["sg-00e9778636a7aee5e","sg-082e93cadbd35fd8b"]
# "vpc_security_group_ids" : [aws_security_group.ssh-sg.id]
}
]
}
Because vpc_security_group_ids is bound to the specified application_name. I can hard code it by "vpc_security_group_ids": ["sg-00e9778636a7aee5e", "sg-082e93cadbd35fd8b"]. But that's obviously not elegant enough.
I tried to use local to achieve, but still failed.
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if
you run "terraform apply" now.
root@Will-T-PC:/mnt/c/terraform-leaning-will/Expressions/deploy-multiple-ec2-for_each-2# terraform plan
╷
│ Error: Variables not allowed
│
│ on variables.tf line 17, in variable "configuration":
│ 17: "vpc_security_group_ids" : local.target_sg
│
│ Variables may not be used here.
╵
A: That's not possible. variables can't be dynamic which means they can't refer to any other variable nor locals.
Only local variables can be dynamic. So you have to use that instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 7 Error: undefined method `javascript_pack_tag' for # I have this on my application.rb, I wanted to put the stylesheets and the javascript tag, however, this would throw an error:
I commented it here as this will throw an error. I am currently using the default one:
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%# <%= stylesheet_link_tag 'application', media: 'all','data-turbolinks-track': 'reload' %> %>
<%# <% javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
Gem file:
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby "3.2.0"
# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.4", ">= 7.0.4.2"
# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
gem "sprockets-rails"
# Use postgresql as the database for Active Record
gem "pg", "~> 1.1"
# Use the Puma web server [https://github.com/puma/puma]
gem "puma", "~> 5.0"
# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"
# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"
# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"
# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"
# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"
# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
# gem "kredis"
# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]
# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false
# Use Sass to process CSS
# gem "sassc-rails"
# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"
group :development, :test do
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
gem "debug", platforms: %i[ mri mingw x64_mingw ]
end
group :development do
# Use console on exceptions pages [https://github.com/rails/web-console]
gem "web-console"
# Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
# gem "rack-mini-profiler"
# Speed up commands on slow machines / big apps [https://github.com/rails/spring]
# gem "spring"
end
group :test do
# Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
gem "capybara"
gem "selenium-webdriver"
gem "webdrivers"
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: r survey package: Geometric means adjusted for covariates From here:
library(survey)
data(nhanes)
nhanes_design <- svydesign(id=~SDMVPSU,
strata=~SDMVSTRA,
weights=~WTMEC2YR,
nest=TRUE, data=nhanes)
agesexmodel <- svyglm(HI_CHOL ~ agecat + RIAGENDR, design=nhanes_design, family=quasibinomial)
print(summary(agesexmodel))
## high cholesterol by race/ethnicity, adjusted for demographic differences
means <- svypredmeans(agesexmodel, ~factor(race))
print(means)
print(confint(means))
As I understand it, this gives the mean adjusted by the covariate race. How would I do the same to get covariate-adjusted geometric means?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django css and javascript app not served in production I have a django project which in development mode css are loaded just fine but not in production.
In my settings.py file I've set these trhee variables
STATIC_ROOT = BASE_DIR / 'staticfiles/' STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ]
I also set DEBUG = False
When I run python manage.py collectstatic command the staticfiles folder receives the files properly. I created a static folder in the root of the project to install bootstrap there, again, in developent runs just fine. I'm using Apache server throug XAMPP becasuse I'm on Windows. the configuration for the project is next:
`LoadFile "C:/Python310/python310.dll"
LoadModule wsgi_module "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd"
WSGIPythonHome "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k"
WSGIScriptAlias /outgoing "D:/DEV/PYTHON/GASTOS/software/outgoing/project/wsgi.py" application-group=%{GLOBAL}
WSGIPythonPath "D:/DEV/PYTHON/GASTOS/software/outgoing"
<Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/project">
Require all granted
Alias /static/ "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles/"
<Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles">
Require all granted
`
The point is, the app load well but without the bootstrap css and javascript files. Also the browser console tells this.
`Refused to apply style from 'http://localhost/outgoing/static/node_modules/bootstrap/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
GET http://localhost/outgoing/static/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js`
Help please.
A: With DEBUG=FALSE, it is expected that the static files folder will be located on an external resource, as this creates vulnerabilities for the site.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert mutable 2D array of pairs to a static 2D array in kotlin How can I convert:
mutableListOf<MutableList<Pair<Int, Int>>>
To a:
Array<Array<Pair<Int,Int>>>
I'm pretty new in the language of Kotlin, I thought that I can loop for the entire 2D array and put the values in the new one, but I was wondering if there's another faster solution
A:
I thought that I can loop for the entire 2D array and put the values in the new one
You can't actually explicitly "loop". When you create an Array of non-null elements in Kotlin you have to specify the default value at each index. So all you have to do is specify each element of the list:
// suppose list is a MutableList<MutableList<Pair<Int, Int>>>
// create an array of list.size...
Array(list.size) { i ->
// where the element at index i is another array with size "list[i].size"
Array(list[i].size) { j ->
// and the element at index j of this array is "list[i][j]"
list[i][j]
}
}
This is pretty much as fast as you can get in terms of execution time.
If you mean "fast" as in less typing, you can do:
list.map { it.toTypedArray() }.toTypedArray()
This first converts the inner lists to arrays, creating a List<Array<Pair<Int, Int>>>, and then converts that list to an array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ubuntu 22.04 need to update system without SSL Distributor ID: Ubuntu
Description: Ubuntu 22.04 LTS
Release: 22.04
Codename: jammy
Need "apt update" but without update Openssl
Need to keep *libssl1.1_1.1.1f-1ubuntu2.12_amd64.deb *and not update.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I am running unit test using Sentinel. Can I get the test result summary using junit AbstractTestResultAction? I am running unit test on sentinel policies using the command “sentinel test test-case-folder”in Jenkins. However, the test results are too extensive, only option available is to provide -json flag while running the Sentinel command. This will give the test result in a JSON output format yet still extensive. Can I get the test result summary using junit AbstractTestResultAction?
I have tried using junit AbstractTestResultAction in Jenkins . However, I dont think it will work because JUnit and Sentinel are entirely different unit test framework. Any suggestion will be highly appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Homework Help - Python For Data Analytics (Linear Regression Modelling) Part I:
Perform linear regression modelling to predict the delay in days (between the Planned
and Actual date) in processing the claims, explaining the approach taken, including
any further data pre-processing needed for modelling.
Part II:
Discuss the results obtained from the modelling and state the linear regression
equation.
I'm trying to perform linear regression modelling to predict the delays.
But I'm not so sure which values should I be putting into my X and Y axis.
At first, I thought of using a df['delay'] = pd.to_datetime(df['Planned']) - pd.to_datetime(df['Actual']) to plot one of the axis. But I am not sure what to do for the other axis, thought of using the count of delays but it wouldn't make sense.
Sorry in advanced. I'm quite new to this.
Code Snippet
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
df = pd.read_csv('test.csv', na_values=['Unkn', '???'])
# Count the number of missing values in each column
missing_counts = df.isna().sum()
# Print the number of missing values in each column
print('Missing value counts:\n', missing_counts)
# Drop rows with any missing value
df = df.dropna(axis = 0, how = "any")
# Print the updated number of rows and columns in the dataframe
# print('Updated dataframe shape:', df.shape)
model = LinearRegression()
model2 = LinearRegression()
planned = pd.to_datetime(df['Planned']).values.reshape(-1, 1)
actual = pd.to_datetime(df['Actual']).values.reshape(-1, 1)
df['Delay'] = (pd.to_datetime(df['Actual']) - pd.to_datetime(df['Planned'])).dt.days
# Fit the model on the planned and actual data
model.fit(planned, actual)
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape(-1, 1)
# model2.fit(df['Amount'],df['Delay'])
# Print the intercept and coefficients of the model
print("Intercept: ", model.intercept_)
print("Coefficient: ", model.coef_)
# print("Intercept: ", model2.intercept_)
# print("Coefficient: ", model2.coef_)
Sample csv to use
Claim_ID,Policy_No,Name,Planned,Actual,Created,Amount,Paid,Category,Terms,Region,Type2928509866,300764795,Roger Torres,17/1/2021,18/1/2021 0:00,20210112,3072.349,Yes,AT,AD23,LOC,L0012928511094,300434439,Jason Jones,5/2/2021,16/1/2021 0:00,20210130,910.944,Yes,AT,EC05,LOC,L0012928516927,300769623,Robert Martin,18/1/2021,14/1/2021 0:00,20210113,567.936,Yes,AT,AB27,LOC,L0012928517338,300794332,Stacy Anderson,15/1/2021,18/1/2021 0:00,20210110,181.651,Yes,AT,AE14,LOC,L0012928518375,300792283,Mr. Adam Whitaker III,5/2/2021,8/2/2021 0:00,20210131,238.74,Yes,AT,EC05,LOC,L0012928518381,300782669,Robert James,18/1/2021,22/1/2021 0:00,20210113,772.492,Yes,AT,AD23,LOC,L0012928521263,300739006,Amanda Garza,17/1/2021,23/1/2021 0:00,20210112,2854.26,Yes,AT,AD23,LOC,L0012928528363,300729942,Courtney Robbins,17/1/2021,22/1/2021 0:00,20210112,2898.78,Yes,AT,AD23,LOC,L0012928528375,300778870,Jonathan Peterson,19/1/2021,5/2/2021 0:00,20210115,5742.653,Yes,AT,AD23,LOC,L0012928531494,300742521,Mrs. Donna Keller,4/2/2021,22/1/2021 0:00,20210130,371.7,Yes,AT,EC05,LOC,L0012928532226,300756072,Lisa Vincent,23/1/2021,29/1/2021 0:00,20210118,1457.347,Yes,AT,DE16,LOC,L0012928532560,300718130,Andre Gonzalez,3/2/2021,23/1/2021 0:00,20210129,758.015,Yes,AT,EC05,LOC,L0012928532814,300418007,Joan Elliott,19/1/2021,22/1/2021 0:00,20210114,183.71,Yes,AT,AD23,LOC,L0012928532814,300418007,Joan Elliott,19/1/2021,22/1/2021 0:00,20210114,183.71,Yes,AT,AD23,LOC,L0012928533426,300769623,Troy Phillips,14/1/2021,9/1/2021 0:00,20210109,4271.192,Yes,AT,AB27,LOC,L0012928533509,300418007,Megan Hendricks,19/1/2021,22/1/2021 0:00,20210114,293.001,Yes,AT,AD23,LOC,L0012928533987,300726979,Denise Higgins,17/1/2021,22/1/2021 0:00,20210112,5558.286,Yes,AT,AD23,LOC,L0012928534458,300718130,Kathleen Parker,23/1/2021,29/1/2021 0:00,20210118,194.206,Yes,AT,DE16,LOC,L0012928535047,300290370,Sean Brown,16/1/2021,26/2/2021 0:00,20210112,1648.274,Yes,AT,AD23,LOC,L0012928536356,300762301,Chelsea Ibarra,14/1/2021,15/1/2021 0:00,20210109,503.221,Yes,AT,CD89,LOC,L001
main.py
Full CSV File
A: not so sure if this is the answer you are looking for but this might be a good solution or a sample answer.
A few things missing from your code might be converting the date format for year month day. As well as changing the format to days.
Here's my attempt at your questions. Let me know if you need any more help.
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
df = pd.read_csv('test.csv', na_values=['Unkn', '???'])
# Count the number of missing values in each column
missing_counts = df.isna().sum()
# Drop rows with any missing value
df = df.dropna(axis = 0, how = "any")
# convert to datetime of Planned
df['Planned'] = pd.to_datetime(df['Planned'], format='%d/%m/%Y')
# convert to yyyy-mm-dd format
df['Planned'] = df['Planned'].dt.strftime('%Y-%m-%d')
#convert datetime of Actual
df['Actual'] = pd.to_datetime(df['Actual'], format='%d/%m/%Y %H:%M')
# convert to yyyy-mm-dd format
df['Actual'] = df['Actual'].dt.strftime('%Y-%m-%d')
model = LinearRegression()
planned = pd.to_datetime(df['Planned']).dt.day.values.reshape(-1, 1)
actual = pd.to_datetime(df['Actual']).dt.day.values.reshape(-1, 1)
# Fit the model on the planned and actual data
model.fit(planned, actual)
# Print the intercept and coefficients of the model
print("Intercept: ", model.intercept_)
print("Coefficient: ", model.coef_)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: While(1) error in C language while working with characters # enter image description hereI made a character detector but when I put the While(1) code, the program seems to repeat the first two lines twice. I've got no idea why.
The error after I tried putting a while(1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Is there a way to get the x-axis coordinates of the left and right y axes when the x-axis is discrete in ggplot2? The title sort of says it all. With continuous data on the x-axis this is relatively easy to solve. The issue arises when the x-axis is categorial or discrete. I'd like to place annotations near the left and right y-axis lines but it seems impossible to either find or set them. You can't set with scale_x_discrete. And coord_cartesian isn't any help with setting the limits. Further layer_scales doesn't extract that information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to configure vscode to find clang libraries Following this SO answer I created a FindClassDecls.cpp file and I try to setup a VSCode in macOS to find the required clang headers. So I've tried to add the output of these two commands:
*
*llvm-config --cflags and
*clang -E - -v < /dev/null 2>&1 | grep "^ /" | grep clang
to the "includePath" entry in .vscode/c_cpp_properties.json. So my .json looks like this:
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/opt/homebrew/Cellar/llvm/15.0.7_1/include",
"/opt/homebrew/Cellar/llvm/15.0.7_1/lib/clang/15.0.7/include"
],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX13.sdk/System/Library/Frameworks"
],
"compilerPath": "/opt/homebrew/opt/llvm/bin/clang",
"cStandard": "c17",
"cppStandard": "c++14",
"intelliSenseMode": "macos-clang-arm64"
}
],
"version": 4
}
However, the required headers are still not found:
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/Tooling.h"
Any idea what could be missing?
My environment:
> clang --version
Homebrew clang version 15.0.7
Target: arm64-apple-darwin22.2.0
Thread model: posix
InstalledDir: /opt/homebrew/opt/llvm/bin
> llvm-config --version --prefix --includedir --libdir --libs
15.0.7
/opt/homebrew/Cellar/llvm/15.0.7_1
/opt/homebrew/Cellar/llvm/15.0.7_1/include
/opt/homebrew/Cellar/llvm/15.0.7_1/lib
-lLLVM-15
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find a missing file inside Bootstrap. please i need this file
php-email-form.php
with bootstrap -> /assets/vendor/php-email-form/php-email-form.php
I did not find this file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Unity Character Not Moving With Axis System Hello I am trying to make a 2D simple platformer and I am a begginer in Unity. For some reason when I hit arrow keys, my character will play the forward animation, but doesn't move at all. Then when I release it plays the idle animation. Also it won't jump either. Below I have code attached. I have researched and tryed many methods that tinker with the rigidbody but none of them work. Currently, I have a polygonal collider attached to both my player and ground. I also have a rigidbody attached to my character. I even tryed adding debug logs to show my move input. Soo far when I hit the arrow keys the moveinput changes. So, from my view I think there is a problem with the physics.
Any help would be appreciated,
thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpforce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform GroundCheck;
public float checkRadius;
public LayerMask whatIsground;
private int extraJumps;
public int extraJumpsValue;
private Animator anim;
void Start()
{
anim = GetComponent<Animator>();
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
moveInput = Input.GetAxis("Horizontal");
Debug.Log(moveInput);
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0)
{
Flip();
}else if(facingRight == true && moveInput < 0)
{
Flip();
}
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(GroundCheck.position, checkRadius, whatIsground);
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpforce;
extraJumps--;
}else if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps == 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpforce;
}
if (moveInput == 0)
{
anim.SetBool("isRunning", false);
}else
{
anim.SetBool("isRunning", true);
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do i need Hibernate Validator to run a Custom Spring Validator? I have a custom spring validator to validates a role DTO class but when I called it using @Valid annotation or by any other means (like data binder validation or calling validate method) nothing happens. I didn't understand if i'm doing something wrong, i have spring validation starter as dependency like so:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
But when i added the Hibernate Validator it started to validate normally but why? wasn't supposed to spring-boot-starter-validation solve that as it related to spring ?
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.0.Final</version>
</dependency>
DTO
@Getter @Setter
public class UserRegistrationDTO {
private String username;
private String password;
private String confirmPassword;
private String email;
}
Validator
@Component(value = "userRegistrationValidator")
public class UserRegistrationValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return UserRegistrationDTO.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
UserRegistrationDTO userRegistrationDTO = (UserRegistrationDTO) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"password", "password.empty", "The password must not be empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"confirmPassword", "cpassword.empty", "You have to confirm you password");
if (userRegistrationDTO.getPassword() != null) {
if (userRegistrationDTO.getPassword().length() < 5 || userRegistrationDTO.getPassword().length() > 25)
errors.rejectValue("password", "password.size", "The password size must be between 5 to 25");
if (userRegistrationDTO.getConfirmPassword() != null && !userRegistrationDTO.getPassword().equals(userRegistrationDTO.getConfirmPassword()))
errors.rejectValue("confirmPassword", "password.not_equals", "The password is not equals");
}
}
}
Controller
@Controller
@RequestMapping("/register")
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class RegisterController {
@Qualifier("userRegistrationValidator")
private final Validator validator;
@PostMapping
public String registerProcessing(@ModelAttribute("userRegistration") @RequestBody UserRegistrationDTO userRegistrationDTO, BindingResult bindingResult) {
ValidationUtils.invokeValidator(validator, userRegistrationDTO, bindingResult);
if (bindingResult.hasErrors()) {
return "login/signup";
}
// ...
return "redirect:/login";
}
}
My first attempt was setting the validator directly to the data binder. Therefore, i would not need to call the validator. Nothing happens.
@Qualifier("userRegistrationValidator")
private final Validator validator;
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.addValidators(validator);
}
My second attempt was call the validate method but it still doesn't work.
@PostMapping
public String registerProcessing(@ModelAttribute("userRegistration") @RequestBody UserRegistrationDTO userRegistrationDTO, BindingResult bindingResult) {
validator.validate(userRegistrationDTO, bindingResult);
if (bindingResult.hasErrors()) {
return "login/signup";
}
// ...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75639994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Promotion to Power bi investors workspace We are in the process of giving our investors access to power bi reports and dashboards. Currently these reports and dashboards are in respective workspaces of each departments such as sales, marketing, finance, supply chain etc. each department has their own power bi deployment pipelines (standard dev/test/prod stages). We don’t want to provide investors separate workspace for each department. We want investors to have single access point so that they can see these reports produced by individual departments at one place. We also have stricter controls on how reports are promoted to production department workspace. What are different ways we can achieve this? We were thinking about creating single workspace for investors and promote reports to it as soon as a report is promoted to individual production department workspace. Is this possible?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a For Loop that creates if statements I'm in CS2 for my college program and I've been tasked with creating code for a PokerCard class which extends off of a Card class that carries a bunch of methods which it overrides. In this particular instance, I am overriding the toString method for testing and am in the middle of writing a bunch of if statements. Is it possible to create a for loop that can loop the creation of my code? I tried inserting i's in place of ordinals for enums but am I stuck with this ugly code here? Thanks in advance!
/**
*
* An child of the Card class intended to Override the toString of the card
* class. The toString will output integer form followed by a suit symbol.
*
* @author Steven Lee
*
*/
// Implement PokerCard as an interface with Comparable
public class PokerCard extends Card {
/**
*
* Child constructor that copies the constructor of the parent Card. Create
* constructor.
*
* @param suit
* @param rank
*/
public PokerCard(Suit suit, Rank rank) {
super(suit, rank);
}
/**
* TODO Create compareTo Override here. comapareTo should be checking for card
* rank differences and sorting them from lowest rank to highest (2 to Ace).
*/
/**
* TODO Override toString from parent Card. This should print in the following
* format: "[Initial][Suit]. Initial is either an int or capitalized first
* letter of the rank. Suit will be output with unicode.
*/
@Override
public String toString() {
// Check for rank value. If J-A.
String letter = null;
String symbol = null;
if (PokerCard.this.getRank().equals(Rank.ACE)) {
letter = "A";
}
if (PokerCard.this.getRank().equals(Rank.KING)) {
letter = "K";
}
if (PokerCard.this.getRank().equals(Rank.QUEEN)) {
letter = "Q";
}
if (PokerCard.this.getRank().equals(Rank.JACK)) {
letter = "J";
}
if (PokerCard.this.getRank().equals(Rank.JACK)) {
letter = "J";
}
if (PokerCard.this.getRank().equals(Rank.TEN)) {
letter = "10";
}
if (PokerCard.this.getRank().equals(Rank.NINE)) {
letter = "9";
}
if (PokerCard.this.getRank().equals(Rank.EIGHT)) {
letter = "8";
}
if (PokerCard.this.getRank().equals(Rank.SEVEN)) {
letter = "7";
}
if (PokerCard.this.getRank().equals(Rank.SIX)) {
letter = "6";
}
if (PokerCard.this.getRank().equals(Rank.FIVE)) {
letter = "5";
}
if (PokerCard.this.getRank().equals(Rank.FOUR)) {
letter = "4";
}
if (PokerCard.this.getRank().equals(Rank.THREE)) {
letter = "3";
}
if (PokerCard.this.getRank().equals(Rank.TWO)) {
letter = "2";
}
if (PokerCard.this.getSuit().equals(Suit.SPADES)) {
symbol = "\u2660";
}
if (PokerCard.this.getSuit().equals(Suit.HEARTS)) {
symbol = "\u2665";
}
if (PokerCard.this.getSuit().equals(Suit.DIAMONDS)) {
symbol = "\u2666";
}
if (PokerCard.this.getSuit().equals(Suit.CLUBS)) {
symbol = "\u2663";
}
return letter + symbol;
}
}
I'm hoping to streamline the "if" statement creation process. Or if there is a better way to arrange this toString, I'd greatly appreciate that as well. thank you in advance. (Note that as far as the exercise goes, there is no need to add the red colored suit variants)
A: String letter = "";
String symbol = "";
Rank rank = PokerCard.this.getRank();
Suit suit = PokerCard.this.getSuit();
if (rank.ordinal() >= 8 && rank.ordinal() <= 12) {
letter = Character.toString((char) ('A' + rank. Ordinal() - 8));
} else if (rank. Ordinal() >= 0 && rank.ordinal() <= 6) {
letter = Integer.toString(rank. Ordinal() + 2);
} else if (rank == Rank.TEN) {
letter = "10";
}
swrank. Ordinal{
case SPADES:
symbol = "\u2660";
break;
case HEARTS:
symbol = "\u2665";
break;
case DIAMONDS:
symbol = "\u2666";
break;
case CLUBS:
symbol = "\u2663";
break;
}
return letter + symbol;
we use the ordinal value of the Rank enum to determine the letter value. We check if the ordinal value is between 8 and 12 (inclusive) for the face cards (A, K, Q, J), and between 0 and 6 (inclusive) for the number cards (2-9). For the rank value of 10, we use a separate if statement to assign the value "10" to the letter variable.
We also use a switch statement to determine the symbol value based on the Suit enum.enter code here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C#: how to capture user input to the textbox while he is entering? When the user types to the textbox, I want to constantly capture the input and as soon as it matches certain condition the program will automatically submit for the user. I haven't found any sample code yet after searching.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Having a list of yaml cron expressions, how to get them properly in my config and then access them per SpEL expression? In a legacy job system on a Linux system I have a Cron expression like that
30 08 28 * 5 /home/me/myJob.sh
to let myJob run at 08:30 each 28th of a month and every Friday. "And" a Human Being would state here, but it is not exactly right from a IT perspective. Actually it is OR: a day which is the 28th of a month or is a Friday. That is exactly what the Linux Cron does: on the date or the day. For the current month of March/2023 it runs on 3rd, 10th, 17th, 24th, 28th, and 31st.
Unfortunately the Spring people thought the other way around. In German there is a common saying "What kind of horse had been riding them!". In the context of a @Scheduled(cron = "00 30 08 28 * 5") expression it is indeed an "AND": a day which is Friday the 28th. For the current month March/2023 it will not run at all because the 28th is not a Friday.
This dilemma leads us to being required to state the above legacy Cron condition in a Spring Boot system writing two @Scheduled expressions in a @Schedules construct.
Best practice would be to have them in a Yaml properties file:
my:
job:
properties:
schedules:
- "00 30 08 28 * *"
- "00 30 08 * * 5"
The corresponding Spring configuration bean should be:
@Configuration
@ConfigurationProperties(prefix = "my.job.properties")
public class myConfig {
private List<String> schedules;
public List<String> getSchedules() {
return schedules;
}
public void setSchedules(List<String> schedules) {
this.schedules = schedules;
}
}
With that I should be able to define my job:
@Schedules({
@Scheduled(cron = "${myConfig.schedules[0]}"),
@Scheduled(cron = "${myConfig.schedules[1]}")
})
public void myJob() {
...
}
or
@Schedules({
@Scheduled(cron = "#{${my.job.properties.schedules}[0]}",
@Scheduled(cron = "#{${my.job.properties.schedules}[1]}"
})
public void myJob() {
...
}
But both don't work for me. The task myJob does not start at all.
What do I wrong? Did I miss something? Are the SpEL's wrong?
What I brought to work was using two properties schedule1 and schedule2, having two String attributes in myConfig with these names and values "30 * * * * *" and "11 * * * * *" and using them in the two @Scheduled(cron = ...) expressions.
Any help would be appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to handle changing the content on a PDF file in a Swift app? I am developing a PDF editing application on iOS using Swift and I am having trouble handling changes to the content on a PDF file. I have tried using Apple's PDFKit, but it does not support changing the content on a PDF.
I want to ask if there is any other technology that I can use to handle changes to the content on a PDF file within my application. I have heard about Core Graphics and Quartz, but I am unsure how to use them to achieve my goal.
Has anyone encountered this problem before and can guide me on how to achieve this? Any suggestions, documentation, or recommended technologies would be greatly appreciated. Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to safely package youtube api auth inside built electron app I want to include YouTube API auth (such as uploading videos to youtube) inside my electron app, which I build and release for the mac/win/linux desktop app stores.
I have a working proof of concept:
https://github.com/MartinBarker/electron-youtube-upload
Which relies on the user downloading a credentials .json file:
{
"installed": {
"client_id": "123123123.googleusercontent.com",
"project_id": "132123123",
"auth_uri": "132123123",
"token_uri": "132123123",
"auth_provider_x509_cert_url": "132123123",
"client_secret": "132123123",
"redirect_uris": [
"http://localhost"
]
}
}
and placing it in their electron dev repo. The electron app will use this auth.json file to generate a url, which the user visits in their browser, where they sign in, and then an access code is provided, which the electron app picks up on and uses so the user can upload youtube videos to their account.
As you can see this process relies on the auth.json file which contains vars such as client_id and client_secret. I want to ship my app with this feature, but don't want to include this hardcoded auth.json file in my built product, because of these reasons:
*
*including client_secret in the packaged app could easily be viewed if someone de-packaged my app
*including the hard-coded project_id var means if i want to swap/replace my google cloud youtube v3 api project, I would need to generate a new auth.json and repackage/rebuild/ship a completely new version.
If all I'm doing is providing the user a link for them to login, is there a better way I could include this functionality safely and securely within my electron app?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error for the usage of system exit function I have used the System.exit() function inside the if...else block, but
it is showing my syntax errors and runtime errors,
one of the major errors is:
main.java:58: error: method exit in class System cannot be applied to given types;
System.exit();
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 error.
My code is:
import java.util.Scanner;
class main
{
/* Instance variables:
* int vno
* int hours
* double bill;
*
* Member methods:
* void frontend-1()
* void backend()
* To compute the parking charge at the rate $3 for the first
* hour of part thereof, and $1.50 for each additon hour of part therefore
* void frontend-2() */
int vno; //to store the vehicle number
int hours; //to store the hours the vehicle had been
String name; //to store the name of customer
double bill; //to store the total bill
main()
{
vno=0;
hours=0;
name="";
bill=0.0;
}
void frontend1()
{
//Initializing the scanner class
Scanner sc = new Scanner(System.in);
//Taking input from the user
System.out.println("\t|<NIR-NIMESH PARKING LOT>|");
System.out.println("-------------------------------");
System.out.print("name of customer: ");
name = sc.nextLine();
System.out.println();
System.out.print("time of vehicle stay(in hours): ");
hours = sc.nextInt();
System.out.println("THANK YOU");
}
void backend()
{
//if the car is parked for less than one hour
if(hours<1)
{
bill=3.0;
}
//if the car is parked for more than one hour
else if(hours>1)
{
bill = 1.50*hours;
}
//if invalid input is received from the user
else
{
System.out.println("INVALID INPUT");
System.exit();
}
}
void frontend2()
{
System.out.println("_________________________________");
System.out.println("Name: "+name);
System.out.println("Stay of the vehicle in hour: "+hours);
System.out.println("Total Bill: "+bill);
}
public static void main()
{
main obj = new main();
obj.frontend1();
obj.backend();
obj.frontend2();
}
}
I have tried several methods and also tried putting the system.exit () functions in different places but it didn't work out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: actual and formal argument lists differ in length no argument found enter image description here the program
enter image description here the part the causes the error
enter image description here the file that has the error
enter image description here the error
i cannot change the FractionTester file
only the reciprocal method
i should get the reciprocal fraction 22/7 but instead i get this error
this is the fraction tester:
Fraction f1 = new Fraction( 44,14 ); // reduces to 22/7
System.out.println( "f1=" + f1 ); // should output 22/7
Fraction f2 = new Fraction( 21,14 ); // reduces to 3/2
System.out.println( "f2=" + f2 ); // should output 3/2
System.out.println( f1.add( f2 ) ); // should output 65/14
System.out.println( f1.subtract( f2 ) ); // should output 23/14
System.out.println( f1.multiply( f2 ) ); // should output 33/7
System.out.println( f1.divide( f2 ) ); // should output 44/21
System.out.println( f1.reciprocal() ); // should output 7/22'
this is the code i used to print out the last statement:
which is the same one I've used for the others and they worked
public Fraction reciprocal (Fraction other)
{
return new Fraction ( this.denom , this.numer);
}
and this is the error:
FractionTester.java:20: error: method reciprocal in class Fraction cannot be applied to given types;
System.out.println( f1.reciprocal() ); // should output 7/22
^
required: Fraction
found: no arguments
reason: actual and formal argument lists differ in length
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: How to exchange files between Windows 10 guest VM on Linux Arch Host using qemu virtmanger and guestmount while VM is running I am using Garuda, an Arch based Distro with xfce desktop on a Lenovo Thinkpad T480 with i7 8 log. Cores and 32 GB RAM.
I installeda qemu and virt-manager via:
sudo pacman -S qemu virt-manager
sudo systemctl start virtlogd.service
sudo systemctl enable libvirtd.service
sudo virsh net-start default**
sudo pacman -S ebtables dnsmasq
Then I setup the Windows 10 VM using the .iso Image and 4 log. cores and 16000 MB RAM, and after the Installation I used the virtio-win-0.1.229.iso image for the drivers for the virtual devices. Then I installed on the host the libguestfs-tools package with:
sudo pacman -S libguestfs
made a mounting directory for file exchange between Host and Guest with
sudo mkdir /mnt/sda2
mounted the qemu-Win 10-Image with:
sudo guestmount -a /var/lib/libvirt/images/win10.qcow2 -m /dev/sda2 /mnt/sda2
and then I could exchange as root, files from the Host via /mnt/sda2 to the C:\ drive of the Windows 10 Guest
but then I mounted the win10.qcow2-Image the VM doesn't start up, "the Image is already in use".
What can I do to have access from Guest to Host-directory or Host to Guest-directory while the VM is running?
Is it a rights-problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Following the Ruby on Rails Tutorial: Microposts Controller Test Error when I tested the Microposts controller, this is what it shows:
1st Error:
Failure:
MicropostsControllerTest#test_should_create_micropost
"Micropost.count" didn't change by 1.
Expected: 3
Actual: 2
2nd Error:
Failure:
MicropostsControllerTest#test_should_update_micropost
Expected response to be a <3XX: redirect>, but was a <422: Unprocessable Entity>
Micropost Controller:
class MicropostsController < ApplicationController
before_action :set_micropost, only: %i[ show edit update destroy ]
# GET /microposts or /microposts.json
def index
@microposts = Micropost.all
end
# GET /microposts/1 or /microposts/1.json
def show
end
# GET /microposts/new
def new
@micropost = Micropost.new
end
# GET /microposts/1/edit
def edit
end
# POST /microposts or /microposts.json
def create
@micropost = Micropost.new(micropost_params)
respond_to do |format|
if @micropost.save
format.html { redirect_to micropost_url(@micropost), notice: "Micropost was successfully created." }
format.json { render :show, status: :created, location: @micropost }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @micropost.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /microposts/1 or /microposts/1.json
def update
respond_to do |format|
if @micropost.update(micropost_params)
format.html { redirect_to micropost_url(@micropost), notice: "Micropost was successfully updated." }
format.json { render :show, status: :ok, location: @micropost }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @micropost.errors, status: :unprocessable_entity }
end
end
end
# DELETE /microposts/1 or /microposts/1.json
def destroy
@micropost.destroy
respond_to do |format|
format.html { redirect_to microposts_url, notice: "Micropost was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_micropost
@micropost = Micropost.find(params[:id])
end
# Only allow a list of trusted parameters through.
def micropost_params
params.require(:micropost).permit(:content, :user_id)
end
end
User Controller:
class UsersController < ApplicationController
before_action :set_user, only: %i[ show edit update destroy ]
# GET /users or /users.json
def index
@users = User.all
end
# GET /users/1 or /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users or /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to user_url(@user), notice: "User was successfully created." }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1 or /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to user_url(@user), notice: "User was successfully updated." }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1 or /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: "User was successfully destroyed." }
format.json { head :no_content }
end
end
#show micropost for the user
def show
@user = User.find(params[:id])
@micropost = @user.microposts.first
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a list of trusted parameters through.
def user_params
params.require(:user).permit(:name, :email)
end
end
Models:
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: {maximum: 140},
presence: true
end
class User < ApplicationRecord
has_many :microposts
validates :name, presence: true
validates :email, presence: true
end
How can I fix these errors?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating a view sql with intersect with multiple tables why can't i create this view with intersect
create view vw_Countries
as
select * from (
select distinct country from [dbo].[CO2_Data]
intersect
select distinct country from [dbo].[Maize_Production]
intersect
select distinct country from [dbo].[Maize_Yields]
intersect
select distinct country from [dbo].[Rice_Production]
intersect
select distinct country from [dbo].[Rice_Yields]
intersect
select distinct country from [dbo].[Surface_Temperature_Anomaly]
intersect
select distinct country from [dbo].[Wheat_Production]
intersect
select distinct country from [dbo].[Wheat_Yields])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I move box to the right corner <html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css"></link>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<title>PM</title>
<style>
.margin-left{
margin-left: 10px;
}
</style>
</head>
<body>
<div class="content">
<div id='pm-header' class="margin-left my-3 shadow shadow-gray-50 border-cyan-100 border-solid border-2 overflow-hidden"></div>
<div id="box" class="margin-left box border-2 border-solid border-gray-500"></div>
<div id="friends" class="flex-1 border-2 border-solid border-gray-500"></div>
<input class='mx-3' type="text" id="snd">
</div>
</body>
<script>
function resize(){
var win_h = $(window).height();
$('#pm-header').height(win_h - 500);
var htmlhd = $('#pm-header').height();
var nh = win_h - htmlhd - 100;
$('#box').height(nh);
$("#box").width($(window).width() - 260);
$("#pm-header").width($(window).width() - 260);
$("#snd").width($('#box').width());
$("#friends").width($(window).width() - $('#pm-header').width() - 50)
$("#friends").height($("#box").height() + $('#pm-header').height())
}
$(window).on('resize', function(){resize()});
resize();
</script>
</html>
im using tailwindcss im trying to move #friends to the right corner and fill that space and i dont know how
im using tailwindcss im trying to move #friends to the right corner and fill that space and i dont know how
like this but on right
how i want it
A: It depends on your use case, based on your how i want it image , i am giving my possible solutions
*
*Use fractionally width
<div class="content">
<div id="pm-header" class="margin-left my-3 overflow-hidden border-2 border-solid border-cyan-100 shadow shadow-gray-50">Header</div>
<div class="flex">
<div id="box" class="box w-2/6 border-2 border-solid border-gray-500">Box</div>
<div id="friends" class="flex-1 border-2 border-solid border-gray-500">Friends</div>
</div>
</div>
*Use flex-1
<div class="content">
<div id="pm-header" class="margin-left my-3 overflow-hidden border-2 border-solid border-cyan-100 shadow shadow-gray-50">Header</div>
<div class="flex">
<div id="box" class="box border-2 border-solid border-gray-500">Box</div>
<div id="friends" class="flex-1 border-2 border-solid border-gray-500">Friends</div>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to solve this error java.util.ConcurrentModificationException . i was writing a program to show occurence of letters using thread package thread;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.Scanner;
//concurrent modification error because of modifying map concurrently
class occurence extends Thread {
String s;
//HashMap
HashMap<Character, Integer> map;
occurence(String s,HashMap<Character,Integer> map){
this.s=s;
this.map=map;
}
public void run(){
for(int i=0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}else{
map.put(s.charAt(i), 1);
}
}
}
}
class Main{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
HashMap<Character,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
String s=sc.next();
occurence o= new occurence(s,map);
o.start();
}
for(Entry<Character,Integer> entry:map.entrySet()){
System.out.println(entry.getKey()+entry.getValue());
}
sc.close();
}
}
[](https://i.stack.imgur.com/883jx.png)
how to solve this error java.util.ConcurrentModificationException . i was writing a program to show occurence of letters using thread .i was expecting output as it would print character followed by their occurrences.
A: There are several issues with your code.
Once you start the processing in a thread, you should wait for it to complete. You can do this by calling the join() method on the thread.
But, this will cause the main thread to wait for the result before processing the next user-inputted string.
Next, you aren't handling multiple inputs from the user. This again depends on how you want to handle the threads.
*
*If you want to create one thread for each input and okay to wait till the processing is done, you can print the result (map contents) after the thread has completed its work.
*If you don't want to be blocked by the thread, then you have to start the threads, store the reference to them in a list and then wait for their completion at the end. You also have to create one map instance for each thread and store them as well so that you can print all of them at the end.
*
*(As a more advanced approach) You can also use an ExecutorService to submit multiple tasks and wait for their completion. If you are interested, you can search about this.
To keep it simple, assuming you want to create a thread for processing and will wait for it to complete before moving to process the next input, you can change your code as,
for (int i = 0; i < n; i++) {
String s = sc.next();
HashMap<Character, Integer> map = new LinkedHashMap<>();
Occurrence o = new Occurrence(s, map);
o.start();
o.join();
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "" + entry.getValue());
}
}
You can notice several modifications:
*
*I've used a LinkedHashMap to maintain the insertion order (as per your requirement). Also, creating one new map for each input processing.
*Calling o.join() to wait for the thread to complete.
*Moved the for loop to print the map contents inside the first for loop. When you have a char + int, it will convert the character to an integer and perform numeric addition. To avoid it, I've concatenated the character with an empty string. Or you can call .toString() on the Character instance as well.
*Renamed the occurence class as Occurrence to follow Java's naming convention.
Finally, don't close the Scanner backed up by System.in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: R: argument matches multiple formal arguments in R m <- metagen(TE=metagen$cohen.s.d, se=metagen$se, studlab=paste(metagen$author, metagen$year, sep=","), sm="Cohen'd", backtransf=TRUE)
Error in metagen(TE = metagen$cohen.s.d, se = metagen$se, studlab = paste(metagen$author, :
argument 2 matches multiple formal arguments
I don't know what to do. Please help, thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i update the javascript file so the effect applies on the container and it contents only when the page is scrolled? I am creating a project where a container contains images that scrolls inside of the container when the user scrolls the page. the container it self grow or shrink based on the scroll speed so it changes the css transform style, and inputs transform value based on the speed of the scroll. So as you are scrolling, there is a bulge effect applied to any object in the center of the page (When so scroll up and down it's growing the container div of the image)
Here is the effect i want to recreate :
THE effect
Original version
Here is the javascript file :
const container = document.querySelector('.container');
const images = document.querySelectorAll('.container img');
const containerHeight = container.offsetHeight;
const centerPosition = window.innerHeight / 2;
function updateScrollPosition() {
const scrollPosition = window.scrollY;
const scrollSpeed = Math.abs(window.scrollY - containerHeight) / 100;
const bulgeAmount = -1 * scrollSpeed;
const newContainerHeight = containerHeight + scrollSpeed;
const translateY = Math.max(-2000, Math.min(0, bulgeAmount));
container.style.height = `${newContainerHeight}px`;
container.style.transform = `translateY(${translateY}px)`;
images.forEach(image => {
const imageTopPosition = image.getBoundingClientRect().top;
const distanceFromCenter = centerPosition - imageTopPosition;
const imageBulgeAmount = bulgeAmount / 5;
const imageTranslateY = Math.max(-2000, Math.min(0, imageBulgeAmount));
image.style.transform = `translate3d(0px, ${imageTranslateY}px, 0px)`;
});
}
window.addEventListener('scroll', updateScrollPosition);
In this implementation, we calculate the scroll speed as the absolute difference between the current scroll position and the original container height, divided by 100. We then use this value to adjust the height of the container and the translateY value. We also adjust the translateY value of each image individually based on the bulgeAmount value. The Math.max and Math.min functions are used to prevent the translateY value from exceeding a certain range, to avoid visual glitches. The translate3d CSS property is used to enable hardware acceleration for smoother performance.
*
*Here is the html file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Distortion and Bounce Effect with Three.js</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./js/app.js"></script>
<div class="container">
<img src="img/img51.jpg" />
<img src="img/img52.jpg" />
<img src="img/img64.jpg" />
<img src="img/img71.jpg" />
</div>
</body>
</html>
*
*Here is the style.css file :
.body{
background-color: rgb(110, 109, 109);
}
.container{
border-radius: 16px;
height: 550px;
width: 750;
max-width: 800px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
overflow: hidden;
overflow-y: scroll;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.container img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 16px;
}
@media only screen and (min-width: 350px) {
/* Set a specific width for larger screens */
.container {
width: 80%;
}
}
For this effect i tried to use the pixijs.io algorithm but it didn't create the effect that i want
Here is the result :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bulge Effect on Scroll</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/6.1.3/pixi.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
overflow-x: hidden;
background-color: #222222;
}
#canvas-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80vw;
height: 80vh;
border-radius: 16px;
overflow: hidden;
}
</style>
</head>
<body>
<div id="canvas-container"></div>
<script>
const canvasContainer = document.getElementById('canvas-container');
const app = new PIXI.Application({
width: canvasContainer.offsetWidth,
height: canvasContainer.offsetHeight,
backgroundColor: 0x222222
});
canvasContainer.appendChild(app.view);
// Create a container for the images
const container = new PIXI.Container();
container.width = app.screen.width;
container.height = app.screen.height;
container.position.set(app.screen.width / 2, app.screen.height / 2);
app.stage.addChild(container);
// Load the images
const loader = new PIXI.Loader();
const images = [
'img/img51.jpg',
'img/img52.jpg',
'img/img64.jpg',
'img/img71.jpg'
];
images.forEach((img) => loader.add(img));
loader.load(setup);
// Setup the images
function setup() {
images.forEach((img) => {
const texture = PIXI.Texture.from(img);
const sprite = new PIXI.Sprite(texture);
sprite.anchor.set(0.5);
sprite.width = app.screen.width;
sprite.height = app.screen.height;
container.addChild(sprite);
});
// Apply bulge effect on scroll
let scrollPosition = 0;
const maxScroll = -2000;
app.ticker.add(() => {
const delta = (scrollPosition - window.scrollY) * 0.1;
scrollPosition = window.scrollY;
container.children.forEach((sprite) => {
const x = sprite.x - app.screen.width / 2;
const y = sprite.y - app.screen.height / 2;
const distance = Math.sqrt(x * x + y * y);
const angle = Math.atan2(y, x);
const radius = distance / 20;
const distortionX = Math.sin(angle * 10) * radius * delta;
const distortionY = Math.cos(angle * 10) * radius * delta;
sprite.position.set(sprite.x + distortionX, sprite.y + distortionY);
});
container.scale.y = PIXI.utils.clamp(1 + (scrollPosition / maxScroll), 1, 2);
});
}
</script>
</body>
</html>
In this script, i used the PIXI.Application class to create a new PixiJS application and add it to the canvas-container div. I then created a container for the images, loaded the images using a PIXI.Loader, and added them to the container.
But as you can see it's not that good.
So does anyone knows how to create this type of animation ? :
originale effect
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to correctly layout websites? I want to learn how to correctly layout websites. But there are many forms and properties and tools.
What is the general rule for correctly create the webiste layout?
There are some old properties still usable and some new methods. How to do it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Appcheck token is not printing any more for Adroid (It was printing fine before) I have Flutter mobile app that I am currently developing locally while using real android device and Firebase emulator in the backend. I am using Appcheck and the token was printing all the time to the console. Recently, I noticed that the Appcheck token does not print any more. I have not make any change related to Appcheck from my side.
I am using firebase_app_check: ^0.1.1+12
How can I get Appcheck token to print again?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i fix the error "Must use import to load ES Module"? I found this error while testing with jest.
Must use import to load ES Module: ...\node_modules\react-markdown\index.js
1 | import React from "react";
2 | import styled from "styled-components";
> 3 | import MDEditor from "@uiw/react-md-editor";
| ^
4 |
5 | import { useNavigate } from "react-router-dom";
6 |
at Runtime.requireModule (node_modules/jest-runtime/build/index.js:840:21)
at Object.require (node_modules/@uiw/react-markdown-preview/src/index.tsx:2:1)
at Object.<anonymous> (node_modules/@uiw/react-md-editor/src/Editor.tsx:2:1)
at Object.<anonymous> (node_modules/@uiw/react-md-editor/src/index.tsx:1:1)
at Object.require (src/components/Card.tsx:3:1)
at Object.require (src/pages/MainPage/Main.tsx:1:1)
at Object.require (src/App.tsx:1:1)
at Object.require (src/index.test.js:4:1)
Here is my jest.config.js file.
jest: {
roots: ["<rootDir>/src"],
collectCoverageFrom: [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts",
"!**/node_modules/**",
],
globals: {
"js-jest": {
useESM: true,
},
},
extensionsToTreatAsEsm: [".js"],
setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
testMatch: [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}",
],
testEnvironment: "jsdom",
transform: { "^.+\\.(js|jsx|ts|tsx)?$": "babel-jest" },
transformIgnorePatterns: ["node_modules/(?!react-markdown/)"],
moduleNameMapper: {
"^.+\\.svg$": "jest-svg-transformer",
"\\.(css|less|scss|sass)$": "identity-obj-proxy",
},
moduleFileExtensions: ["js", "ts", "jsx", "tsx", "json", "node"],
resetMocks: true,
},
and babel.config.js
presets: [
"@babel/preset-react",
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-typescript",
],
script
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
I've tried many things, but I can't find the problem.
I am not using react-markdown, so can I know why this error occurs?
add the script : "--experimental-vm-modules node_modules/jest/bin/jest.js"
add the 'globals' in jest.config.js : "js-jest": {useESM: true,},
A: Add this line to your package.json file :
"type": "module",
Take a look here to see How to move CommonJS project to ESM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why image always shows under buttons? The ImageView is placed under the two buttons in xml file, but when the ImageView is moved programmatically to the buttons' position, the buttons cover the ImageView.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NewGameViewActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bgColor" />
<Button
android:id="@+id/back_button"
android:layout_width="160px"
android:layout_height="160px"
android:text="BACK"
android:layout_gravity="top|start"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"/>
<Button
android:id="@+id/undo_button"
android:layout_width="160px"
android:layout_height="160px"
android:text="UNDO"
android:layout_gravity="top|end"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"/>
<ImageView
android:id="@+id/tutorial_hand"
android:layout_width="140px"
android:layout_height="140px"
android:gravity="center"
android:src="@drawable/hand" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't reach my flask api running on port 5000 from other devices on the network. Tried firewall. Tried router. Stumped I am working on an Android app using a Windows 11 pc as both the app dev environment and also a flask/python backend api for it.
I can get the app in the emulator to reach the api at its address, ie. 192.168.0.100:5000. But the same address on my phone and other laptop just returns a timeout.
I've tried adding inbound rules to the windows machine firewall (local port 5000, remopte port all ports).
I've tried disabling the firewall.
I've tried adding port forwarding on the router from 5000 to 5000 for the reserved IP of the pc.
I am running the flask app as host=0.0.0.0 from the command line
Nothing seems to work. The service works fine when I'm on the pc both from browser, postman, and the android emulator. But it's dead everywhere else on the wifi and I need to be on an actual phone to properly test everything.
I'm at the end of my networking knowledge and don't know where else to look. Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to extract cardinality of key value pairs in a given column I have a table that contains two columns metric and dimensionName=dimensionValue key value pairs such that the data is stored as:
metric
dimensions
A
{x=1, y=2, z=3}
A
{x=1, y=2, z=3}
A
{x=2, y=2, z=3}
A
{x=2, y=3, z=3}
A
{x=3, y=4, z=3}
I want to get all the unique combinations involving dimensions x and y in this table ie I want to treat x=1,y=2 as the same combination in row 1 and 2 so ultimately the cardinality of key value pairs involving x and y in this table will be 4 since there will be 4 unique combinations of x and y values (x=1,y=2), (x=2,y=2), (x=2,y=3) and (x=3,y=4).
So far I tried using unnest but that is giving me two columns dimensionName and dimensionValue but I was not sure how to get the unique combo with x and y values being in different rows
SELECT
dimension_name, dimension_value
FROM
"metrics"
CROSS JOIN
UNNEST(dimensions) AS dimension_map(dimension_name, dimension_value)
WHERE metric='A' AND dimension_name IN ('x', 'y');
Any help is highly appreciated. Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|