content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Pytorch lightning logger doesn't work as expected Good evening, I am a beginner in Pytorch lightning and I am trying to implement a NN and plot the graph (loss and accuracy) on various sets. The code is this one def training_step(self, train_batch, batch_idx): X, y = train_batch y_copy = y # Integer y for the accuracy X = X.type(torch.float32) y = y.type(torch.float32) # forward pass y_pred = self.forward(X).squeeze() # accuracy accuracy = Accuracy() acc = accuracy(y_pred, y_copy) # compute loss loss = self.loss_fun(y_pred, y) self.log_dict({'train_loss': loss, 'train_accuracy': acc}, on_step=False, on_epoch=True, prog_bar=True, logger=True) return loss def validation_step(self, validation_batch, batch_idx): X, y = validation_batch X = X.type(torch.float32) # forward pass y_pred = self.forward(X).squeeze() # compute metrics accuracy = Accuracy() acc = accuracy(y_pred, y) loss = self.loss_fun(y_pred, y) self.log_dict({'validation_loss': loss, 'validation_accuracy': acc}, on_step=False, on_epoch=True, prog_bar=True, logger=True) return loss def test_step(self, test_batch, batch_idx): X, y = test_batch X = X.type(torch.float32) # forward pass y_pred = self.forward(X).squeeze() # compute metrics accuracy = Accuracy() acc = accuracy(y_pred, y) loss = self.loss_fun(y_pred, y) self.log_dict({'test_loss': loss, 'test_accuracy': acc}, on_epoch=True, prog_bar=True, logger=True) return loss After training the NN, I run this peace of code: metrics = pd.read_csv(f"{trainer.logger.log_dir}/metrics.csv") del metrics["step"] metrics and I obtain this It is okay than on the validation set there's only one accuracy and one loss, because I am performing an hold out CV. On the test set, I noticed that the value test_accuracy=0.97 is the mean of all the accuracy for each epoch. with that I can't see the intermediate values (for each epoch) and then I can't plot any curve. It would be useful also when I'll do a cross validation with KFold. Why he's taking the mean and How can I see the intermediate results ? For the training_step it works properly, I can't figure out why the logger doesn't perform the same print for the test_step. Can someone help me please ? A: It looks like the test_step method is logging the metrics using the on_epoch parameter, which means that the logged values will be averaged over the entire epoch and only logged once per epoch. To log the metrics at each step, you should set the on_epoch parameter to False in the test_step method like this: self.log_dict({'test_loss': loss, 'test_accuracy': acc}, on_epoch=False, prog_bar=True, logger=True) This will log the loss and accuracy at each step in the test_step method, allowing you to see the intermediate values and plot the curve.
Pytorch lightning logger doesn't work as expected
Good evening, I am a beginner in Pytorch lightning and I am trying to implement a NN and plot the graph (loss and accuracy) on various sets. The code is this one def training_step(self, train_batch, batch_idx): X, y = train_batch y_copy = y # Integer y for the accuracy X = X.type(torch.float32) y = y.type(torch.float32) # forward pass y_pred = self.forward(X).squeeze() # accuracy accuracy = Accuracy() acc = accuracy(y_pred, y_copy) # compute loss loss = self.loss_fun(y_pred, y) self.log_dict({'train_loss': loss, 'train_accuracy': acc}, on_step=False, on_epoch=True, prog_bar=True, logger=True) return loss def validation_step(self, validation_batch, batch_idx): X, y = validation_batch X = X.type(torch.float32) # forward pass y_pred = self.forward(X).squeeze() # compute metrics accuracy = Accuracy() acc = accuracy(y_pred, y) loss = self.loss_fun(y_pred, y) self.log_dict({'validation_loss': loss, 'validation_accuracy': acc}, on_step=False, on_epoch=True, prog_bar=True, logger=True) return loss def test_step(self, test_batch, batch_idx): X, y = test_batch X = X.type(torch.float32) # forward pass y_pred = self.forward(X).squeeze() # compute metrics accuracy = Accuracy() acc = accuracy(y_pred, y) loss = self.loss_fun(y_pred, y) self.log_dict({'test_loss': loss, 'test_accuracy': acc}, on_epoch=True, prog_bar=True, logger=True) return loss After training the NN, I run this peace of code: metrics = pd.read_csv(f"{trainer.logger.log_dir}/metrics.csv") del metrics["step"] metrics and I obtain this It is okay than on the validation set there's only one accuracy and one loss, because I am performing an hold out CV. On the test set, I noticed that the value test_accuracy=0.97 is the mean of all the accuracy for each epoch. with that I can't see the intermediate values (for each epoch) and then I can't plot any curve. It would be useful also when I'll do a cross validation with KFold. Why he's taking the mean and How can I see the intermediate results ? For the training_step it works properly, I can't figure out why the logger doesn't perform the same print for the test_step. Can someone help me please ?
[ "It looks like the test_step method is logging the metrics using the on_epoch parameter, which means that the logged values will be averaged over the entire epoch and only logged once per epoch. To log the metrics at each step, you should set the on_epoch parameter to False in the test_step method like this:\nself.log_dict({'test_loss': loss, 'test_accuracy': acc}, on_epoch=False, prog_bar=True, logger=True)\n\nThis will log the loss and accuracy at each step in the test_step method, allowing you to see the intermediate values and plot the curve.\n" ]
[ 0 ]
[]
[]
[ "deep_learning", "machine_learning", "neural_network", "pytorch", "pytorch_lightning" ]
stackoverflow_0074669022_deep_learning_machine_learning_neural_network_pytorch_pytorch_lightning.txt
Q: Excel: Highlight cells based on search bar, but remove highlights when user clicks I have an excel sheet with lots of data. I would like to implement a "search box" at the top, where a user can type in a term/string, click a button, and excel will highlight any cell that contains the string. However, I also want these cells to "un-highlight" once the user mouse clicks anywhere in the document. I cannot seem to find the VBA code for this...mainly the last part. Thanks I was trying to solve the problem with Conditional Formatting but couldn't make it work, so now I am looking to VBA for the solution. However, I am not familiar with mouseclick properties. A: Conditional Formatting + VBA to clear The following formula in the "Use formula to determine which cells to format" will highlight any cells that "contain" the search phrase: =NOT(ISERROR(FIND($C$2,B5,1))) You can see we use `FIND([the search bar value in $C$2 ], [in dynamic B5 so it applieas separately to each cell in search range],[starting at 1]). If it finds the value it will not be error, if it doesn't find, it will be error. If we delete the cell contents, all will be formatted. to fix this we can either amend our formula to include an if statement checking if search bar is empty, or simply add a second conditional formatting: =ISBLANK($C$2) If you want to make the formatting clear when to click away, then you need to access the VBA worksheet module: Next you'll want to paste the following code: Option Explicit Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim sBar As Range Set sBar = Range("C2") If Selection.Address <> sBar.Offset(1, 0).Address Then sBar.Value = "" End Sub Finished Product:
Excel: Highlight cells based on search bar, but remove highlights when user clicks
I have an excel sheet with lots of data. I would like to implement a "search box" at the top, where a user can type in a term/string, click a button, and excel will highlight any cell that contains the string. However, I also want these cells to "un-highlight" once the user mouse clicks anywhere in the document. I cannot seem to find the VBA code for this...mainly the last part. Thanks I was trying to solve the problem with Conditional Formatting but couldn't make it work, so now I am looking to VBA for the solution. However, I am not familiar with mouseclick properties.
[ "Conditional Formatting + VBA to clear\nThe following formula in the \"Use formula to determine which cells to format\" will highlight any cells that \"contain\" the search phrase:\n\n=NOT(ISERROR(FIND($C$2,B5,1)))\n\n\nYou can see we use `FIND([the search bar value in $C$2 ], [in dynamic B5 so it applieas separately to each cell in search range],[starting at 1]).\nIf it finds the value it will not be error, if it doesn't find, it will be error.\nIf we delete the cell contents, all will be formatted. to fix this we can either amend our formula to include an if statement checking if search bar is empty, or simply add a second conditional formatting:\n\n=ISBLANK($C$2)\n\n\nIf you want to make the formatting clear when to click away, then you need to access the VBA worksheet module:\n\nNext you'll want to paste the following code:\nOption Explicit\n\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n\n Dim sBar As Range\n Set sBar = Range(\"C2\")\n If Selection.Address <> sBar.Offset(1, 0).Address Then sBar.Value = \"\"\n\nEnd Sub\n\nFinished Product:\n\n\n\n" ]
[ 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074605155_excel_vba.txt
Q: what is the meaning of the line bboxes= utils.format_boxes(bboxes,height,weight) I'm trying for object tracking using webcam using yolov4. I want to know the meaning of this line -> bboxes = utils.format_boxes(bboxes, original_h, original_w). I'm using https://github.com/theAIGuysCode/yolov4-deepsort.git repository for cloning. One can find the above line in object_tracer.py file. - line 151. # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, width, height original_h, original_w, _ = frame.shape bboxes = utils.format_boxes(bboxes, original_h, original_w) A: The answer is literally in the comment at the first line of the code you pasted. This method translates bounding boxes in normalized coordinates (xmin, ymin, xmax, y max) to not normalized coordinates (xmin, ymin, width, height). Coordinates are usually expressed in pixels, which is the not normalized form. Normalized coordinates are ones that are divided by the image dimensions, i.e. numbers between 0 and 1. The point (xmin, ymin) is the top-left corner of the bounding box and (xmax, ymax) the bottom-right one. (width, height) is simply the dimensio of the bounding box.
what is the meaning of the line bboxes= utils.format_boxes(bboxes,height,weight)
I'm trying for object tracking using webcam using yolov4. I want to know the meaning of this line -> bboxes = utils.format_boxes(bboxes, original_h, original_w). I'm using https://github.com/theAIGuysCode/yolov4-deepsort.git repository for cloning. One can find the above line in object_tracer.py file. - line 151. # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, width, height original_h, original_w, _ = frame.shape bboxes = utils.format_boxes(bboxes, original_h, original_w)
[ "The answer is literally in the comment at the first line of the code you pasted.\nThis method translates bounding boxes in normalized coordinates (xmin, ymin, xmax, y max) to not normalized coordinates (xmin, ymin, width, height).\nCoordinates are usually expressed in pixels, which is the not normalized form. Normalized coordinates are ones that are divided by the image dimensions, i.e. numbers between 0 and 1.\nThe point (xmin, ymin) is the top-left corner of the bounding box and (xmax, ymax) the bottom-right one. (width, height) is simply the dimensio of the bounding box.\n" ]
[ 0 ]
[]
[]
[ "python", "yolov4" ]
stackoverflow_0074645659_python_yolov4.txt
Q: Normalizing location data Before I ask the question I just want to say that I am a backend engineer and have no experience in data science, but I'm trying to look into the machine learning solution for this problem and any sort of answer that what I'm trying to do is impossible or that I should be looking into something different is appreciated. I'm working on a project and we currently want to normalize location data. User has free text input, and we want to try and map that into a row in the predefined table of all the locations in the world, if possible, and get country, state and city. So we want to map input => {country, state, city} for example Schwäbisch Gmünd, Baden-Württemberg, Deutschland => Germany, Baden-Württemberg, Schwäbisch Gmünd United States, Los Angeles => United States, California, Los Angeles United States => United States, null, null Tuscany => Italy, Tuscany, null Wien => Austria, Vienna, Vienna Is this possible to do this with machine learning? If it is what should we be looking into? A: Yes, it is possible to use machine learning to map free-text input to locations in a predefined table. One approach to solve this problem would be to use a natural language processing (NLP) model to extract the relevant location information from the free-text input and then use a machine learning model to map that information to the predefined table of locations. To train the NLP model, you would need a large dataset of free-text input containing location information, along with the corresponding location information in structured format (i.e. the {country, state, city} format you mentioned in your question). This dataset could be used to train the NLP model to extract the relevant location information from the free-text input. Once the NLP model has been trained and is able to extract the relevant location information from the free-text input, you could then use a machine learning model to map that information to the predefined table of locations. This could be done using a supervised learning approach, where the model is trained on a dataset of location information in the {country, state, city} format, along with the corresponding location in the predefined table of locations. Overall, this is a challenging problem to solve, but it is certainly possible to use machine learning to normalize location data in the way you described. I would recommend consulting with a data scientist or machine learning expert to help you design and implement a solution for this problem.
Normalizing location data
Before I ask the question I just want to say that I am a backend engineer and have no experience in data science, but I'm trying to look into the machine learning solution for this problem and any sort of answer that what I'm trying to do is impossible or that I should be looking into something different is appreciated. I'm working on a project and we currently want to normalize location data. User has free text input, and we want to try and map that into a row in the predefined table of all the locations in the world, if possible, and get country, state and city. So we want to map input => {country, state, city} for example Schwäbisch Gmünd, Baden-Württemberg, Deutschland => Germany, Baden-Württemberg, Schwäbisch Gmünd United States, Los Angeles => United States, California, Los Angeles United States => United States, null, null Tuscany => Italy, Tuscany, null Wien => Austria, Vienna, Vienna Is this possible to do this with machine learning? If it is what should we be looking into?
[ "Yes, it is possible to use machine learning to map free-text input to locations in a predefined table. One approach to solve this problem would be to use a natural language processing (NLP) model to extract the relevant location information from the free-text input and then use a machine learning model to map that information to the predefined table of locations.\nTo train the NLP model, you would need a large dataset of free-text input containing location information, along with the corresponding location information in structured format (i.e. the {country, state, city} format you mentioned in your question). This dataset could be used to train the NLP model to extract the relevant location information from the free-text input.\nOnce the NLP model has been trained and is able to extract the relevant location information from the free-text input, you could then use a machine learning model to map that information to the predefined table of locations. This could be done using a supervised learning approach, where the model is trained on a dataset of location information in the {country, state, city} format, along with the corresponding location in the predefined table of locations.\nOverall, this is a challenging problem to solve, but it is certainly possible to use machine learning to normalize location data in the way you described. I would recommend consulting with a data scientist or machine learning expert to help you design and implement a solution for this problem.\n" ]
[ 1 ]
[]
[]
[ "artificial_intelligence", "machine_learning" ]
stackoverflow_0074668782_artificial_intelligence_machine_learning.txt
Q: In keycloak how to deploy a custom validator for custom user attribute within declarative user profile? Hello keycloak extension experts, I have enabled successfully the declarative user profile (https://www.keycloak.org/docs/latest/server_admin/#user-profile). I would like now to "deploy" a custom-made validator. (KC 18.0 embedded wildfly) I have trouble to understand how I need to package my validator to make it available in the admin console UI. I did with maven a jar as for an eventListener extension spi (which used to work very fine) with a ProviderFactory and a Provider. Yet, the validator is not proposed in the console UI as a validator. Deployment seems successful. I wonder if my packaging is wrong or if there is an extra step required. By the way I had a look to https://github.com/thomasdarimont/keycloak-extension-playground/blob/master/custom-user-profile-extension/src/main/java/com/github/thomasdarimont/keycloak/userprofile/validator/AgeValidator.java but here it lacks the packaging stage as far as I can see You can find the code below. I duplicated the code for the out of the box LengthValidator. org.keycloak.validate.ValidatorFactory lu.lns.keycloak.custom.validator.LengthValidatorProviderFactory LengthValidatorProviderFactory.java package lu.lns.keycloak.custom.validator; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.validate.Validator; import org.keycloak.validate.ValidatorFactory; public class LengthValidatorProviderFactory implements ValidatorFactory { @Override public Validator create(KeycloakSession session) { return new LengthValidatorProvider(); } @Override public void init(Config.Scope config) { } @Override public void postInit(KeycloakSessionFactory factory) { } @Override public String getId() { return "lns-length-validator"; } } LengthValidatorProvider package lu.lns.keycloak.custom.validator; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.keycloak.models.KeycloakSession; import org.keycloak.provider.ConfiguredProvider; import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.validate.AbstractStringValidator; import org.keycloak.validate.ValidationContext; import org.keycloak.validate.ValidationError; import org.keycloak.validate.ValidationResult; import org.keycloak.validate.ValidatorConfig; import org.keycloak.validate.validators.ValidatorConfigValidator; /** * String value length validation - accepts plain string and collection of strings, for basic behavior like null/blank * values handling and collections support see {@link AbstractStringValidator}. Validator trims String value before the * length validation, can be disabled by {@link #KEY_TRIM_DISABLED} boolean configuration entry set to * <code>true</code>. * <p> * Configuration have to be always provided, with at least one of {@link #KEY_MIN} and {@link #KEY_MAX}. */ public class LengthValidatorProvider extends AbstractStringValidator implements ConfiguredProvider { public static final LengthValidatorProvider INSTANCE = new LengthValidatorProvider(); public static final String ID = "lns-length"; public static final String MESSAGE_INVALID_LENGTH = "LNS-error-invalid-length"; public static final String KEY_MIN = "min"; public static final String KEY_MAX = "max"; public static final String KEY_TRIM_DISABLED = "trim-disabled"; private static final List<ProviderConfigProperty> configProperties = new ArrayList<>(); static { ProviderConfigProperty property; property = new ProviderConfigProperty(); property.setName(KEY_MIN); property.setLabel("Minimum length"); property.setHelpText("The minimum length"); property.setType(ProviderConfigProperty.STRING_TYPE); configProperties.add(property); property = new ProviderConfigProperty(); property.setName(KEY_MAX); property.setLabel("Maximum length"); property.setHelpText("The maximum length"); property.setType(ProviderConfigProperty.STRING_TYPE); configProperties.add(property); } @Override public String getId() { return ID; } @Override protected void doValidate(String value, String inputHint, ValidationContext context, ValidatorConfig config) { Integer min = config.getInt(KEY_MIN); Integer max = config.getInt(KEY_MAX); if (!config.getBooleanOrDefault(KEY_TRIM_DISABLED, Boolean.FALSE)) { value = value.trim(); } int length = value.length(); if (config.containsKey(KEY_MIN) && length < min.intValue()) { context.addError(new ValidationError(ID, inputHint, MESSAGE_INVALID_LENGTH, min, max)); return; } if (config.containsKey(KEY_MAX) && length > max.intValue()) { context.addError(new ValidationError(ID, inputHint, MESSAGE_INVALID_LENGTH, min, max)); return; } } @Override public ValidationResult validateConfig(KeycloakSession session, ValidatorConfig config) { Set<ValidationError> errors = new LinkedHashSet<>(); if (config == null || config == ValidatorConfig.EMPTY) { errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); } else { if (config.containsKey(KEY_TRIM_DISABLED) && (config.getBoolean(KEY_TRIM_DISABLED) == null)) { errors.add(new ValidationError(ID, KEY_TRIM_DISABLED, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_BOOLEAN_VALUE, config.get(KEY_TRIM_DISABLED))); } boolean containsMin = config.containsKey(KEY_MIN); boolean containsMax = config.containsKey(KEY_MAX); if (!(containsMin || containsMax)) { errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); } else { if (containsMin && config.getInt(KEY_MIN) == null) { errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, config.get(KEY_MIN))); } if (containsMax && config.getInt(KEY_MAX) == null) { errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, config.get(KEY_MAX))); } if (errors.isEmpty() && containsMin && containsMax && (config.getInt(KEY_MIN) > config.getInt(KEY_MAX))) { errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_VALUE)); } } } return new ValidationResult(errors); } @Override public String getHelpText() { return "LNS Length validator"; } @Override public List<ProviderConfigProperty> getConfigProperties() { return configProperties; } } NB: I cross-posted the same question into keycloak forum. A: AbstractStringValidator implements both the Validator and ValidatorFactory. Therefore, you don't need to implement a separate factory for you custom SPI. Also, the META-INF directory should have services as a subdirectory, not META-INF.services (this is probably why it isn't working). If you remove the factory and put the LengthValidatorProvider in the META-INF file then it should work.
In keycloak how to deploy a custom validator for custom user attribute within declarative user profile?
Hello keycloak extension experts, I have enabled successfully the declarative user profile (https://www.keycloak.org/docs/latest/server_admin/#user-profile). I would like now to "deploy" a custom-made validator. (KC 18.0 embedded wildfly) I have trouble to understand how I need to package my validator to make it available in the admin console UI. I did with maven a jar as for an eventListener extension spi (which used to work very fine) with a ProviderFactory and a Provider. Yet, the validator is not proposed in the console UI as a validator. Deployment seems successful. I wonder if my packaging is wrong or if there is an extra step required. By the way I had a look to https://github.com/thomasdarimont/keycloak-extension-playground/blob/master/custom-user-profile-extension/src/main/java/com/github/thomasdarimont/keycloak/userprofile/validator/AgeValidator.java but here it lacks the packaging stage as far as I can see You can find the code below. I duplicated the code for the out of the box LengthValidator. org.keycloak.validate.ValidatorFactory lu.lns.keycloak.custom.validator.LengthValidatorProviderFactory LengthValidatorProviderFactory.java package lu.lns.keycloak.custom.validator; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.validate.Validator; import org.keycloak.validate.ValidatorFactory; public class LengthValidatorProviderFactory implements ValidatorFactory { @Override public Validator create(KeycloakSession session) { return new LengthValidatorProvider(); } @Override public void init(Config.Scope config) { } @Override public void postInit(KeycloakSessionFactory factory) { } @Override public String getId() { return "lns-length-validator"; } } LengthValidatorProvider package lu.lns.keycloak.custom.validator; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.keycloak.models.KeycloakSession; import org.keycloak.provider.ConfiguredProvider; import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.validate.AbstractStringValidator; import org.keycloak.validate.ValidationContext; import org.keycloak.validate.ValidationError; import org.keycloak.validate.ValidationResult; import org.keycloak.validate.ValidatorConfig; import org.keycloak.validate.validators.ValidatorConfigValidator; /** * String value length validation - accepts plain string and collection of strings, for basic behavior like null/blank * values handling and collections support see {@link AbstractStringValidator}. Validator trims String value before the * length validation, can be disabled by {@link #KEY_TRIM_DISABLED} boolean configuration entry set to * <code>true</code>. * <p> * Configuration have to be always provided, with at least one of {@link #KEY_MIN} and {@link #KEY_MAX}. */ public class LengthValidatorProvider extends AbstractStringValidator implements ConfiguredProvider { public static final LengthValidatorProvider INSTANCE = new LengthValidatorProvider(); public static final String ID = "lns-length"; public static final String MESSAGE_INVALID_LENGTH = "LNS-error-invalid-length"; public static final String KEY_MIN = "min"; public static final String KEY_MAX = "max"; public static final String KEY_TRIM_DISABLED = "trim-disabled"; private static final List<ProviderConfigProperty> configProperties = new ArrayList<>(); static { ProviderConfigProperty property; property = new ProviderConfigProperty(); property.setName(KEY_MIN); property.setLabel("Minimum length"); property.setHelpText("The minimum length"); property.setType(ProviderConfigProperty.STRING_TYPE); configProperties.add(property); property = new ProviderConfigProperty(); property.setName(KEY_MAX); property.setLabel("Maximum length"); property.setHelpText("The maximum length"); property.setType(ProviderConfigProperty.STRING_TYPE); configProperties.add(property); } @Override public String getId() { return ID; } @Override protected void doValidate(String value, String inputHint, ValidationContext context, ValidatorConfig config) { Integer min = config.getInt(KEY_MIN); Integer max = config.getInt(KEY_MAX); if (!config.getBooleanOrDefault(KEY_TRIM_DISABLED, Boolean.FALSE)) { value = value.trim(); } int length = value.length(); if (config.containsKey(KEY_MIN) && length < min.intValue()) { context.addError(new ValidationError(ID, inputHint, MESSAGE_INVALID_LENGTH, min, max)); return; } if (config.containsKey(KEY_MAX) && length > max.intValue()) { context.addError(new ValidationError(ID, inputHint, MESSAGE_INVALID_LENGTH, min, max)); return; } } @Override public ValidationResult validateConfig(KeycloakSession session, ValidatorConfig config) { Set<ValidationError> errors = new LinkedHashSet<>(); if (config == null || config == ValidatorConfig.EMPTY) { errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); } else { if (config.containsKey(KEY_TRIM_DISABLED) && (config.getBoolean(KEY_TRIM_DISABLED) == null)) { errors.add(new ValidationError(ID, KEY_TRIM_DISABLED, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_BOOLEAN_VALUE, config.get(KEY_TRIM_DISABLED))); } boolean containsMin = config.containsKey(KEY_MIN); boolean containsMax = config.containsKey(KEY_MAX); if (!(containsMin || containsMax)) { errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE)); } else { if (containsMin && config.getInt(KEY_MIN) == null) { errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, config.get(KEY_MIN))); } if (containsMax && config.getInt(KEY_MAX) == null) { errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, config.get(KEY_MAX))); } if (errors.isEmpty() && containsMin && containsMax && (config.getInt(KEY_MIN) > config.getInt(KEY_MAX))) { errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_VALUE)); } } } return new ValidationResult(errors); } @Override public String getHelpText() { return "LNS Length validator"; } @Override public List<ProviderConfigProperty> getConfigProperties() { return configProperties; } } NB: I cross-posted the same question into keycloak forum.
[ "AbstractStringValidator implements both the Validator and ValidatorFactory. Therefore, you don't need to implement a separate factory for you custom SPI.\nAlso, the META-INF directory should have services as a subdirectory, not META-INF.services (this is probably why it isn't working).\nIf you remove the factory and put the LengthValidatorProvider in the META-INF file then it should work.\n" ]
[ 0 ]
[]
[]
[ "keycloak" ]
stackoverflow_0072463813_keycloak.txt
Q: Elements of array gets pushed to index 0 in a new array rather than sequentially So I'm using a forEach loop on an Array of objects. This forEach loop gives the array of objects an ID concatenated with a number. // e = object from different array this.vertices.forEach((e) => { if (e === s) { // this.nodeIDS = the ID // this.nodeIdCount = the number I give to the ID this.start_node_key = e.setID(`${this.nodeIDS + this.nodeIdCount}`); this.adjacencyList.set(this.start_node_key, [n]); } else if (e === n) { this.nothing_node_key = e.setID(`${this.nodeIDN + this.nodeIdCount}`); this.adjacencyList.set(this.nothing_node_key, [p,n]); } else if (e === w) { this.wall_node_key = e.setID(`${this.nodeIDW + this.nodeIdCount}`); this.adjacencyList.set(this.nothing_node_key, [p]); } else if (e === p) { this.path_node_key = e.setID(`${this.nodeIDP + this.nodeIdCount}`); this.adjacencyList.set(this.path_node_key, [n,w,g]); } else if (e === g) { this.goal_node_key = e.setID(`${this.nodeIDG + this.nodeIdCount}`); this.adjacencyList.set(this.goal_node_key, [p]) } else { console.log("unread elements"); } this.nodeIdCount++ console.log(e.getID()) }); In a different class I have 2 methods. setID and getID. The theory is I want the setID method to push each element from the forEach loop into an array sequentially. However, all the elements are pushed into index 0 rather than array[0] = element_0 array[1] = element_1 etc //Takes in the argument "this.nodeID + this.nodeIdCount" setID(id_number) { this.id_number = id_number; let new_id_number_array = [id_number]; // array I want with the id_numbers in sequence this.new_id_number_array = new_id_number_array; } // Return this.nodeID + this.nodeIdCount getID() { return this.new_id_number_array[1] //returns undefined but this.new_id_number_array[0] returns all the id_number } I tried using a forEachLoop inside the setID method on newidnumberarray but it returned the same results because it is only reading 1 element in my array setID(id_number) { this.id_number = id_number; let new_id_number_array = [id_number]; // array I want with the id_numbers in sequence let new_new_id_number_array = []; // forEach loop logic being it pushes a sequence of ids into the new_new array new_id_number_array.forEach((e) => { new_new_id_number_array.push(e) }) A: It looks like the issue is that you are using the same array new_id_number_array for every object in the vertices array. As a result, when you call the setID method on each object, it updates the same array new_id_number_array with the new id_number. This means that the array only ever contains the last id_number that was set, and all previous values are overwritten. To fix this, you need to create a separate array for each object in the vertices array. You can do this by creating the new_id_number_array array inside the setID method, like this: setID(id_number) { this.id_number = id_number; let new_id_number_array = [id_number]; // Create a new array for each object this.new_id_number_array = new_id_number_array; } This way, each object in the vertices array will have its own new_id_number_array array, which will only contain the id_number that was set for that object.
Elements of array gets pushed to index 0 in a new array rather than sequentially
So I'm using a forEach loop on an Array of objects. This forEach loop gives the array of objects an ID concatenated with a number. // e = object from different array this.vertices.forEach((e) => { if (e === s) { // this.nodeIDS = the ID // this.nodeIdCount = the number I give to the ID this.start_node_key = e.setID(`${this.nodeIDS + this.nodeIdCount}`); this.adjacencyList.set(this.start_node_key, [n]); } else if (e === n) { this.nothing_node_key = e.setID(`${this.nodeIDN + this.nodeIdCount}`); this.adjacencyList.set(this.nothing_node_key, [p,n]); } else if (e === w) { this.wall_node_key = e.setID(`${this.nodeIDW + this.nodeIdCount}`); this.adjacencyList.set(this.nothing_node_key, [p]); } else if (e === p) { this.path_node_key = e.setID(`${this.nodeIDP + this.nodeIdCount}`); this.adjacencyList.set(this.path_node_key, [n,w,g]); } else if (e === g) { this.goal_node_key = e.setID(`${this.nodeIDG + this.nodeIdCount}`); this.adjacencyList.set(this.goal_node_key, [p]) } else { console.log("unread elements"); } this.nodeIdCount++ console.log(e.getID()) }); In a different class I have 2 methods. setID and getID. The theory is I want the setID method to push each element from the forEach loop into an array sequentially. However, all the elements are pushed into index 0 rather than array[0] = element_0 array[1] = element_1 etc //Takes in the argument "this.nodeID + this.nodeIdCount" setID(id_number) { this.id_number = id_number; let new_id_number_array = [id_number]; // array I want with the id_numbers in sequence this.new_id_number_array = new_id_number_array; } // Return this.nodeID + this.nodeIdCount getID() { return this.new_id_number_array[1] //returns undefined but this.new_id_number_array[0] returns all the id_number } I tried using a forEachLoop inside the setID method on newidnumberarray but it returned the same results because it is only reading 1 element in my array setID(id_number) { this.id_number = id_number; let new_id_number_array = [id_number]; // array I want with the id_numbers in sequence let new_new_id_number_array = []; // forEach loop logic being it pushes a sequence of ids into the new_new array new_id_number_array.forEach((e) => { new_new_id_number_array.push(e) })
[ "It looks like the issue is that you are using the same array new_id_number_array for every object in the vertices array. As a result, when you call the setID method on each object, it updates the same array new_id_number_array with the new id_number. This means that the array only ever contains the last id_number that was set, and all previous values are overwritten.\nTo fix this, you need to create a separate array for each object in the vertices array. You can do this by creating the new_id_number_array array inside the setID method, like this:\nsetID(id_number) {\n this.id_number = id_number;\n let new_id_number_array = [id_number]; // Create a new array for each object\n this.new_id_number_array = new_id_number_array;\n}\n\nThis way, each object in the vertices array will have its own new_id_number_array array, which will only contain the id_number that was set for that object.\n" ]
[ 0 ]
[]
[]
[ "arrays", "foreach", "javascript" ]
stackoverflow_0074671832_arrays_foreach_javascript.txt
Q: Can we add webhook url directly inside the pinescript indicator/strategy? I just created an indicator and also backtested it using strategy tester. Now I wish to run it automated with a 3rd party application. How can i add their webhook url in alert programmatically? any code snippets would be amazing!! I am new to pinescript A: This is not possible. You can only configure the alert message programmatically not the webhook URL. A: you can not add url in scrip of tv if you want to do algo trading there is a way to do it ~> bro if you have subscription of tv 1st create broker api and secret key copy it 2nd paste api and secreat key in 3party application bot then bot give you a url copy it . 3st create a alert based on condition and write messages what you want to send to bot so he understand it when to buy/sell order application so that bot can understand 4nd paste url in alert action menu in webhook box 5th As alert triger send message to bot . bot exicute order on broker or exchange if you dont have a subscription plan it has difficult to do it there is other way to do it it will different 1st open a website https://pipedream.com/@/new/build this link create a work flow in triger use email as a triger copy email 1st create a alert in alert there is a alert option email to sms click on that paste here 2nd send http post request and paste bot url here 3rd message send to bot by pipedream and bot will exicute order A: you can not add url in scrip of tv if you want to do algo trading there is a way to do it ~> bro if you have subscription of tv 1st create broker api and secret key copy it 2nd paste api and secreat key in 3party application bot then bot give you a url copy it . 3st create a alert based on condition and write messages what you want to send to bot so he understand it when to buy/sell order application so that bot can understand 4nd paste url in alert action menu in webhook box 5th As alert triger send message to bot . bot exicute order on broker or exchange if you dont have a subscription plan it has difficult to do it there is other way to do it it will different 1st open a website https://pipedream.com/@/new/build this link create a work flow in triger use email as a triger copy email 1st create a alert in alert there is a alert option email to sms click on that paste here and verify emai otp send to pipedream workflow `~> body in text 2nd click on + button of workflow send http post request and paste bot url there 3rd message send to bot by pipedream and bot will exicute order
Can we add webhook url directly inside the pinescript indicator/strategy?
I just created an indicator and also backtested it using strategy tester. Now I wish to run it automated with a 3rd party application. How can i add their webhook url in alert programmatically? any code snippets would be amazing!! I am new to pinescript
[ "This is not possible. You can only configure the alert message programmatically not the webhook URL.\n", "you can not add url in scrip of tv\nif you want to do algo trading there is a way to do it ~>\nbro if you have subscription of tv\n1st create broker api and secret key copy it\n2nd paste api and secreat key in 3party application bot then bot give you a url\ncopy it .\n3st create a alert based on condition and write messages what you want to send\nto bot so he understand it when to buy/sell order\napplication so that bot can understand\n4nd paste url in alert action menu in webhook box\n5th As alert triger send message to bot . bot exicute order on broker or\nexchange\nif you dont have a subscription plan\nit has difficult to do it\nthere is other way to do it it will different\n1st open a website https://pipedream.com/@/new/build this link create a work flow\nin triger use email as a triger copy email\n1st create a alert in alert there is a alert option email to sms click on that\npaste here\n2nd send http post request and paste bot url here\n3rd message send to bot by pipedream and bot will exicute order\n", "you can not add url in scrip of tv\nif you want to do algo trading there is a way to do it ~>\nbro if you have subscription of tv\n1st create broker api and secret key copy it\n2nd paste api and secreat key in 3party application bot then bot give you a url\ncopy it .\n3st create a alert based on condition and write messages what you want to send\nto bot so he understand it when to buy/sell order\napplication so that bot can understand\n4nd paste url in alert action menu in webhook box\n5th As alert triger send message to bot . bot exicute order on broker or\nexchange\nif you dont have a subscription plan\nit has difficult to do it\nthere is other way to do it it will different\n1st open a website https://pipedream.com/@/new/build this link create a work flow\nin triger use email as a triger copy email\n1st create a alert in alert there is a alert option email to sms click on that\npaste here and verify emai otp send to pipedream workflow `~> body in text\n2nd click on + button of workflow send http post request and paste bot url there\n3rd message send to bot by pipedream and bot will exicute order\n" ]
[ 0, 0, 0 ]
[]
[]
[ "algorithmic_trading", "pine_script", "pinescript_v5" ]
stackoverflow_0074524297_algorithmic_trading_pine_script_pinescript_v5.txt
Q: Error: Undefined name and Method not defined I am new to flutter. I am building todo list app by following one of the article. I have managed to find couple of errors already such as asyn and .then method, FieldButton to Text button. I am struggling to fix couple of errors This is the first error message: lib/main.dart:88:24: Error: Undefined name '_todoList'. for (String title in _todoList) { This is the second error message: lib/main.dart:89:22: Error: Method not found: '_buildTodoItem'. _todoWidgets.add(_buildTodoItem(title)); ^^^^^^^^^^^^^^ Here is my full code: import 'package:flutter/material.dart'; void main() { runApp(App()); } class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp(title: 'To-Do-List', home: TodoList()); } } class TodoList extends StatefulWidget { @override _TodoListState createState() => _TodoListState(); } class _TodoListState extends State<TodoList> { final List<String> _todoList = <String>[]; final TextEditingController _textFieldController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('To-Do List'), ), body: ListView(children: _getItems()), floatingActionButton: FloatingActionButton( onPressed: () => _displayDialog(context), tooltip: 'Add Item', child: Icon(Icons.add), ), ); } void _addTodoItem(String title) { //Wrapping it inside a set state will notify // the app that the state has changed setState(() { _todoList.add(title); }); _textFieldController.clear(); } //Generate list of item widgets Widget _buildTodoItem(String title) { return ListTile( title: Text(title), ); } //Generate a single item widget Future<AlertDialog> _displayDialog(BuildContext context) async { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Add a task to your List'), content: TextField( controller: _textFieldController, decoration: const InputDecoration(hintText: 'Enter task here'), ), actions: <Widget>[ TextButton( child: const Text('ADD'), onPressed: () { Navigator.of(context).pop(); _addTodoItem(_textFieldController.text); }, ), TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.of(context).pop(); }, ) ], ); }).then((showDialog) => showDialog ?? false); } } List<Widget> _getItems() { final List<Widget> _todoWidgets = <Widget>[]; for (String title in _todoList) { _todoWidgets.add(_buildTodoItem(title)); } return _todoWidgets; } I have already fixed .then method along with Textbutton. I want to understand how exactly I can find be able to resolve this issue. It's quite confusing to beging with. A: Your definition of the function _getItems() falls outside the class definition, i.e. after the closing bracket }. But _todoList is a property of the class _TodoListState. So your function tries to access something that it doesn't have access to. You should include the function _getItems() in your class like this. class _TodoListState extends State<TodoList> { // ... lots of code here... List<Widget> _getItems() { final List<Widget> _todoWidgets = <Widget>[]; for (String title in _todoList) { _todoWidgets.add(_buildTodoItem(title)); } return _todoWidgets; } } Do you notice the difference? The closing bracket of the class is now placed behind the closing bracket of the function. A: in the Dart language, the private members of a class are those with an underscore upfront their name definition, in your case, the _buildTodoItem() method is private and can't be used anywhere outside its class. in addition, if you want a member from outside, you will need to make an instance of that class and access it. This function: List<Widget> _getItems() { final List<Widget> _todoWidgets = <Widget>[]; for (String title in _todoList) { _todoWidgets.add(_buildTodoItem(title)); } return _todoWidgets; } is outside the State class where the _buildTodoItem method belongs, so the error is thrown. you should get back that function inside the State class to fix the error like this: class _TodoListState extends State<TodoList> { final List<String> _todoList = <String>[]; final TextEditingController _textFieldController = TextEditingController(); List<Widget> _getItems() { final List<Widget> _todoWidgets = <Widget>[]; for (String title in _todoList) { _todoWidgets.add(_buildTodoItem(title)); } return _todoWidgets; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('To-Do List'), ), body: ListView(children: _getItems()), floatingActionButton: FloatingActionButton( onPressed: () => _displayDialog(context), tooltip: 'Add Item', child: Icon(Icons.add), ), ); } void _addTodoItem(String title) { //Wrapping it inside a set state will notify // the app that the state has changed setState(() { _todoList.add(title); }); _textFieldController.clear(); } //Generate list of item widgets Widget _buildTodoItem(String title) { return ListTile( title: Text(title), ); } //Generate a single item widget Future<AlertDialog> _displayDialog(BuildContext context) async { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Add a task to your List'), content: TextField( controller: _textFieldController, decoration: const InputDecoration(hintText: 'Enter task here'), ), actions: <Widget>[ TextButton( child: const Text('ADD'), onPressed: () { Navigator.of(context).pop(); _addTodoItem(_textFieldController.text); }, ), TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.of(context).pop(); }, ) ], ); }).then((showDialog) => showDialog ?? false); } }
Error: Undefined name and Method not defined
I am new to flutter. I am building todo list app by following one of the article. I have managed to find couple of errors already such as asyn and .then method, FieldButton to Text button. I am struggling to fix couple of errors This is the first error message: lib/main.dart:88:24: Error: Undefined name '_todoList'. for (String title in _todoList) { This is the second error message: lib/main.dart:89:22: Error: Method not found: '_buildTodoItem'. _todoWidgets.add(_buildTodoItem(title)); ^^^^^^^^^^^^^^ Here is my full code: import 'package:flutter/material.dart'; void main() { runApp(App()); } class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp(title: 'To-Do-List', home: TodoList()); } } class TodoList extends StatefulWidget { @override _TodoListState createState() => _TodoListState(); } class _TodoListState extends State<TodoList> { final List<String> _todoList = <String>[]; final TextEditingController _textFieldController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('To-Do List'), ), body: ListView(children: _getItems()), floatingActionButton: FloatingActionButton( onPressed: () => _displayDialog(context), tooltip: 'Add Item', child: Icon(Icons.add), ), ); } void _addTodoItem(String title) { //Wrapping it inside a set state will notify // the app that the state has changed setState(() { _todoList.add(title); }); _textFieldController.clear(); } //Generate list of item widgets Widget _buildTodoItem(String title) { return ListTile( title: Text(title), ); } //Generate a single item widget Future<AlertDialog> _displayDialog(BuildContext context) async { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Add a task to your List'), content: TextField( controller: _textFieldController, decoration: const InputDecoration(hintText: 'Enter task here'), ), actions: <Widget>[ TextButton( child: const Text('ADD'), onPressed: () { Navigator.of(context).pop(); _addTodoItem(_textFieldController.text); }, ), TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.of(context).pop(); }, ) ], ); }).then((showDialog) => showDialog ?? false); } } List<Widget> _getItems() { final List<Widget> _todoWidgets = <Widget>[]; for (String title in _todoList) { _todoWidgets.add(_buildTodoItem(title)); } return _todoWidgets; } I have already fixed .then method along with Textbutton. I want to understand how exactly I can find be able to resolve this issue. It's quite confusing to beging with.
[ "Your definition of the function _getItems() falls outside the class definition, i.e. after the closing bracket }. But _todoList is a property of the class _TodoListState.\nSo your function tries to access something that it doesn't have access to.\nYou should include the function _getItems() in your class like this.\nclass _TodoListState extends State<TodoList> {\n \n // ... lots of code here...\n\n List<Widget> _getItems() {\n final List<Widget> _todoWidgets = <Widget>[];\n for (String title in _todoList) {\n _todoWidgets.add(_buildTodoItem(title));\n }\n return _todoWidgets;\n } \n\n}\n\nDo you notice the difference?\nThe closing bracket of the class is now placed behind the closing bracket of the function.\n", "in the Dart language, the private members of a class are those with an underscore upfront their name definition, in your case, the _buildTodoItem() method is private and can't be used anywhere outside its class. in addition, if you want a member from outside, you will need to make an instance of that class and access it.\nThis function:\n List<Widget> _getItems() {\n final List<Widget> _todoWidgets = <Widget>[];\n for (String title in _todoList) {\n _todoWidgets.add(_buildTodoItem(title));\n }\n return _todoWidgets;\n}\n\nis outside the State class where the _buildTodoItem method belongs, so the error is thrown.\nyou should get back that function inside the State class to fix the error like this:\n class _TodoListState extends State<TodoList> {\n final List<String> _todoList = <String>[];\n final TextEditingController _textFieldController = TextEditingController();\n\n\n \n List<Widget> _getItems() {\n final List<Widget> _todoWidgets = <Widget>[];\n for (String title in _todoList) {\n _todoWidgets.add(_buildTodoItem(title));\n }\n\n return _todoWidgets;\n}\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: const Text('To-Do List'),\n ),\n body: ListView(children: _getItems()),\n floatingActionButton: FloatingActionButton(\n onPressed: () => _displayDialog(context),\n tooltip: 'Add Item',\n child: Icon(Icons.add),\n ),\n );\n }\n\n void _addTodoItem(String title) {\n //Wrapping it inside a set state will notify\n // the app that the state has changed\n\n setState(() {\n _todoList.add(title);\n });\n _textFieldController.clear();\n }\n\n //Generate list of item widgets\n Widget _buildTodoItem(String title) {\n return ListTile(\n title: Text(title),\n );\n }\n\n //Generate a single item widget\n Future<AlertDialog> _displayDialog(BuildContext context) async {\n return showDialog(\n context: context,\n builder: (BuildContext context) {\n return AlertDialog(\n title: const Text('Add a task to your List'),\n content: TextField(\n controller: _textFieldController,\n decoration: const InputDecoration(hintText: 'Enter task here'),\n ),\n actions: <Widget>[\n TextButton(\n child: const Text('ADD'),\n onPressed: () {\n Navigator.of(context).pop();\n _addTodoItem(_textFieldController.text);\n },\n ),\n TextButton(\n child: const Text('CANCEL'),\n onPressed: () {\n Navigator.of(context).pop();\n },\n )\n ],\n );\n }).then((showDialog) => showDialog ?? false);\n }\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "dart", "flutter" ]
stackoverflow_0074671788_dart_flutter.txt
Q: RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 30 but got size 31 for tensor number 1 in the list Here's the part of my code. from transformers import BertTokenizer,BertForSequenceClassification,AdamW tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',do_lower_case = True,truncation=True) input_ids = [] attention_mask = [] for i in text: encoded_data = tokenizer.encode_plus( i, add_special_tokens=True, truncation=True, max_length=64, padding=True, #pad_to_max_length = True, return_attention_mask= True, return_tensors='pt') input_ids.append(encoded_data['input_ids']) attention_mask.append(encoded_data['attention_mask']) input_ids = torch.cat(input_ids,dim=0) attention_mask = torch.cat(attention_mask,dim=0) labels = torch.tensor(labels) dataset = TensorDataset(input_ids,attention_mask,labels) train_size = int(0.8*len(dataset)) val_size = len(dataset) - train_size train_dataset,val_dataset = random_split(dataset,[train_size,val_size]) print('Training Size - ',train_size) print('Validation Size - ',val_size) train_dl = DataLoader(train_dataset,sampler = RandomSampler(train_dataset), batch_size = 2) val_dl = DataLoader(val_dataset,sampler = SequentialSampler(val_dataset), batch_size = 2) model = BertForSequenceClassification.from_pretrained( 'bert-base-uncased', num_labels = 2, output_attentions = False, output_hidden_states = False) I know I get this line becase of the un-matched size in torch.cat. I wonder how can i fix it? --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Input In [9], in <cell line: 18>() 16 input_ids.append(encoded_data['input_ids']) 17 attention_mask.append(encoded_data['attention_mask']) ---> 18 input_ids = torch.cat(input_ids,dim=0) 19 attention_mask = torch.cat(attention_mask,dim=0) 20 labels = torch.tensor(labels) RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 30 but got size 31 for tensor number 1 in the list. I get an error here. It is due to the unmatched dimension . But I have no idea where i can fix it. A: The error message says that you are trying to concatenate tensors of different sizes along the 0th dimension, which is not allowed. This is likely happening because you are not specifying the pad_to_max_length argument when calling tokenizer.encode_plus(), which means that the length of the encoded tensors will not be the same for all input texts. To fix this error, you can either specify pad_to_max_length = True when calling tokenizer.encode_plus(), which will ensure that all tensors are padded to the same length, or you can use the torch.nn.utils.rnn.pad_sequence() function to pad the tensors before concatenating them. Here is an example of how you could use pad_sequence() to fix the error: from torch.nn.utils.rnn import pad_sequence # Encode the input texts and create the input tensors input_ids = [] attention_mask = [] for i in text: encoded_data = tokenizer.encode_plus( i, add_special_tokens=True, truncation=True, max_length=64, padding=True, return_attention_mask= True, return_tensors='pt') input_ids.append(encoded_data['input_ids']) attention_mask.append(encoded_data['attention_mask']) # Pad the input tensors to the same length input_ids = pad_sequence(input_ids, batch_first=True) attention_mask = pad_sequence(attention_mask, batch_first=True) # Create the label tensor labels = torch.tensor(labels) # Create the dataset and dataloaders dataset = TensorDataset(input_ids, attention_mask, labels) train_size = int(0.8 * len(dataset)) val_size = len(dataset) - train_size train_dataset, val_dataset = random_split(dataset, [train_size, val_size]) train_dl = DataLoader(train_dataset, sampler=RandomSampler(train_dataset), batch_size=2) val_dl = DataLoader(val_dataset, sampler=SequentialSampler(val_dataset), batch_size=2) # Create and train the model model = BertForSequenceClassification.from_pretrained( 'bert-base-uncased', num_labels=2, output_attentions=False, output_hidden_states=False)
RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 30 but got size 31 for tensor number 1 in the list
Here's the part of my code. from transformers import BertTokenizer,BertForSequenceClassification,AdamW tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',do_lower_case = True,truncation=True) input_ids = [] attention_mask = [] for i in text: encoded_data = tokenizer.encode_plus( i, add_special_tokens=True, truncation=True, max_length=64, padding=True, #pad_to_max_length = True, return_attention_mask= True, return_tensors='pt') input_ids.append(encoded_data['input_ids']) attention_mask.append(encoded_data['attention_mask']) input_ids = torch.cat(input_ids,dim=0) attention_mask = torch.cat(attention_mask,dim=0) labels = torch.tensor(labels) dataset = TensorDataset(input_ids,attention_mask,labels) train_size = int(0.8*len(dataset)) val_size = len(dataset) - train_size train_dataset,val_dataset = random_split(dataset,[train_size,val_size]) print('Training Size - ',train_size) print('Validation Size - ',val_size) train_dl = DataLoader(train_dataset,sampler = RandomSampler(train_dataset), batch_size = 2) val_dl = DataLoader(val_dataset,sampler = SequentialSampler(val_dataset), batch_size = 2) model = BertForSequenceClassification.from_pretrained( 'bert-base-uncased', num_labels = 2, output_attentions = False, output_hidden_states = False) I know I get this line becase of the un-matched size in torch.cat. I wonder how can i fix it? --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Input In [9], in <cell line: 18>() 16 input_ids.append(encoded_data['input_ids']) 17 attention_mask.append(encoded_data['attention_mask']) ---> 18 input_ids = torch.cat(input_ids,dim=0) 19 attention_mask = torch.cat(attention_mask,dim=0) 20 labels = torch.tensor(labels) RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 30 but got size 31 for tensor number 1 in the list. I get an error here. It is due to the unmatched dimension . But I have no idea where i can fix it.
[ "The error message says that you are trying to concatenate tensors of different sizes along the 0th dimension, which is not allowed. This is likely happening because you are not specifying the pad_to_max_length argument when calling tokenizer.encode_plus(), which means that the length of the encoded tensors will not be the same for all input texts.\nTo fix this error, you can either specify pad_to_max_length = True when calling tokenizer.encode_plus(), which will ensure that all tensors are padded to the same length, or you can use the torch.nn.utils.rnn.pad_sequence() function to pad the tensors before concatenating them.\nHere is an example of how you could use pad_sequence() to fix the error:\nfrom torch.nn.utils.rnn import pad_sequence\n\n# Encode the input texts and create the input tensors\ninput_ids = []\nattention_mask = []\n\nfor i in text:\n encoded_data = tokenizer.encode_plus(\n i,\n add_special_tokens=True,\n truncation=True,\n max_length=64,\n padding=True,\n return_attention_mask= True,\n return_tensors='pt')\n input_ids.append(encoded_data['input_ids'])\n attention_mask.append(encoded_data['attention_mask'])\n\n# Pad the input tensors to the same length\ninput_ids = pad_sequence(input_ids, batch_first=True)\nattention_mask = pad_sequence(attention_mask, batch_first=True)\n\n# Create the label tensor\nlabels = torch.tensor(labels)\n\n# Create the dataset and dataloaders\ndataset = TensorDataset(input_ids, attention_mask, labels)\ntrain_size = int(0.8 * len(dataset))\nval_size = len(dataset) - train_size\ntrain_dataset, val_dataset = random_split(dataset, [train_size, val_size])\n\ntrain_dl = DataLoader(train_dataset, sampler=RandomSampler(train_dataset),\n batch_size=2)\nval_dl = DataLoader(val_dataset, sampler=SequentialSampler(val_dataset),\n batch_size=2)\n\n# Create and train the model\nmodel = BertForSequenceClassification.from_pretrained(\n 'bert-base-uncased',\n num_labels=2,\n output_attentions=False,\n output_hidden_states=False)\n\n" ]
[ 1 ]
[]
[]
[ "bert_language_model", "machine_learning", "python", "sentiment_analysis", "torch" ]
stackoverflow_0074668301_bert_language_model_machine_learning_python_sentiment_analysis_torch.txt
Q: Get a url to a git commit from the command line I like to share links to git commits with other people. It's useful to be able to get these without too much clicking in emacs, there is a package in emacs that I use (https://github.com/sshaw/git-link) but I want to do this from the command line. Is there an easy way to get a link to a commit from from the command line? (I use github) Related git rev-parse HEAD gives you the commit from the command line A: The URL you'd need for, say, a Bitbucket-hosted Git repository is different from the URL you'd need for a GitHub-hosted Git repository. Git itself doesn't have such links: each hosting system in use has to invent its own. Since you want a GitHub-specific link, you can generate one, knowing that it will begin with https://github.com/ or https://raw.githubusercontent.com/. After that comes the name of the repository, e.g., git/git/. If you then want a particular file, the next part is blob/, then either a branch name or a commit hash ID, then the path to the file. The same scheme works to obtain raw file content when suing raw.githubusercontent.com. A: This linux command should work for GitHub if your remote is called 'origin' and you use https to access your origin echo "$(git config --get remote.origin.url | sed -e 's/\.git$//g')/commit/$(git rev-parse HEAD)"
Get a url to a git commit from the command line
I like to share links to git commits with other people. It's useful to be able to get these without too much clicking in emacs, there is a package in emacs that I use (https://github.com/sshaw/git-link) but I want to do this from the command line. Is there an easy way to get a link to a commit from from the command line? (I use github) Related git rev-parse HEAD gives you the commit from the command line
[ "The URL you'd need for, say, a Bitbucket-hosted Git repository is different from the URL you'd need for a GitHub-hosted Git repository. Git itself doesn't have such links: each hosting system in use has to invent its own.\nSince you want a GitHub-specific link, you can generate one, knowing that it will begin with https://github.com/ or https://raw.githubusercontent.com/. After that comes the name of the repository, e.g., git/git/. If you then want a particular file, the next part is blob/, then either a branch name or a commit hash ID, then the path to the file. The same scheme works to obtain raw file content when suing raw.githubusercontent.com.\n", "This linux command should work for GitHub if your remote is called 'origin' and you use https to access your origin\necho \"$(git config --get remote.origin.url | sed -e 's/\\.git$//g')/commit/$(git rev-parse HEAD)\"\n\n" ]
[ 2, 0 ]
[]
[]
[ "git", "github", "hyperlink" ]
stackoverflow_0071440540_git_github_hyperlink.txt
Q: How do I change the variables inside of a python table? This is my table. playerdata = { 'Saves' : [{ 'name' : charactername, 'class' : playerclass, 'level' : level, 'race' : playerrace, 'Inventory' : [{ 'Slot 1' : 'Test', 'Slot 2' : 'Test', 'Slot 3' : 'Test' }], 'Attributes' : [{ 'Dexterity' : attDexterity, 'Strength' : attStrength, 'Wisdom' : attWisdom, 'Intelligence' : attIntelligence, 'Charisma' : attCharisma, 'Constitution' : attConstitution }] }] } If the variable charactername updates the value inside of the table stays the same. How would I make the value change when the variable changes? The table gets dumped into a json file. That’s how I know it doesn’t change. A: To update the value in the table when the variable charactername changes, you can use the following code: # Update the value of charactername in the table playerdata['Saves'][0]['name'] = charactername This code accesses the Saves key in the playerdata dictionary, then accesses the first element in the Saves list (which is a dictionary), and finally updates the name key with the current value of the charactername variable. Note that you will also need to update the value in the JSON file by writing the updated playerdata dictionary to the file, using the json.dump() method. Here is an example of how you can do that: import json # Update the value of charactername in the table playerdata['Saves'][0]['name'] = charactername # Open the JSON file for writing with open('playerdata.json', 'w') as f: # Dump the updated playerdata dictionary to the file json.dump(playerdata, f)
How do I change the variables inside of a python table?
This is my table. playerdata = { 'Saves' : [{ 'name' : charactername, 'class' : playerclass, 'level' : level, 'race' : playerrace, 'Inventory' : [{ 'Slot 1' : 'Test', 'Slot 2' : 'Test', 'Slot 3' : 'Test' }], 'Attributes' : [{ 'Dexterity' : attDexterity, 'Strength' : attStrength, 'Wisdom' : attWisdom, 'Intelligence' : attIntelligence, 'Charisma' : attCharisma, 'Constitution' : attConstitution }] }] } If the variable charactername updates the value inside of the table stays the same. How would I make the value change when the variable changes? The table gets dumped into a json file. That’s how I know it doesn’t change.
[ "To update the value in the table when the variable charactername changes, you can use the following code:\n# Update the value of charactername in the table\nplayerdata['Saves'][0]['name'] = charactername\n\nThis code accesses the Saves key in the playerdata dictionary, then accesses the first element in the Saves list (which is a dictionary), and finally updates the name key with the current value of the charactername variable.\nNote that you will also need to update the value in the JSON file by writing the updated playerdata dictionary to the file, using the json.dump() method.\nHere is an example of how you can do that:\nimport json\n\n# Update the value of charactername in the table\nplayerdata['Saves'][0]['name'] = charactername\n\n# Open the JSON file for writing\nwith open('playerdata.json', 'w') as f:\n # Dump the updated playerdata dictionary to the file\n json.dump(playerdata, f)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671769_python.txt
Q: Variable '${username}' not found while using Robot Framework with DataDriver library I'm new in Robot Framework, and now get stuck while using DataDriver library in my robot script. My problem: There is a message : "Variable '${username}' not found." while I run the robot script and the test was FAIL. This is my robot script: *** Settings *** Library DataDriver file=resources/user_password.csv encoding=utf_8 dialect=unix Test Template Test Credential *** Test Cases *** Doing Test Credentials for ${username} and ${password} *** Keywords *** Test Credential [Arguments] ${username} ${password} Log ${username} Log ${password} and this is my CSV file: *** Test Cases ***, ${username}, ${password}, [Tags], [Documentation] Valid user, [email protected], pass123, Positive, This is valid user credential Invalid user, [email protected], pass123, Negative, This user is invalid Invalid password, [email protected], pass, Negative, This password is invalid Blank user, ${EMPTY}, pass123, Negative, Blank user Blank password, [email protected], ${EMPTY}, Negative, Blank password Blank user and password, ${EMPTY}, ${EMPTY}, Negative, Blank both user and password Any help would be greatly appreciated. Thanks. Welly A: I think the problem is in: *** Test Cases *** Doing Test Credentials for ${username} and ${password} You're not passing any variables to the keyword as it's shown in the documentation for the DataDriver library: https://github.com/Snooz82/robotframework-datadriver#example-test-suite A solution would be to pass some values to the keyword: *** Test Cases *** Doing Test Credentials for ${username} and ${password} secret-user secret-pwd EDIT: Another is the format of your csv file. You include spaces after each comma, if I delete them: *** Test Cases ***,${username},${password},[Tags],[Documentation] Valid user,[email protected],pass123,Positive,This is valid user credential I can run it without any problems: and the report: A: I also observed that if we don't give "dialect=unix" in "Library DataDriver file=resources/logindata2.csv endocing=uft_8", then we get error Variable '${username}' not found. or Variable '${password}' not found.
Variable '${username}' not found while using Robot Framework with DataDriver library
I'm new in Robot Framework, and now get stuck while using DataDriver library in my robot script. My problem: There is a message : "Variable '${username}' not found." while I run the robot script and the test was FAIL. This is my robot script: *** Settings *** Library DataDriver file=resources/user_password.csv encoding=utf_8 dialect=unix Test Template Test Credential *** Test Cases *** Doing Test Credentials for ${username} and ${password} *** Keywords *** Test Credential [Arguments] ${username} ${password} Log ${username} Log ${password} and this is my CSV file: *** Test Cases ***, ${username}, ${password}, [Tags], [Documentation] Valid user, [email protected], pass123, Positive, This is valid user credential Invalid user, [email protected], pass123, Negative, This user is invalid Invalid password, [email protected], pass, Negative, This password is invalid Blank user, ${EMPTY}, pass123, Negative, Blank user Blank password, [email protected], ${EMPTY}, Negative, Blank password Blank user and password, ${EMPTY}, ${EMPTY}, Negative, Blank both user and password Any help would be greatly appreciated. Thanks. Welly
[ "I think the problem is in:\n*** Test Cases ***\nDoing Test Credentials for ${username} and ${password}\n\nYou're not passing any variables to the keyword as it's shown in the documentation for the DataDriver library: https://github.com/Snooz82/robotframework-datadriver#example-test-suite\nA solution would be to pass some values to the keyword:\n*** Test Cases ***\nDoing Test Credentials for ${username} and ${password} secret-user secret-pwd\n\nEDIT:\nAnother is the format of your csv file. You include spaces after each comma, if I delete them:\n*** Test Cases ***,${username},${password},[Tags],[Documentation]\nValid user,[email protected],pass123,Positive,This is valid user credential\n\nI can run it without any problems:\n\nand the report:\n\n", "I also observed that if we don't give \"dialect=unix\" in \"Library DataDriver file=resources/logindata2.csv endocing=uft_8\", then we get error\nVariable '${username}' not found.\nor\nVariable '${password}' not found.\n" ]
[ 0, 0 ]
[]
[]
[ "robotframework" ]
stackoverflow_0064749767_robotframework.txt
Q: Timeseries split datetime data type to seperate date and time columns I am importing a CSV file that contains a nonformatted dataset, the date and time are separated but the data type is an object, and the times' time zone is incorrect. The timezone of this original dataset is EET which is currently 7-hour difference from eastern standard time, (sometimes it is 6 hours during daylight savings time) I am trying to convert the objects to date time format and convert the timezone to Eastern standard time, having the date and time in separate columns. a snippet of my code is as follows: Transform the date column to a datetime format df['date'] = pd.to_datetime(df['date']) the above code successfully converts the date column to datetime data type, great. My trouble is when I work with the time column. I am unable to separate the date and time using .split(), the timezone is not accurate so I have compensated by using a different time zone to account for the -7hrs that I am looking for (us/mountain seems to produce the -7hr that I need) Transform the time column to a datetime data type df["time"] = pd.to_datetime( df["time"], infer_datetime_format = True ) Convert the time column to the US/Eastern timezone df["time"] = df["time"].dt.tz_localize("US/Mountain") As it turns out, the output is: 2022-12-03 23:55:00-07:00 I am looking for an output of 16:55 or even 16:55:00 is fine as well. My question is how can I separate the time from date while in datetime format and subtract the -7:00 so the output is 16:55 (or 16:55:00) I have tried using: df['time'].to_datetime().strftime('%h-%m') and receive the following error: AttributeError: 'Series' object has no attribute 'to_datetime' df['time'].apply(lambda x:time.strptime(x, "%H:%M")) gives the following output 64999 (1900, 1, 1, 23, 55, 0, 0, 1, -1) df['Time'] = pd.to_datetime(df['time']).dt.time gives me the original time '23:55:00' To be clear, I am looking for an output of just the converted time, for example 16:55. I do not want 23:55:00-07:00 I am looking for an output of date time split into separate columns in the correct timezone example: date | time ------ ------ 2022-12-02 | 16:55 A: sample: data = { "date": ["2022-12-02"], "time": ["23:55:00"] } df = pd.DataFrame(data) code: df["datetime"] = ( pd.to_datetime(df["date"].str.cat(df["time"], sep=" ")) .dt.tz_localize("UTC") .dt.tz_convert("US/Mountain") .dt.tz_localize(None) ) df["date"], df["time"] = zip(*[(x.date(), x.time()) for x in df.pop("datetime")]) print(df) output: date time 0 2022-12-02 16:55:00
Timeseries split datetime data type to seperate date and time columns
I am importing a CSV file that contains a nonformatted dataset, the date and time are separated but the data type is an object, and the times' time zone is incorrect. The timezone of this original dataset is EET which is currently 7-hour difference from eastern standard time, (sometimes it is 6 hours during daylight savings time) I am trying to convert the objects to date time format and convert the timezone to Eastern standard time, having the date and time in separate columns. a snippet of my code is as follows: Transform the date column to a datetime format df['date'] = pd.to_datetime(df['date']) the above code successfully converts the date column to datetime data type, great. My trouble is when I work with the time column. I am unable to separate the date and time using .split(), the timezone is not accurate so I have compensated by using a different time zone to account for the -7hrs that I am looking for (us/mountain seems to produce the -7hr that I need) Transform the time column to a datetime data type df["time"] = pd.to_datetime( df["time"], infer_datetime_format = True ) Convert the time column to the US/Eastern timezone df["time"] = df["time"].dt.tz_localize("US/Mountain") As it turns out, the output is: 2022-12-03 23:55:00-07:00 I am looking for an output of 16:55 or even 16:55:00 is fine as well. My question is how can I separate the time from date while in datetime format and subtract the -7:00 so the output is 16:55 (or 16:55:00) I have tried using: df['time'].to_datetime().strftime('%h-%m') and receive the following error: AttributeError: 'Series' object has no attribute 'to_datetime' df['time'].apply(lambda x:time.strptime(x, "%H:%M")) gives the following output 64999 (1900, 1, 1, 23, 55, 0, 0, 1, -1) df['Time'] = pd.to_datetime(df['time']).dt.time gives me the original time '23:55:00' To be clear, I am looking for an output of just the converted time, for example 16:55. I do not want 23:55:00-07:00 I am looking for an output of date time split into separate columns in the correct timezone example: date | time ------ ------ 2022-12-02 | 16:55
[ "sample:\ndata = {\n \"date\": [\"2022-12-02\"],\n \"time\": [\"23:55:00\"]\n}\ndf = pd.DataFrame(data)\n\ncode:\ndf[\"datetime\"] = (\n pd.to_datetime(df[\"date\"].str.cat(df[\"time\"], sep=\" \"))\n .dt.tz_localize(\"UTC\")\n .dt.tz_convert(\"US/Mountain\")\n .dt.tz_localize(None)\n)\ndf[\"date\"], df[\"time\"] = zip(*[(x.date(), x.time()) for x in df.pop(\"datetime\")])\nprint(df)\n\noutput:\n date time\n0 2022-12-02 16:55:00\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "pandas", "python", "time_series", "types" ]
stackoverflow_0074671714_datetime_pandas_python_time_series_types.txt
Q: In MySQL database, how can I reach the rows A header Another header 1 adcxy 2 axsey 3 drfhgh 4 ayxddfy 5 weaxjug ... ... In MySQL database, how can I reach bolded row with "axy" search? A: Use like with the predicate built from the letters you're searching for: select * from mytable where another_header like '%a%x%y%' All your examples that match start with a and end with y, but it's not clear if that's a requirement. If it is, use like 'a%x%y' instead.
In MySQL database, how can I reach the rows
A header Another header 1 adcxy 2 axsey 3 drfhgh 4 ayxddfy 5 weaxjug ... ... In MySQL database, how can I reach bolded row with "axy" search?
[ "Use like with the predicate built from the letters you're searching for:\nselect *\nfrom mytable\nwhere another_header like '%a%x%y%'\n\nAll your examples that match start with a and end with y, but it's not clear if that's a requirement. If it is, use like 'a%x%y' instead.\n" ]
[ 1 ]
[]
[]
[ "mysql", "processmaker" ]
stackoverflow_0074671830_mysql_processmaker.txt
Q: SwiftUI PreferenceKey not Updating I'm struggling trying to implement a PreferenceKey. I've read countless articles, so obviously I'm missing something. onPreferenceChange reports once at simulator startup but not during scrolling. Scrolling updates the text in the TextEditor overlay, but the offsetCGSize property is apparently never updated. Here's a simplified version of the code: struct SOView: View { @State private var firstText: String = "first" @State private var secondText: String = "second" @State private var thirdText: String = "third" @State private var offsetCGSize: CGSize = .zero var body: some View { ScrollView { VStack { ForEach(0..<20) {index in Text("Line number \(index)") } Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) TextField("First", text: $firstText) GeometryReader { teGeo in TextEditor(text: $secondText) .frame(height: 100) .overlay( RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2) ) .overlay( Text("\(teGeo.frame(in: .global).minY)") ) .preference(key: OffsetPreferenceKey.self, value: CGSize(width: 0, height: teGeo.frame(in: .global).minY)) }//geo .frame(height: 100) TextField("Third", text: $thirdText) Text("TextEditor top is \(offsetCGSize.height)") }//v .padding() }//scroll .onPreferenceChange(OffsetPreferenceKey.self) { value in offsetCGSize = value print("offsetCGSize is \(offsetCGSize)") } }//body }//so view private struct OffsetPreferenceKey: PreferenceKey { static var defaultValue: CGSize = CGSize.zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } }//off pref Any guidance would be appreciated. Xcode 14.0.1, iOS 16 A: For others - I don't understand why, but by moving the two TextFields, the Image and the reporting Text outside of the ScrollView I get the results I expect. (In this file, I changed the key name to OffsetPreferenceKey2) struct SOView2: View { @State private var firstText: String = "first" @State private var secondText: String = "second" @State private var thirdText: String = "third" @State private var offsetCGSize: CGSize = .zero var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) TextField("First", text: $firstText) .padding(.horizontal) ScrollView { VStack { ForEach(0..<20) {index in Text("Line number \(index)") } GeometryReader { teGeo in TextEditor(text: $secondText) .frame(height: 100) .overlay( RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2) ) .overlay( Text("\(teGeo.frame(in: .global).minY)") ) .preference(key: OffsetPreferenceKey2.self, value: CGSize(width: 0, height: teGeo.frame(in: .global).minY)) }//geo .frame(height: 100) }//v .padding() }//scroll .onPreferenceChange(OffsetPreferenceKey2.self) { value in offsetCGSize = value print("offsetCGSize is \(offsetCGSize)") }// pref change TextField("Third", text: $thirdText) .padding(.horizontal) Text("TextEditor top is \(offsetCGSize.height)") }//outer v }//body }//so view private struct OffsetPreferenceKey2: PreferenceKey { static var defaultValue: CGSize = CGSize.zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } }//off pref
SwiftUI PreferenceKey not Updating
I'm struggling trying to implement a PreferenceKey. I've read countless articles, so obviously I'm missing something. onPreferenceChange reports once at simulator startup but not during scrolling. Scrolling updates the text in the TextEditor overlay, but the offsetCGSize property is apparently never updated. Here's a simplified version of the code: struct SOView: View { @State private var firstText: String = "first" @State private var secondText: String = "second" @State private var thirdText: String = "third" @State private var offsetCGSize: CGSize = .zero var body: some View { ScrollView { VStack { ForEach(0..<20) {index in Text("Line number \(index)") } Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) TextField("First", text: $firstText) GeometryReader { teGeo in TextEditor(text: $secondText) .frame(height: 100) .overlay( RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2) ) .overlay( Text("\(teGeo.frame(in: .global).minY)") ) .preference(key: OffsetPreferenceKey.self, value: CGSize(width: 0, height: teGeo.frame(in: .global).minY)) }//geo .frame(height: 100) TextField("Third", text: $thirdText) Text("TextEditor top is \(offsetCGSize.height)") }//v .padding() }//scroll .onPreferenceChange(OffsetPreferenceKey.self) { value in offsetCGSize = value print("offsetCGSize is \(offsetCGSize)") } }//body }//so view private struct OffsetPreferenceKey: PreferenceKey { static var defaultValue: CGSize = CGSize.zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } }//off pref Any guidance would be appreciated. Xcode 14.0.1, iOS 16
[ "For others - I don't understand why, but by moving the two TextFields, the Image and the reporting Text outside of the ScrollView I get the results I expect. (In this file, I changed the key name to OffsetPreferenceKey2)\n\nstruct SOView2: View {\n @State private var firstText: String = \"first\"\n @State private var secondText: String = \"second\"\n @State private var thirdText: String = \"third\"\n\n @State private var offsetCGSize: CGSize = .zero\n\n var body: some View {\n VStack {\n \n Image(systemName: \"globe\")\n .imageScale(.large)\n .foregroundColor(.accentColor)\n TextField(\"First\", text: $firstText)\n .padding(.horizontal)\n \n ScrollView {\n VStack {\n ForEach(0..<20) {index in\n Text(\"Line number \\(index)\")\n }\n \n GeometryReader { teGeo in\n TextEditor(text: $secondText)\n .frame(height: 100)\n .overlay(\n RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2)\n )\n .overlay(\n Text(\"\\(teGeo.frame(in: .global).minY)\")\n )\n .preference(key: OffsetPreferenceKey2.self, value: CGSize(width: 0, height: teGeo.frame(in: .global).minY))\n }//geo\n .frame(height: 100)\n \n }//v\n .padding()\n }//scroll\n .onPreferenceChange(OffsetPreferenceKey2.self) { value in\n offsetCGSize = value\n print(\"offsetCGSize is \\(offsetCGSize)\")\n }// pref change\n \n TextField(\"Third\", text: $thirdText)\n .padding(.horizontal)\n Text(\"TextEditor top is \\(offsetCGSize.height)\")\n \n }//outer v\n \n }//body\n}//so view\n\nprivate struct OffsetPreferenceKey2: PreferenceKey {\n static var defaultValue: CGSize = CGSize.zero\n static func reduce(value: inout CGSize, nextValue: () -> CGSize) {\n value = nextValue()\n }\n}//off pref\n\n" ]
[ 0 ]
[]
[]
[ "ios", "swiftui", "xcode" ]
stackoverflow_0074650105_ios_swiftui_xcode.txt
Q: What happens if I cast a pointer that is NULL to something else? I have this piece of code here: assert_ptr_equals(get_data(hm,key_three),NULL); assert_true((int*)get_data(hm,key_three)==NULL); The get_data function returns a void pointer. The first assert is true but second one fails. Any idea why? Here is the minimum reproducible code #include<stdlib.h> #include<stddef.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #define ASSERTION_FAILURE_EXITCODE 47 #define assert_true(x) assert_that(x) #define assert_ptr_equals(x, y) assert_ptr_equals_internal(__FILE__, __extension__ __FUNCTION__, __LINE__, #x, x, #y, y) #define assert_that(x) assert_that_internal(__FILE__, __extension__ __FUNCTION__, __LINE__, #x, x) void assert_ptr_equals_internal(const char *file_name, const char *function_name, int line_number, const char *xname, void *x, const char *yname, void *y) { if (x != y) { fprintf(stderr, "%s:%s:%d: Expected <%s>:%p to be equal to <%s>:%p.\n", file_name, function_name, line_number, xname, x, yname, y); exit(ASSERTION_FAILURE_EXITCODE); } } void assert_that_internal(const char *file_name, const char *function_name, int line_number, const char *condition_name, int condition) { if (!condition) { fprintf(stderr, "%s:%s:%d: Expected '%s' to hold.\n", file_name, function_name, line_number, condition_name); exit(ASSERTION_FAILURE_EXITCODE); } } typedef void * Data; typedef Data (* ResolveCollisionCallback)(Data oldData, Data newData); typedef void (* CallbackIterate)(char * key, Data data); typedef void (* DestroyDataCallback)(Data data); typedef struct { Data * data; //Data pointer to the data char * key; //char pointer to the string key } HashMapItem; typedef struct hashmap { HashMapItem ** items; //items of the hashmaps size_t size; //size of the hashmaps int count; //how many elements are in the hashmap } HashMap; unsigned int hash(const char * key){ //sum of the charaters unsigned int sum = 0; for(int i=0; key[i] != '\0'; i++){ sum += key[i]; } return sum; } HashMap * create_hashmap(size_t key_space){ if(key_space == 0) return NULL; HashMap * hm = (HashMap *) malloc(sizeof(HashMap)); //allocate memory to store hashmap hm->items = (HashMapItem **) calloc(key_space, sizeof(HashMapItem**)); //allocate memory to store every item inside the map, null it hm->size = key_space; //set sitze of hashmap hm->count = 0; //empty at the begining return hm; } void insert_data(HashMap* hm, const char * key, const Data data, const ResolveCollisionCallback resolve_collison){ if(key == NULL || hm == NULL || data == NULL){ return; } //index where to put data unsigned int index = hash(key) % hm->size; if((hm->items)[index] != NULL){ (hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); //allocate memory to store the address if(resolve_collison!=NULL) *(hm->items)[index]->data = resolve_collison((hm->items)[index]->data, data); //copy address of data into the hashmap else *(hm->items)[index]->data = data; //if there is no resolve collision and there is data stored //store the data pointer as is } else { (hm->items)[index] = (HashMapItem *)malloc(sizeof(HashMapItem *)); (hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); *(hm->items)[index]->data = data; } //allocate new space for the string key and copy it there (hm->items)[index]->key = strdup(key); } Data get_data(HashMap* hm, char* key){ if(key == NULL && hm == NULL) return NULL; unsigned int index = hash(key) % hm->size; if((hm->items)[index] == NULL){ return NULL; } return *(hm->items)[index]->data; } void remove_data(HashMap* hm, char * key, DestroyDataCallback destroy_data){ if(hm == NULL || key == NULL) return; unsigned int index = hash(key) % hm->size; if((hm->items)[index] == NULL) return; if(destroy_data != NULL){ destroy_data((Data) *(hm->items)[index]->data); } free((hm->items)[index]->data); free((hm->items)[index]->key); free((hm->items)[index]); } void test1() { HashMap *hm = create_hashmap(30); char *key ="jsart", *key_two = ":@-)", *key_three = "stonks"; int x = 69, y = 420; void *placeholder = &x, *placeholder_two = &y; insert_data(hm, key_three, placeholder, NULL); assert_that(get_data(hm,key_three) == placeholder); remove_data(hm,key_three,NULL); assert_ptr_equals(get_data(hm,key_three),NULL); assert_true((int*)get_data(hm,key_three)==NULL); //delete_hashmap(hm, destroy); } int main(){ test1(); return 0; } A: At least these problems: Wrong allocation leading to UB (hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); I suspect OP wanted (hm->items)[index]->data = (Data *)malloc(sizeof(Data)); Avoid size mistakes, allocate to the referenced object. Cast not needed. (hm->items)[index]->data = malloc(sizeof (hm->items)[index]->data[0]); Also in (hm->items)[index] = (HashMapItem *)malloc(sizeof(HashMapItem *)); (hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); hm->items = (HashMapItem **) calloc(key_space, sizeof(HashMapItem**)); Dangling Pointers @n. m. "there is an error in remove_data that leaves (hm->items)[index] dangling after free"
What happens if I cast a pointer that is NULL to something else?
I have this piece of code here: assert_ptr_equals(get_data(hm,key_three),NULL); assert_true((int*)get_data(hm,key_three)==NULL); The get_data function returns a void pointer. The first assert is true but second one fails. Any idea why? Here is the minimum reproducible code #include<stdlib.h> #include<stddef.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #define ASSERTION_FAILURE_EXITCODE 47 #define assert_true(x) assert_that(x) #define assert_ptr_equals(x, y) assert_ptr_equals_internal(__FILE__, __extension__ __FUNCTION__, __LINE__, #x, x, #y, y) #define assert_that(x) assert_that_internal(__FILE__, __extension__ __FUNCTION__, __LINE__, #x, x) void assert_ptr_equals_internal(const char *file_name, const char *function_name, int line_number, const char *xname, void *x, const char *yname, void *y) { if (x != y) { fprintf(stderr, "%s:%s:%d: Expected <%s>:%p to be equal to <%s>:%p.\n", file_name, function_name, line_number, xname, x, yname, y); exit(ASSERTION_FAILURE_EXITCODE); } } void assert_that_internal(const char *file_name, const char *function_name, int line_number, const char *condition_name, int condition) { if (!condition) { fprintf(stderr, "%s:%s:%d: Expected '%s' to hold.\n", file_name, function_name, line_number, condition_name); exit(ASSERTION_FAILURE_EXITCODE); } } typedef void * Data; typedef Data (* ResolveCollisionCallback)(Data oldData, Data newData); typedef void (* CallbackIterate)(char * key, Data data); typedef void (* DestroyDataCallback)(Data data); typedef struct { Data * data; //Data pointer to the data char * key; //char pointer to the string key } HashMapItem; typedef struct hashmap { HashMapItem ** items; //items of the hashmaps size_t size; //size of the hashmaps int count; //how many elements are in the hashmap } HashMap; unsigned int hash(const char * key){ //sum of the charaters unsigned int sum = 0; for(int i=0; key[i] != '\0'; i++){ sum += key[i]; } return sum; } HashMap * create_hashmap(size_t key_space){ if(key_space == 0) return NULL; HashMap * hm = (HashMap *) malloc(sizeof(HashMap)); //allocate memory to store hashmap hm->items = (HashMapItem **) calloc(key_space, sizeof(HashMapItem**)); //allocate memory to store every item inside the map, null it hm->size = key_space; //set sitze of hashmap hm->count = 0; //empty at the begining return hm; } void insert_data(HashMap* hm, const char * key, const Data data, const ResolveCollisionCallback resolve_collison){ if(key == NULL || hm == NULL || data == NULL){ return; } //index where to put data unsigned int index = hash(key) % hm->size; if((hm->items)[index] != NULL){ (hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); //allocate memory to store the address if(resolve_collison!=NULL) *(hm->items)[index]->data = resolve_collison((hm->items)[index]->data, data); //copy address of data into the hashmap else *(hm->items)[index]->data = data; //if there is no resolve collision and there is data stored //store the data pointer as is } else { (hm->items)[index] = (HashMapItem *)malloc(sizeof(HashMapItem *)); (hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); *(hm->items)[index]->data = data; } //allocate new space for the string key and copy it there (hm->items)[index]->key = strdup(key); } Data get_data(HashMap* hm, char* key){ if(key == NULL && hm == NULL) return NULL; unsigned int index = hash(key) % hm->size; if((hm->items)[index] == NULL){ return NULL; } return *(hm->items)[index]->data; } void remove_data(HashMap* hm, char * key, DestroyDataCallback destroy_data){ if(hm == NULL || key == NULL) return; unsigned int index = hash(key) % hm->size; if((hm->items)[index] == NULL) return; if(destroy_data != NULL){ destroy_data((Data) *(hm->items)[index]->data); } free((hm->items)[index]->data); free((hm->items)[index]->key); free((hm->items)[index]); } void test1() { HashMap *hm = create_hashmap(30); char *key ="jsart", *key_two = ":@-)", *key_three = "stonks"; int x = 69, y = 420; void *placeholder = &x, *placeholder_two = &y; insert_data(hm, key_three, placeholder, NULL); assert_that(get_data(hm,key_three) == placeholder); remove_data(hm,key_three,NULL); assert_ptr_equals(get_data(hm,key_three),NULL); assert_true((int*)get_data(hm,key_three)==NULL); //delete_hashmap(hm, destroy); } int main(){ test1(); return 0; }
[ "At least these problems:\nWrong allocation leading to UB\n(hm->items)[index]->data = (Data *)malloc(sizeof(Data *)); \n\nI suspect OP wanted\n(hm->items)[index]->data = (Data *)malloc(sizeof(Data));\n\nAvoid size mistakes, allocate to the referenced object. Cast not needed.\n(hm->items)[index]->data = malloc(sizeof (hm->items)[index]->data[0]);\n\nAlso in\n (hm->items)[index] = (HashMapItem *)malloc(sizeof(HashMapItem *));\n (hm->items)[index]->data = (Data *)malloc(sizeof(Data *));\n\n hm->items = (HashMapItem **) calloc(key_space, sizeof(HashMapItem**)); \n\nDangling Pointers\n@n. m. \"there is an error in remove_data that leaves (hm->items)[index] dangling after free\"\n" ]
[ 3 ]
[]
[]
[ "c", "cmocka", "pointers" ]
stackoverflow_0074671567_c_cmocka_pointers.txt
Q: Perl Function Not Running My Perl code: use strict; use warnings; my $filename = 'data.txt'; open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!"; while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if($fields[7] eq "?" || $fields[7] eq NULL) print "$row\n"; } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); print '$fields: ' , replace($fields[1],"",$fields[1]) , "\n";} } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if (index($fields[2], "-") != -1) { print "$row\n"; } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if($fields[7] eq "Voyager2") print "$row\n"; } Error Message: "my" variable $row masks earlier declaration in same statement at main.pl line 24. "my" variable $row masks earlier declaration in same statement at main.pl line 25. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 10. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 11. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 11. syntax error at main.pl line 12, near ") print" Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 18. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 19. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 19. Unmatched right curly bracket at main.pl line 20, at end of line syntax error at main.pl line 20, near "}" Can't redeclare "my" in "my" at main.pl line 30, near "(my" main.pl has too many errors. Not sure where I went wrong and how to fix errors A: You've got some messed up indentation there that is masking your issues. Lets fix that indentation and highlight the problem. Skipping the error free parts. while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); # @fields undeclared if($fields[7] eq "?" || $fields[7] eq NULL) # missing curly braces { } and bareword NULL needs quotes print "$row\n"; } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); print '$fields: ' , replace($fields[1],"",$fields[1]) , "\n"; } # EXTRA curly brace here } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if (index($fields[2], "-") != -1) { print "$row\n"; } # MISSING curly brace here while (my $row = <$fh>) { # this loop is now part of the previous one, and the chomp $row; # duplicate variable errors start @fields = split(/:/, $row); if($fields[7] eq "Voyager2") print "$row\n"; # MISSING curly braces } So what happens if we fix all these things? Well, we get this, which produces no errors. my $filename = 'data.txt'; open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!"; while (my $row = <$fh>) { chomp $row; my @fields = split(/:/, $row); if($fields[7] eq "?" || $fields[7] eq "NULL") { print "$row\n"; } } while (my $row = <$fh>) { chomp $row; my @fields = split(/:/, $row); print '$fields: ' , replace($fields[1],"",$fields[1]) , "\n"; } while (my $row = <$fh>) { chomp $row; my @fields = split(/:/, $row); if (index($fields[2], "-") != -1) { print "$row\n"; } } while (my $row = <$fh>) { chomp $row; my @fields = split(/:/, $row); if($fields[7] eq "Voyager2") { print "$row\n"; } } But what is it that we have? This code will not work as expected. You have duplicated 4 while loops, and the first loop will exhaust the file handle, leaving the other loops without lines to process. Meaning they will never be executed. Unfortunately, since it is hard to say what you were trying to do here, it's hard to say how to fix it. My guess is that you thought you could read lines in order with a while loop. Perhaps last is what you are looking for, to skip out of the while loop when you find a condition. Perhaps while is wrong for you, and you meant to take line 1, then line 2, etc. Then you need to remove all the while loops. Without more information, the TL;DR is: Your code does not work.
Perl Function Not Running
My Perl code: use strict; use warnings; my $filename = 'data.txt'; open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!"; while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if($fields[7] eq "?" || $fields[7] eq NULL) print "$row\n"; } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); print '$fields: ' , replace($fields[1],"",$fields[1]) , "\n";} } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if (index($fields[2], "-") != -1) { print "$row\n"; } while (my $row = <$fh>) { chomp $row; @fields = split(/:/, $row); if($fields[7] eq "Voyager2") print "$row\n"; } Error Message: "my" variable $row masks earlier declaration in same statement at main.pl line 24. "my" variable $row masks earlier declaration in same statement at main.pl line 25. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 10. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 11. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 11. syntax error at main.pl line 12, near ") print" Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 18. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 19. Global symbol "@fields" requires explicit package name (did you forget to declare "my @fields"?) at main.pl line 19. Unmatched right curly bracket at main.pl line 20, at end of line syntax error at main.pl line 20, near "}" Can't redeclare "my" in "my" at main.pl line 30, near "(my" main.pl has too many errors. Not sure where I went wrong and how to fix errors
[ "You've got some messed up indentation there that is masking your issues. Lets fix that indentation and highlight the problem. Skipping the error free parts.\nwhile (my $row = <$fh>) {\n chomp $row;\n @fields = split(/:/, $row); # @fields undeclared\n if($fields[7] eq \"?\" || $fields[7] eq NULL) # missing curly braces { } and bareword NULL needs quotes\n print \"$row\\n\";\n}\n\nwhile (my $row = <$fh>) {\n chomp $row;\n @fields = split(/:/, $row);\n print '$fields: ' , replace($fields[1],\"\",$fields[1]) , \"\\n\";\n} # EXTRA curly brace here\n}\n\nwhile (my $row = <$fh>) {\n chomp $row;\n @fields = split(/:/, $row);\n if (index($fields[2], \"-\") != -1) {\n print \"$row\\n\";\n }\n# MISSING curly brace here\n\n while (my $row = <$fh>) { # this loop is now part of the previous one, and the \n chomp $row; # duplicate variable errors start\n @fields = split(/:/, $row);\n if($fields[7] eq \"Voyager2\") print \"$row\\n\"; # MISSING curly braces\n}\n\nSo what happens if we fix all these things? Well, we get this, which produces no errors.\nmy $filename = 'data.txt';\nopen(my $fh, '<:encoding(UTF-8)', $filename)\n or die \"Could not open file '$filename' $!\";\n \nwhile (my $row = <$fh>) {\n chomp $row;\n my @fields = split(/:/, $row);\n if($fields[7] eq \"?\" || $fields[7] eq \"NULL\") {\n print \"$row\\n\";\n }\n}\n\nwhile (my $row = <$fh>) {\n chomp $row;\n my @fields = split(/:/, $row);\n print '$fields: ' , replace($fields[1],\"\",$fields[1]) , \"\\n\";\n}\n\nwhile (my $row = <$fh>) {\n chomp $row;\n my @fields = split(/:/, $row);\n if (index($fields[2], \"-\") != -1) {\n print \"$row\\n\";\n }\n}\n\nwhile (my $row = <$fh>) {\n chomp $row;\n my @fields = split(/:/, $row);\n if($fields[7] eq \"Voyager2\") {\n print \"$row\\n\";\n }\n}\n\nBut what is it that we have? This code will not work as expected. You have duplicated 4 while loops, and the first loop will exhaust the file handle, leaving the other loops without lines to process. Meaning they will never be executed. Unfortunately, since it is hard to say what you were trying to do here, it's hard to say how to fix it.\nMy guess is that you thought you could read lines in order with a while loop. Perhaps last is what you are looking for, to skip out of the while loop when you find a condition. Perhaps while is wrong for you, and you meant to take line 1, then line 2, etc. Then you need to remove all the while loops.\nWithout more information, the TL;DR is: Your code does not work.\n" ]
[ 4 ]
[]
[]
[ "perl", "syntax_error" ]
stackoverflow_0074670457_perl_syntax_error.txt
Q: Force 'Sign up with ' flow to reappear for Sign in with Apple in Flutter and retrieve email and fullName The first time I signed in with Apple in my app, I received the full Create an account for <app> using your Apple ID flow. However, I was not able to see and save the email and fullName fields. In all subsequent logins after original sign up, only the uid is given by Apple. This is expected behaviour, see Cannot get name & email with sign in with Apple on real device { credential = { authorizationCode = "<FlutterStandardTypedData: 0x28195d5a0>"; authorizedScopes = ( ); email = "<null>"; fullName = { familyName = "<null>"; givenName = "<null>"; middleName = "<null>"; namePrefix = "<null>"; nameSuffix = "<null>"; nickname = "<null>"; }; identityToken = "<FlutterStandardTypedData: 0x28195d460>"; realUserStatus = 2; state = "<null>"; user = "my user code"; }; credentialType = ASAuthorizationAppleIDCredential; status = authorized; } They advise to remove the app in my Sign in with Apple list and that it should force the original screen to show up again: Unfortunately, for this account it does not show the original login flow after this step, but just the regular Log in screen, for when you are a returning user. Other steps I added: removing the record from the Authentication screen in the Users table in Firebase. disabling, deleting and re-enabling the Apple Sign in in Firebase flutter clean flutter pub cache repair deleting the app from the test device, rebooting test device and rebuilding from Android Studio. removing and re-adding Sign in with Apple in XCode via Runner -> Signing & Capabilities logging in with my Google Sign in and then logging out so it clears my shared preferences: SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.clear(); Env info: username@devicename appname % flutter doctor -v [✓] Flutter (Channel stable, 3.3.8, on macOS 12.6.1 21G217 darwin-x64, locale en-NL) • Flutter version 3.3.8 on channel stable at /Users/username/Development/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 52b3dc25f6 (4 weeks ago), 2022-11-09 12:09:26 +0800 • Engine revision 857bd6b74c • Dart version 2.18.4 • DevTools version 2.15.0 [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0) • Android SDK at /Users/username/Library/Android/sdk • Platform android-33, build-tools 32.0.0 • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866) • All Android licenses accepted. [✓] Xcode - develop for iOS and macOS (Xcode 14.1) • Xcode at /Applications/Xcode.app/Contents/Developer • Build 14B47b • CocoaPods version 1.11.2 [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2021.3) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866) [✓] Connected device (3 available) • iPhone X (mobile) • 79f8aa15db6582019ae695924b064c727bacb88f • ios • iOS 15.6 19G71 • macOS (desktop) • macos • darwin-x64 • macOS 12.6.1 21G217 darwin-x64 • Chrome (web) • chrome • web-javascript • Google Chrome 107.0.5304.121 [✓] HTTP Host Availability • All required HTTP hosts are available Update: By adding the following step to the above list, I am able to force the original login flow: Log out apple account on test device and do not keep any associated data (probably stored data in my keychain via iCloud) However, when running fresh, still the email and fullName fields are empty. A: Turns out it was because I used an old flutter library that did not support the logout feature correctly. I used apple_sign_in, which has been abandoned. That package referenced the_apple_sign_in as the successor. But this package is also out of date. As of date of posting, the package to use is sign_in_with_apple. I used 4.2.0. If you do this, then it is enough to trigger the original sign up flow just by removing the app in my Sign in with Apple list here (https://appleid.apple.com/account/manage).
Force 'Sign up with ' flow to reappear for Sign in with Apple in Flutter and retrieve email and fullName
The first time I signed in with Apple in my app, I received the full Create an account for <app> using your Apple ID flow. However, I was not able to see and save the email and fullName fields. In all subsequent logins after original sign up, only the uid is given by Apple. This is expected behaviour, see Cannot get name & email with sign in with Apple on real device { credential = { authorizationCode = "<FlutterStandardTypedData: 0x28195d5a0>"; authorizedScopes = ( ); email = "<null>"; fullName = { familyName = "<null>"; givenName = "<null>"; middleName = "<null>"; namePrefix = "<null>"; nameSuffix = "<null>"; nickname = "<null>"; }; identityToken = "<FlutterStandardTypedData: 0x28195d460>"; realUserStatus = 2; state = "<null>"; user = "my user code"; }; credentialType = ASAuthorizationAppleIDCredential; status = authorized; } They advise to remove the app in my Sign in with Apple list and that it should force the original screen to show up again: Unfortunately, for this account it does not show the original login flow after this step, but just the regular Log in screen, for when you are a returning user. Other steps I added: removing the record from the Authentication screen in the Users table in Firebase. disabling, deleting and re-enabling the Apple Sign in in Firebase flutter clean flutter pub cache repair deleting the app from the test device, rebooting test device and rebuilding from Android Studio. removing and re-adding Sign in with Apple in XCode via Runner -> Signing & Capabilities logging in with my Google Sign in and then logging out so it clears my shared preferences: SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.clear(); Env info: username@devicename appname % flutter doctor -v [✓] Flutter (Channel stable, 3.3.8, on macOS 12.6.1 21G217 darwin-x64, locale en-NL) • Flutter version 3.3.8 on channel stable at /Users/username/Development/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 52b3dc25f6 (4 weeks ago), 2022-11-09 12:09:26 +0800 • Engine revision 857bd6b74c • Dart version 2.18.4 • DevTools version 2.15.0 [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0) • Android SDK at /Users/username/Library/Android/sdk • Platform android-33, build-tools 32.0.0 • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866) • All Android licenses accepted. [✓] Xcode - develop for iOS and macOS (Xcode 14.1) • Xcode at /Applications/Xcode.app/Contents/Developer • Build 14B47b • CocoaPods version 1.11.2 [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2021.3) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866) [✓] Connected device (3 available) • iPhone X (mobile) • 79f8aa15db6582019ae695924b064c727bacb88f • ios • iOS 15.6 19G71 • macOS (desktop) • macos • darwin-x64 • macOS 12.6.1 21G217 darwin-x64 • Chrome (web) • chrome • web-javascript • Google Chrome 107.0.5304.121 [✓] HTTP Host Availability • All required HTTP hosts are available Update: By adding the following step to the above list, I am able to force the original login flow: Log out apple account on test device and do not keep any associated data (probably stored data in my keychain via iCloud) However, when running fresh, still the email and fullName fields are empty.
[ "Turns out it was because I used an old flutter library that did not support the logout feature correctly.\nI used apple_sign_in, which has been abandoned.\nThat package referenced the_apple_sign_in as the successor. But this package is also out of date.\nAs of date of posting, the package to use is sign_in_with_apple. I used 4.2.0.\nIf you do this, then it is enough to trigger the original sign up flow just by removing the app in my Sign in with Apple list here (https://appleid.apple.com/account/manage).\n" ]
[ 0 ]
[]
[]
[ "apple_sign_in", "authentication", "flutter", "ios", "xcode" ]
stackoverflow_0074671355_apple_sign_in_authentication_flutter_ios_xcode.txt
Q: How to use ordinal encoder after splitting dataset? I have a dataframe X and Y. The X data frame consists of independent categorical variables and Y dataset consists of dependant variables. How do I apply ordinal encoder to the X dataframe after the dataset has been split? step1 = ColumnTransformer(transformers=[ ('col_tnf',OrdinalEncoder([x])) ],remainder='passthrough') step2 = RandomForestRegressor(n_estimators=14, random_state=42, max_features=0.7) pipe = Pipeline([ ('step1',step1), ('step2',step2) ]) pipe.fit(X_train,y_train) y_pred = pipe.predict(X_test) print('R2 score',r2_score(X_test,y_test)) A: To apply ordinal encoder to the X dataframe after splitting the dataset, you can first initialize the ordinal encoder and then fit and transform the X_train data. This will encode the categorical variables in the training set according to the ordinal encoding scheme. Then you can use the same ordinal encoder to transform the X_test data. This will ensure that the categorical variables in the test set are encoded in the same way as the training set, which is important for ensuring the validity of the model's predictions. Here is an example of how you could do this: # Initialize the ordinal encoder ordinal_encoder = OrdinalEncoder() # Fit and transform the X_train data using the ordinal encoder X_train = ordinal_encoder.fit_transform(X_train) # Transform the X_test data using the ordinal encoder X_test = ordinal_encoder.transform(X_test) Once you have encoded the categorical variables in the X_train and X_test data, you can proceed to fit and evaluate your model as you have done in your code above.
How to use ordinal encoder after splitting dataset?
I have a dataframe X and Y. The X data frame consists of independent categorical variables and Y dataset consists of dependant variables. How do I apply ordinal encoder to the X dataframe after the dataset has been split? step1 = ColumnTransformer(transformers=[ ('col_tnf',OrdinalEncoder([x])) ],remainder='passthrough') step2 = RandomForestRegressor(n_estimators=14, random_state=42, max_features=0.7) pipe = Pipeline([ ('step1',step1), ('step2',step2) ]) pipe.fit(X_train,y_train) y_pred = pipe.predict(X_test) print('R2 score',r2_score(X_test,y_test))
[ "To apply ordinal encoder to the X dataframe after splitting the dataset, you can first initialize the ordinal encoder and then fit and transform the X_train data. This will encode the categorical variables in the training set according to the ordinal encoding scheme. Then you can use the same ordinal encoder to transform the X_test data. This will ensure that the categorical variables in the test set are encoded in the same way as the training set, which is important for ensuring the validity of the model's predictions.\nHere is an example of how you could do this:\n# Initialize the ordinal encoder\nordinal_encoder = OrdinalEncoder()\n\n# Fit and transform the X_train data using the ordinal encoder\nX_train = ordinal_encoder.fit_transform(X_train)\n\n# Transform the X_test data using the ordinal encoder\nX_test = ordinal_encoder.transform(X_test)\n\nOnce you have encoded the categorical variables in the X_train and X_test data, you can proceed to fit and evaluate your model as you have done in your code above.\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "ordinal", "supervised_learning" ]
stackoverflow_0074671887_machine_learning_ordinal_supervised_learning.txt
Q: How to order list of lists of strings by another list of lists of floats in Pandas I have a Pandas dataframe such that df['cname']: 0 [berkshire, hathaway] 1 [icbc] 2 [saudi, arabian, oil, company, saudi, aramco] 3 [jpmorgan, chase] 4 [china, construction, bank] Name: tokenized_company_name, dtype: object and another Pandas dataframe such that tfidf['output']: [0.7071067811865476, 0.7071067811865476] [1.0] [0.3779598156018814, 0.39838548612653973, 0.39838548612653973, 0.3285496573358837, 0.6570993146717674] [0.7071067811865476, 0.7071067811865476] [0.4225972188244829, 0.510750779645552, 0.7486956870005814] I'm trying to sort each list of tokens in f_sp['tokenized_company_name'] by tfidf['output_column'] such that I get: 0 [berkshire, hathaway] # no difference 1 [icbc] # no difference 2 [aramco, arabian, oil, saudi, company] # re-ordered by decreasing value of tf_sp['output_column'] 3 [chase, jpmorgan] # tied elements should be ordered alphabetically 4 [bank, construction, china] # re-ordered by decreasing value of tf_sp['output_column'] Here's what I've tried so far: (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], reverse=True), axis=1)) But I get the following error: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [166], in <cell line: 1>() ----> 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\frame.py:9555, in DataFrame.apply(self, func, axis, raw, result_type, args, **kwargs) 9544 from pandas.core.apply import frame_apply 9546 op = frame_apply( 9547 self, 9548 func=func, (...) 9553 kwargs=kwargs, 9554 ) -> 9555 return op.apply().__finalize__(self, method="apply") File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:746, in FrameApply.apply(self) 743 elif self.raw: 744 return self.apply_raw() --> 746 return self.apply_standard() File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:873, in FrameApply.apply_standard(self) 872 def apply_standard(self): --> 873 results, res_index = self.apply_series_generator() 875 # wrap results 876 return self.wrap_results(results, res_index) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:889, in FrameApply.apply_series_generator(self) 886 with option_context("mode.chained_assignment", None): 887 for i, v in enumerate(series_gen): 888 # ignore SettingWithCopy here in case the user mutates --> 889 results[i] = self.f(v) 890 if isinstance(results[i], ABCSeries): 891 # If we have a view on v, we need to make a copy because 892 # series_generator will swap out the underlying data 893 results[i] = results[i].copy(deep=False) Input In [166], in <lambda>(x) ----> 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) Input In [166], in <lambda>.<locals>.<lambda>(y) 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], ----> 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) IndexError: list index out of range Why is this happening? Each list of lists has the same number of elements. A: To sort the list of tokens in f_sp['tokenized_company_name'] by the corresponding value in tf_sp['output_column'], you can use the zip function to combine the two columns and then sort the resulting list of tuples by the value of the second element in each tuple (which is the corresponding value from tf_sp['output_column']). You can then extract only the first element of each tuple (which is the token) to obtain the sorted list of tokens. Here is an example of how you can achieve this using a lambda function with the apply method of f_sp: f_sp['tokenized_company_name'] = f_sp.apply(lambda x: [t[0] for t in sorted(zip(x['tokenized_company_name'], tf_sp.loc[x.name, 'output_column']), key=lambda t: t[1], reverse=True)], axis=1) This will sort the list of tokens in f_sp['tokenized_company_name'] by the corresponding value in tf_sp['output_column'] and store the sorted list back in f_sp['tokenized_company_name']. Note that this solution assumes that the length of f_sp['tokenized_company_name'] and tf_sp['output_column'] is the same for each row in f_sp. Otherwise, you may need to handle the case where the length of the two columns is different. A: To order a list of lists of strings by another list of lists of floats in Pandas, you can use the "sort_values" method. Here is an example: import pandas as pd # create dataframe with string lists as data df = pd.DataFrame({'strings': [['apple', 'banana', 'cherry'], ['dog', 'cat', 'bird'], ['red', 'green', 'blue']]}) # create dataframe with float lists as data df_floats = pd.DataFrame({'floats': [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]}) # sort the string dataframe by the float dataframe df.sort_values(by=df_floats['floats']) This will return a new dataframe with the strings in each list sorted according to the corresponding list of floats.
How to order list of lists of strings by another list of lists of floats in Pandas
I have a Pandas dataframe such that df['cname']: 0 [berkshire, hathaway] 1 [icbc] 2 [saudi, arabian, oil, company, saudi, aramco] 3 [jpmorgan, chase] 4 [china, construction, bank] Name: tokenized_company_name, dtype: object and another Pandas dataframe such that tfidf['output']: [0.7071067811865476, 0.7071067811865476] [1.0] [0.3779598156018814, 0.39838548612653973, 0.39838548612653973, 0.3285496573358837, 0.6570993146717674] [0.7071067811865476, 0.7071067811865476] [0.4225972188244829, 0.510750779645552, 0.7486956870005814] I'm trying to sort each list of tokens in f_sp['tokenized_company_name'] by tfidf['output_column'] such that I get: 0 [berkshire, hathaway] # no difference 1 [icbc] # no difference 2 [aramco, arabian, oil, saudi, company] # re-ordered by decreasing value of tf_sp['output_column'] 3 [chase, jpmorgan] # tied elements should be ordered alphabetically 4 [bank, construction, china] # re-ordered by decreasing value of tf_sp['output_column'] Here's what I've tried so far: (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], reverse=True), axis=1)) But I get the following error: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [166], in <cell line: 1>() ----> 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\frame.py:9555, in DataFrame.apply(self, func, axis, raw, result_type, args, **kwargs) 9544 from pandas.core.apply import frame_apply 9546 op = frame_apply( 9547 self, 9548 func=func, (...) 9553 kwargs=kwargs, 9554 ) -> 9555 return op.apply().__finalize__(self, method="apply") File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:746, in FrameApply.apply(self) 743 elif self.raw: 744 return self.apply_raw() --> 746 return self.apply_standard() File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:873, in FrameApply.apply_standard(self) 872 def apply_standard(self): --> 873 results, res_index = self.apply_series_generator() 875 # wrap results 876 return self.wrap_results(results, res_index) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:889, in FrameApply.apply_series_generator(self) 886 with option_context("mode.chained_assignment", None): 887 for i, v in enumerate(series_gen): 888 # ignore SettingWithCopy here in case the user mutates --> 889 results[i] = self.f(v) 890 if isinstance(results[i], ABCSeries): 891 # If we have a view on v, we need to make a copy because 892 # series_generator will swap out the underlying data 893 results[i] = results[i].copy(deep=False) Input In [166], in <lambda>(x) ----> 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) Input In [166], in <lambda>.<locals>.<lambda>(y) 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], ----> 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) IndexError: list index out of range Why is this happening? Each list of lists has the same number of elements.
[ "To sort the list of tokens in f_sp['tokenized_company_name'] by the corresponding value in tf_sp['output_column'], you can use the zip function to combine the two columns and then sort the resulting list of tuples by the value of the second element in each tuple (which is the corresponding value from tf_sp['output_column']). You can then extract only the first element of each tuple (which is the token) to obtain the sorted list of tokens.\nHere is an example of how you can achieve this using a lambda function with the apply method of f_sp:\nf_sp['tokenized_company_name'] = f_sp.apply(lambda x: [t[0] for t in sorted(zip(x['tokenized_company_name'], tf_sp.loc[x.name, 'output_column']), key=lambda t: t[1], reverse=True)], axis=1)\n\nThis will sort the list of tokens in f_sp['tokenized_company_name'] by the corresponding value in tf_sp['output_column'] and store the sorted list back in f_sp['tokenized_company_name'].\nNote that this solution assumes that the length of f_sp['tokenized_company_name'] and tf_sp['output_column'] is the same for each row in f_sp. Otherwise, you may need to handle the case where the length of the two columns is different.\n", "To order a list of lists of strings by another list of lists of floats in Pandas, you can use the \"sort_values\" method. Here is an example:\nimport pandas as pd\n\n# create dataframe with string lists as data\ndf = pd.DataFrame({'strings': [['apple', 'banana', 'cherry'],\n ['dog', 'cat', 'bird'],\n ['red', 'green', 'blue']]})\n\n# create dataframe with float lists as data\ndf_floats = pd.DataFrame({'floats': [[1.0, 2.0, 3.0],\n [4.0, 5.0, 6.0],\n [7.0, 8.0, 9.0]]})\n\n# sort the string dataframe by the float dataframe\ndf.sort_values(by=df_floats['floats'])\n\nThis will return a new dataframe with the strings in each list sorted according to the corresponding list of floats.\n" ]
[ 0, 0 ]
[]
[]
[ "nlp", "pandas", "python", "string", "token" ]
stackoverflow_0074671883_nlp_pandas_python_string_token.txt
Q: asyncg - transaction requirement I found in the asyncpg documentation that every call to сonnection.execute() or connection.fetch() should be wrapped in async with connection.transaction():. But in one of the repositories I saw the following code without wrapping it in a transaction: async def bench_asyncpg_con(): start = time.monotonic() for i in range(1, 1000): con = await asyncpg.connect(user='benchmark_user', database='benchmark_db', host='127.0.0.1') await con.fetchval('SELECT * FROM "Post" LIMIT 100') await con.close() end = time.monotonic() print(end - start) And it works. Can you explain to me when I should use transactions and when I shouldn't ? A: The reason why the code in your example doesn't have a transaction is because it's just fetching data from the database. There are no changes happening to the database (no udpates, no inserted data, no deleting of data, etc..) Quoted from asyncpg docs: When not in an explicit transaction block, any changes to the database will be applied immediately. This is also known as auto-commit. From the quote above, when you use asyncpg to execute a query to change data in the database, it will be automatically committed unless you use a transaction. When you wrap your code in a transaction, you have to call commit to have those changes saved. Additionally, transactions allow you to execute queries and if any of those queries fail, you can rollback all of the executed queries that were wrapped in that transaction. Here is an example of a transaction that shows you the mechanics. tr = connection.transaction() await tr.start() try: ... except: await tr.rollback() raise else: await tr.commit()
asyncg - transaction requirement
I found in the asyncpg documentation that every call to сonnection.execute() or connection.fetch() should be wrapped in async with connection.transaction():. But in one of the repositories I saw the following code without wrapping it in a transaction: async def bench_asyncpg_con(): start = time.monotonic() for i in range(1, 1000): con = await asyncpg.connect(user='benchmark_user', database='benchmark_db', host='127.0.0.1') await con.fetchval('SELECT * FROM "Post" LIMIT 100') await con.close() end = time.monotonic() print(end - start) And it works. Can you explain to me when I should use transactions and when I shouldn't ?
[ "The reason why the code in your example doesn't have a transaction is because it's just fetching data from the database. There are no changes happening to the database (no udpates, no inserted data, no deleting of data, etc..) Quoted from asyncpg docs:\n\nWhen not in an explicit transaction block, any changes to the database will be applied immediately. This is also known as auto-commit.\n\nFrom the quote above, when you use asyncpg to execute a query to change data in the database, it will be automatically committed unless you use a transaction. When you wrap your code in a transaction, you have to call commit to have those changes saved. Additionally, transactions allow you to execute queries and if any of those queries fail, you can rollback all of the executed queries that were wrapped in that transaction. Here is an example of a transaction that shows you the mechanics.\ntr = connection.transaction()\nawait tr.start()\ntry:\n ...\nexcept:\n await tr.rollback()\n raise\nelse:\n await tr.commit()\n\n" ]
[ 1 ]
[]
[]
[ "asyncpg", "python" ]
stackoverflow_0071783811_asyncpg_python.txt
Q: URLCache not caching 404 response My server is sending proper cache headers, however URLSession will not cache the response. Is there any way to make it cache, although it is a 404? HTTP/1.1 404 Not Found Content-Type: application/json; charset=utf-8 Cache-Control: public, max-age=30 Content-Length: 0 Date: Fri, 02 Dec 2022 10:39:43 GMT A: Unfortunately, URLSession uses the HTTP status code to determine whether to cache the response. Since the status code is 404 (not found) the response will not be cached. The best thing to do is to make sure that your server is returning an appropriate status code (such as 200 OK) for the response you want to be cached. Example: func shouldCacheResponse(for request: URLRequest) -> Bool { let session = URLSession.shared var shouldCacheResponse = false let task = session.dataTask(with: request) { data, response, error in guard let response = response as? HTTPURLResponse else { return } shouldCacheResponse = response.statusCode == 200 } task.resume() return shouldCacheResponse } This code is a function that takes a URLRequest as an argument and returns a boolean value. The code uses URLSession to create a data task with the URLRequest. It then uses a guard statement to check if the response is an HTTPURLResponse. If it is, it sets the shouldCacheResponse variable to true if the status code is equal to 200. Finally, the task is resumed and the function returns the value of shouldCacheResponse.
URLCache not caching 404 response
My server is sending proper cache headers, however URLSession will not cache the response. Is there any way to make it cache, although it is a 404? HTTP/1.1 404 Not Found Content-Type: application/json; charset=utf-8 Cache-Control: public, max-age=30 Content-Length: 0 Date: Fri, 02 Dec 2022 10:39:43 GMT
[ "Unfortunately, URLSession uses the HTTP status code to determine whether to cache the response. Since the status code is 404 (not found) the response will not be cached.\nThe best thing to do is to make sure that your server is returning an appropriate status code (such as 200 OK) for the response you want to be cached.\nExample:\nfunc shouldCacheResponse(for request: URLRequest) -> Bool {\nlet session = URLSession.shared\nvar shouldCacheResponse = false\nlet task = session.dataTask(with: request) {\n data, response, error in guard let response = response as? HTTPURLResponse\n else { return }\n shouldCacheResponse = response.statusCode == 200\n}\ntask.resume()\nreturn shouldCacheResponse\n\n}\nThis code is a function that takes a URLRequest as an argument and returns a boolean value. The code uses URLSession to create a data task with the URLRequest. It then uses a guard statement to check if the response is an HTTPURLResponse. If it is, it sets the shouldCacheResponse variable to true if the status code is equal to 200. Finally, the task is resumed and the function returns the value of shouldCacheResponse.\n" ]
[ 0 ]
[]
[]
[ "ios", "nsurlcache", "swift", "urlcache" ]
stackoverflow_0074654429_ios_nsurlcache_swift_urlcache.txt
Q: MongoRuntimeError: Connection pool closed I am seeing my mongoose pool seemingly close before it inserts data as I am getting this error when making a call to my mongoose db in my cloud cluster MongoRuntimeError: Connection pool closed but I am awaiting all of the calls? so I'm unsure why I'm seeing this issue, maybe it has something to do with the way I am defining my client? hopefully someone has some tips or ideas on this export const storeData = async (data) =>{ const uri = `mongodb+srv://plantmaster:${password}@cluster0.yey8l.mongodb.net/plantstore?retryWrites=true&w=majority`; const client = await MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 }); const newPLantData = { name: "Company Inc", address: "Highway 37" }; await client.db("plantstore").collection("plantdata").insertOne(newPLantData, (err, res) =>{ if(err) throw err; console.log(result) }) await client.close(); }; I am calling this function on an express post route like so // store data app.post('/store', async function (req, res) { await storeData(req.body); res.send('data was stored') }) A: i was facing the same error, but i fixed it by waiting 1500ms before closing the connection. setTimeout(() => {client.close()}, 1500) A: Try this example approach import { MongoClient } from "mongodb"; const handler = async (req, res) => { if (req.method === "POST") { const { email } = req.body; if (!email || !email.includes("@")) { res.status(422).json({ message: "Entered email is not valid" }); return; } const url = <your-mongo-url> const client = new MongoClient(url); await client.connect(); const collection = client.db("events").collection("newsletter"); try { await collection.insertOne({ email }); return res.status(201).json({ message: "You have successfully signed up to newsletters!", email, }); } catch (error) { throw res.status(500).json({ message: "Server error occured" }); } finally { client.close(); } } }; export default handler;
MongoRuntimeError: Connection pool closed
I am seeing my mongoose pool seemingly close before it inserts data as I am getting this error when making a call to my mongoose db in my cloud cluster MongoRuntimeError: Connection pool closed but I am awaiting all of the calls? so I'm unsure why I'm seeing this issue, maybe it has something to do with the way I am defining my client? hopefully someone has some tips or ideas on this export const storeData = async (data) =>{ const uri = `mongodb+srv://plantmaster:${password}@cluster0.yey8l.mongodb.net/plantstore?retryWrites=true&w=majority`; const client = await MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 }); const newPLantData = { name: "Company Inc", address: "Highway 37" }; await client.db("plantstore").collection("plantdata").insertOne(newPLantData, (err, res) =>{ if(err) throw err; console.log(result) }) await client.close(); }; I am calling this function on an express post route like so // store data app.post('/store', async function (req, res) { await storeData(req.body); res.send('data was stored') })
[ "i was facing the same error, but i fixed it by waiting 1500ms before closing the connection.\nsetTimeout(() => {client.close()}, 1500)\n\n", "Try this example approach\nimport { MongoClient } from \"mongodb\";\n\nconst handler = async (req, res) => {\n if (req.method === \"POST\") {\n const { email } = req.body;\n\n if (!email || !email.includes(\"@\")) {\n res.status(422).json({ message: \"Entered email is not valid\" });\n return;\n }\n\n const url = <your-mongo-url>\n const client = new MongoClient(url);\n await client.connect();\n \n const collection = client.db(\"events\").collection(\"newsletter\");\n\n try {\n await collection.insertOne({ email });\n return res.status(201).json({\n message: \"You have successfully signed up to newsletters!\",\n email,\n });\n } catch (error) {\n throw res.status(500).json({ message: \"Server error occured\" });\n } finally {\n client.close();\n }\n }\n};\n\nexport default handler;\n\n" ]
[ 4, 0 ]
[]
[]
[ "api", "mongodb", "node.js" ]
stackoverflow_0072155712_api_mongodb_node.js.txt
Q: How to replace a value in a matrix by index Let's say I have a 4X4 matrix containing value from 1 to 20. If I want the element at line 2 column 3 to be equal to 100, how can I do this ? A: First, import the numpy library: import numpy as np Then, create the matrix: matrix = np.array([[1,2,3], [4,5,6], [7,8,9]]) Finally, use the index to replace the value: matrix[1,2] = 10 The new matrix will be: [[ 1 2 3] [ 4 5 10] [ 7 8 9]]
How to replace a value in a matrix by index
Let's say I have a 4X4 matrix containing value from 1 to 20. If I want the element at line 2 column 3 to be equal to 100, how can I do this ?
[ "First, import the numpy library:\n\nimport numpy as np\n\nThen, create the matrix:\n\nmatrix = np.array([[1,2,3], [4,5,6], [7,8,9]])\n\nFinally, use the index to replace the value:\n\nmatrix[1,2] = 10\nThe new matrix will be:\n\n[[ 1 2 3]\n [ 4 5 10]\n [ 7 8 9]]\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671888_python.txt
Q: No module named 'Adafruit_GPIO' I am doing the project in this video (https://www.youtube.com/watch?v=9sb_zuHGmY4) with the OLED screen. The step by step guide I followed (https://www.the-diy-life.com/diy-raspberry-pi-4-desktop-case-with-oled-stats-display/) and I get this error: Traceback (most recent call last): File "stats.py", line 23, in <module> import Adafruit_GPIO.SPI as SPI ModuleNotFoundError: No module named 'Adafruit_GPIO' Code: # Author: Tony DiCola & James DeVito # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import time import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont import subprocess # Raspberry Pi pin configuration: RST = None # on the PiOLED this pin isnt used # Note the following are only used with SPI: DC = 23 SPI_PORT = 0 SPI_DEVICE = 0 # Beaglebone Black pin configuration: # RST = 'P9_12' # Note the following are only used with SPI: # DC = 'P9_15' # SPI_PORT = 1 # SPI_DEVICE = 0 # 128x32 display with hardware I2C: disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) # 128x64 display with hardware I2C: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST) # Note you can change the I2C address by passing an i2c_address parameter like: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) # Alternatively you can specify an explicit I2C bus number, for example # with the 128x32 display you would use: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2) # 128x32 display with hardware SPI: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # 128x64 display with hardware SPI: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # Alternatively you can specify a software SPI implementation by providing # digital GPIO pin numbers for all the required display pins. For example # on a Raspberry Pi with the 128x32 display you might use: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22) # Initialize library. disp.begin() # Clear display. disp.clear() disp.display() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. width = disp.width height = disp.height image = Image.new('1', (width, height)) # Get drawing object to draw on image. draw = ImageDraw.Draw(image) # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) # Draw some shapes. # First define some constants to allow easy resizing of shapes. padding = -2 top = padding bottom = height-padding # Move left to right keeping track of the current x position for drawing shapes. x = 0 # Load default font. font = ImageFont.load_default() # Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script! # Some other nice fonts to try: http://www.dafont.com/bitmap.php # font = ImageFont.truetype('Minecraftia.ttf', 8) while True: # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load cmd = "hostname -I | cut -d\' \' -f1" IP = subprocess.check_output(cmd, shell = True ) cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'" CPU = subprocess.check_output(cmd, shell = True ) cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'" MemUsage = subprocess.check_output(cmd, shell = True ) cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'" Disk = subprocess.check_output(cmd, shell = True ) # Write two lines of text. draw.text((x, top), "IP: " + str(IP), font=font, fill=255) draw.text((x, top+8), str(CPU), font=font, fill=255) draw.text((x, top+16), str(MemUsage), font=font, fill=255) draw.text((x, top+25), str(Disk), font=font, fill=255) # Display image. disp.image(image) disp.display() time.sleep(.1) A: When in doubt, take a look at the official docs! You're missing an old library. While you may be able to bring it in, the maintainers have actually deprecated it and suggest another https://github.com/adafruit/Adafruit_Python_GPIO This library has been deprecated in favor of our python3 Blinka library. We have replaced all of the libraries that use this repo with CircuitPython libraries that are Python3 compatible, and support a wide variety of single board/linux computers! Do take a look at the updated docs from Adafruit: https://learn.adafruit.com/monochrome-oled-breakouts/python-usage-2 They have a direct example showing the use of these libraries import board import digitalio from PIL import Image, ImageDraw, ImageFont import adafruit_ssd1306 ... A: This is a couple years late, but figured why not post my solution. I’ve put together an updated setup.py script that’s adapted to Adafruit’s newer CircuitPython libraries. To note, I’ve tested this on a 4GB RPI4B running Raspbian GNU/Linux 11 armv7. Before attempting to execute this script, make sure to follow the 'Python Setup' instructions listed here.
No module named 'Adafruit_GPIO'
I am doing the project in this video (https://www.youtube.com/watch?v=9sb_zuHGmY4) with the OLED screen. The step by step guide I followed (https://www.the-diy-life.com/diy-raspberry-pi-4-desktop-case-with-oled-stats-display/) and I get this error: Traceback (most recent call last): File "stats.py", line 23, in <module> import Adafruit_GPIO.SPI as SPI ModuleNotFoundError: No module named 'Adafruit_GPIO' Code: # Author: Tony DiCola & James DeVito # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import time import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont import subprocess # Raspberry Pi pin configuration: RST = None # on the PiOLED this pin isnt used # Note the following are only used with SPI: DC = 23 SPI_PORT = 0 SPI_DEVICE = 0 # Beaglebone Black pin configuration: # RST = 'P9_12' # Note the following are only used with SPI: # DC = 'P9_15' # SPI_PORT = 1 # SPI_DEVICE = 0 # 128x32 display with hardware I2C: disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) # 128x64 display with hardware I2C: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST) # Note you can change the I2C address by passing an i2c_address parameter like: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) # Alternatively you can specify an explicit I2C bus number, for example # with the 128x32 display you would use: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2) # 128x32 display with hardware SPI: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # 128x64 display with hardware SPI: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # Alternatively you can specify a software SPI implementation by providing # digital GPIO pin numbers for all the required display pins. For example # on a Raspberry Pi with the 128x32 display you might use: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22) # Initialize library. disp.begin() # Clear display. disp.clear() disp.display() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. width = disp.width height = disp.height image = Image.new('1', (width, height)) # Get drawing object to draw on image. draw = ImageDraw.Draw(image) # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) # Draw some shapes. # First define some constants to allow easy resizing of shapes. padding = -2 top = padding bottom = height-padding # Move left to right keeping track of the current x position for drawing shapes. x = 0 # Load default font. font = ImageFont.load_default() # Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script! # Some other nice fonts to try: http://www.dafont.com/bitmap.php # font = ImageFont.truetype('Minecraftia.ttf', 8) while True: # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load cmd = "hostname -I | cut -d\' \' -f1" IP = subprocess.check_output(cmd, shell = True ) cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'" CPU = subprocess.check_output(cmd, shell = True ) cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'" MemUsage = subprocess.check_output(cmd, shell = True ) cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'" Disk = subprocess.check_output(cmd, shell = True ) # Write two lines of text. draw.text((x, top), "IP: " + str(IP), font=font, fill=255) draw.text((x, top+8), str(CPU), font=font, fill=255) draw.text((x, top+16), str(MemUsage), font=font, fill=255) draw.text((x, top+25), str(Disk), font=font, fill=255) # Display image. disp.image(image) disp.display() time.sleep(.1)
[ "When in doubt, take a look at the official docs! You're missing an old library.\nWhile you may be able to bring it in, the maintainers have actually deprecated it and suggest another https://github.com/adafruit/Adafruit_Python_GPIO\n\nThis library has been deprecated in favor of our python3 Blinka library. We have replaced all of the libraries that use this repo with CircuitPython libraries that are Python3 compatible, and support a wide variety of single board/linux computers!\n\nDo take a look at the updated docs from Adafruit: https://learn.adafruit.com/monochrome-oled-breakouts/python-usage-2\nThey have a direct example showing the use of these libraries\nimport board\nimport digitalio\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_ssd1306\n...\n\n", "This is a couple years late, but figured why not post my solution.\nI’ve put together an updated setup.py script that’s adapted to Adafruit’s newer CircuitPython libraries. To note, I’ve tested this on a 4GB RPI4B running Raspbian GNU/Linux 11 armv7.\nBefore attempting to execute this script, make sure to follow the\n'Python Setup' instructions listed here.\n" ]
[ 0, 0 ]
[]
[]
[ "adafruit", "python", "raspberry_pi4" ]
stackoverflow_0065148950_adafruit_python_raspberry_pi4.txt
Q: AssertionError: Label class 15 exceeds nc=1 in data/coco128.yaml. Possible class labels are 0-0 I've been building the yolov5 environment and trying to run it for the last few days. I used the following code to test whether My setup was successful. python train.py --img 640 --data data/coco128.yaml --cfg models/yolov5s.yaml --weights weights/yolov5s.pt --batch-size 16 --epochs 100 And then it gave me the following error, and I tried to find answers on Google, but I didn't see anything useful. I'm devastated right now. Can someone give me a hand? I really appreciate it. Transferred 362/370 items from weights/yolov5s.pt Optimizer groups: 62 .bias, 70 conv.weight, 59 other Scanning labels data\coco128\labels\train2017.cache (32 found, 0 missing, 0 empty, 0 duplicate, for 32 images): 32it [00:00, 3270.57it/s] Traceback (most recent call last): File "train.py", line 456, in <module> train(hyp, opt, device, tb_writer) File "train.py", line 172, in train assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1) AssertionError: Label class 15 exceeds nc=1 in data/coco128.yaml. Possible class labels are 0-0 I really don't use this site. Forgive me. A: I found this exact error too. In your .txt files you've created for the annotations, there will be an integer number followed by four floats (ie, 13 0.3434 0.251 0.4364 0.34353) - something like that. This error essentially articulates that your number of classes (ie, the number of different objects you're trying to train into the model) is too low for the ID number of the classes you're using. In my example above, the ID is 13 (the 14th class since 0 is included). If I set nc=1, then I can only have on class (0). I would need to set nc=14 and ensure that 0-12 existed. To fix this, simply change the classes so that the IDs sit inside your chose number of classes. For nc=1, you'll only need class/ID = 0. As a note (and I fell foul of this), delete train.cache before you re-run the training. That caused me a bit of a nuisance since it still was certain I had classes of >0, when I didn't. A: The error is caused by the fact that you have one or many labels with the number 15 as a class. You have to change the class to an allowed class value (which in your case appears to be only 0), you can do it manually or with a script. I changed the values of the classes manually in my dataset, for finding the files that contained the non-allowed classes, I ran a python script, which I have adapted for your situation: path = 'C:/foo/bar' #path of labels labels = os.listdir('path') for x in labels: with open('path'+x) as f: lines = f.read().splitlines() for y in lines: if y[:1]!='0': print(x) This snippet will print all of the files that contain a class different from 0. For anyone that finds this and has more than one class, you must substitute the value of 0 with the value or values(you could iterate through a list of possible values) of the class or classes that are higher than the number of classes you stated before. A: I also faced this problem and tried few solutions and solved as below: Actually the dataset is consist of 11 class. And when i check .xml files which is include label of image, i saw label:11. So : set nc:12, add '' value to the label array. ['','apple','banana', etc.] Dont forget to remove label chache !rm -f data/train/labels.npy
AssertionError: Label class 15 exceeds nc=1 in data/coco128.yaml. Possible class labels are 0-0
I've been building the yolov5 environment and trying to run it for the last few days. I used the following code to test whether My setup was successful. python train.py --img 640 --data data/coco128.yaml --cfg models/yolov5s.yaml --weights weights/yolov5s.pt --batch-size 16 --epochs 100 And then it gave me the following error, and I tried to find answers on Google, but I didn't see anything useful. I'm devastated right now. Can someone give me a hand? I really appreciate it. Transferred 362/370 items from weights/yolov5s.pt Optimizer groups: 62 .bias, 70 conv.weight, 59 other Scanning labels data\coco128\labels\train2017.cache (32 found, 0 missing, 0 empty, 0 duplicate, for 32 images): 32it [00:00, 3270.57it/s] Traceback (most recent call last): File "train.py", line 456, in <module> train(hyp, opt, device, tb_writer) File "train.py", line 172, in train assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1) AssertionError: Label class 15 exceeds nc=1 in data/coco128.yaml. Possible class labels are 0-0 I really don't use this site. Forgive me.
[ "I found this exact error too.\nIn your .txt files you've created for the annotations, there will be an integer number followed by four floats (ie, 13 0.3434 0.251 0.4364 0.34353) - something like that.\nThis error essentially articulates that your number of classes (ie, the number of different objects you're trying to train into the model) is too low for the ID number of the classes you're using. In my example above, the ID is 13 (the 14th class since 0 is included). If I set nc=1, then I can only have on class (0). I would need to set nc=14 and ensure that 0-12 existed.\nTo fix this, simply change the classes so that the IDs sit inside your chose number of classes. For nc=1, you'll only need class/ID = 0.\nAs a note (and I fell foul of this), delete train.cache before you re-run the training. That caused me a bit of a nuisance since it still was certain I had classes of >0, when I didn't.\n", "The error is caused by the fact that you have one or many labels with the number 15 as a class. You have to change the class to an allowed class value (which in your case appears to be only 0), you can do it manually or with a script. I changed the values of the classes manually in my dataset, for finding the files that contained the non-allowed classes, I ran a python script, which I have adapted for your situation:\npath = 'C:/foo/bar' #path of labels\nlabels = os.listdir('path')\nfor x in labels:\n with open('path'+x) as f:\n lines = f.read().splitlines()\n for y in lines:\n if y[:1]!='0':\n print(x)\n\nThis snippet will print all of the files that contain a class different from 0.\nFor anyone that finds this and has more than one class, you must substitute the value of 0 with the value or values(you could iterate through a list of possible values) of the class or classes that are higher than the number of classes you stated before.\n", "I also faced this problem and tried few solutions and solved as below:\nActually the dataset is consist of 11 class. And when i check .xml files which is include label of image, i saw label:11. So :\n\nset nc:12,\nadd '' value to the label array. ['','apple','banana', etc.]\n\nDont forget to remove label chache !rm -f data/train/labels.npy\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "yolov5" ]
stackoverflow_0063950508_python_yolov5.txt
Q: Django REST Framework - return a value from get_queryset? I am trying to return a value from get_queryset. def get_queryset(self): if self.request.user.is_superuser: return StockPriceModel.objects.order_by('ticker').distinct() elif not self.request.user.is_authenticated: print('in') print(self.request.data) last_price = StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time')[0].last_price print(last_price) return last_price last price gets printed without an issue. In return I get various errors: TypeError at /api/stock-prices-upload/ 'float' object is not iterable If I try to return till: StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time') It works. As soon as I try to return just the 0 position queryset I get errors. I assume this is because get_queryset is supposed to return a queryset. Not sure how to return just the value. Edit: I am now trying to get only the latest row i.e. [0] form the data but still getting the same errors i.e. StockPriceModel object is not iterable # The current output if I don't add the [0] i.e. try to get the last row of data [{"id":23,"last_price":"395.2","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":null,"last_date_time":"2022-10-20T15:58:26+04:00","created_at":"2022-10-20T23:20:37.499166+04:00"},{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}] Expected response: [{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}] I have tried using last, get etc. Just won't work. A: Because, get_queryset() always return a queryset of objects or a list of objects. You cannot return an object or a field from the get_queryset method. the last_price value will be printed, but it is a field value and therefore the get_queryset method will not return it. When you add [0], it takes the first object from the filtered queryset. Till that point, it is a queryset of objects. A: A bit hacky and I am sure there must be a better way to do this. I wanted to get return of either a single row(last_date_time) based or the last_price value. I wrapped the query: # removed the .last_price last_price = StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time')[0] last_price = [last_price] # made it into a list, i.e. iterable return last_price And now I can get the last row. Posting here incase someone spends the same number of hours trying to figure this out. If you have the correct way of doing this, please post.
Django REST Framework - return a value from get_queryset?
I am trying to return a value from get_queryset. def get_queryset(self): if self.request.user.is_superuser: return StockPriceModel.objects.order_by('ticker').distinct() elif not self.request.user.is_authenticated: print('in') print(self.request.data) last_price = StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time')[0].last_price print(last_price) return last_price last price gets printed without an issue. In return I get various errors: TypeError at /api/stock-prices-upload/ 'float' object is not iterable If I try to return till: StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time') It works. As soon as I try to return just the 0 position queryset I get errors. I assume this is because get_queryset is supposed to return a queryset. Not sure how to return just the value. Edit: I am now trying to get only the latest row i.e. [0] form the data but still getting the same errors i.e. StockPriceModel object is not iterable # The current output if I don't add the [0] i.e. try to get the last row of data [{"id":23,"last_price":"395.2","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":null,"last_date_time":"2022-10-20T15:58:26+04:00","created_at":"2022-10-20T23:20:37.499166+04:00"},{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}] Expected response: [{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}] I have tried using last, get etc. Just won't work.
[ "Because, get_queryset() always return a queryset of objects or a list of objects.\nYou cannot return an object or a field from the get_queryset method.\nthe last_price value will be printed, but it is a field value and therefore the get_queryset method will not return it.\nWhen you add [0], it takes the first object from the filtered queryset. Till that point, it is a queryset of objects.\n", "A bit hacky and I am sure there must be a better way to do this.\nI wanted to get return of either a single row(last_date_time) based or the last_price value.\nI wrapped the query:\n# removed the .last_price\nlast_price = StockPriceModel.objects.all().filter(\n ticker=self.request.data['ticker']).order_by('-last_date_time')[0]\nlast_price = [last_price] # made it into a list, i.e. iterable\nreturn last_price\n\nAnd now I can get the last row.\nPosting here incase someone spends the same number of hours trying to figure this out. If you have the correct way of doing this, please post.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074657136_django_python.txt
Q: Getting field from another model into my custom serializer I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information: This is the serializers.py file: enter image description here This is the models.py file (from django-friendship model): enter image description here I am also attaching views.py: enter image description here A: In this case I would make a serializer for the user and then use that in the FriendshipRequestSerializer. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name',) class FriendshipRequestSerialiser(serializers.ModelSerializer): to_user = UserSerializer(many=False) from_user = UserSerializer(many=False) class Meta: model = FriendshipRequest fields = ('id', 'to_user', 'from_user', 'message', ... extra_kwargs = ...
Getting field from another model into my custom serializer
I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information: This is the serializers.py file: enter image description here This is the models.py file (from django-friendship model): enter image description here I am also attaching views.py: enter image description here
[ "In this case I would make a serializer for the user and then use that in the FriendshipRequestSerializer.\nclass UserSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = User\n fields = ('id', 'first_name', 'last_name',)\n\n\nclass FriendshipRequestSerialiser(serializers.ModelSerializer):\n to_user = UserSerializer(many=False)\n from_user = UserSerializer(many=False)\n\n class Meta:\n model = FriendshipRequest\n fields = ('id', 'to_user', 'from_user', 'message', ...\n extra_kwargs = ...\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074671836_django_django_rest_framework_python.txt
Q: how to condition a url depending on the parameters in flask? I currently have my site like this: @main.route("/reports", methods=["GET", "POST"]) def reports(): return render_template( "template.html") I intend to add a new design and place it in the following way if in the url they add "/reports/1" or "/reports/0" direct them to a different template: @main.route("/reports/<int:ds>", methods=["GET", "POST"]) def reports(ds): View=ds if View == 1: return render_template("template.html") if View == 0: return render_template("templateNew.html") Within templeteNew.html I have the option to return to my old layout and place it in the same way by sending a parameter <a href="{{ url_for('main.report_in', ds=1) }}" > Return to previous layout </a> The problem is that in the whole project and in external projects it refers to this url: 127.0.0.1:8000/reportes and it might cause errors if I implement it the way I intended. What I want is that if there is any other way to condition the url, if they write this url: http://127.0.0.1:8000/reportes I directed them to this: @main.route("/reports/<int:ds>", methods=["GET", "POST"]) def reports(ds): View=ds if View == 1: return render_template( "template.html") if View == 0: return render_template( "templateNew.html") Any suggestions to improve this please? A: http://127.0.0.1:8000/reportes looks like a typo (extra "e"). Anyway you can add one more route to your function as follows: @main.route("/reports", methods=["GET", "POST"]) @main.route("/reports/<int:ds>", methods=["GET", "POST"]) def reports(ds=1): # <-- provide here the default value you want ds to be View=ds if View == 1: return render_template( "template.html") if View == 0: return render_template( "templateNew.html") Another option is to pass the default value in the route definition: @main.route("/reports", methods=["GET", "POST"], defaults={'ds': 1}) @main.route("/reports/<int:ds>", methods=["GET", "POST"]) def reports(ds): to be View=ds if View == 1: return render_template( "template.html") if View == 0: return render_template( "templateNew.html")
how to condition a url depending on the parameters in flask?
I currently have my site like this: @main.route("/reports", methods=["GET", "POST"]) def reports(): return render_template( "template.html") I intend to add a new design and place it in the following way if in the url they add "/reports/1" or "/reports/0" direct them to a different template: @main.route("/reports/<int:ds>", methods=["GET", "POST"]) def reports(ds): View=ds if View == 1: return render_template("template.html") if View == 0: return render_template("templateNew.html") Within templeteNew.html I have the option to return to my old layout and place it in the same way by sending a parameter <a href="{{ url_for('main.report_in', ds=1) }}" > Return to previous layout </a> The problem is that in the whole project and in external projects it refers to this url: 127.0.0.1:8000/reportes and it might cause errors if I implement it the way I intended. What I want is that if there is any other way to condition the url, if they write this url: http://127.0.0.1:8000/reportes I directed them to this: @main.route("/reports/<int:ds>", methods=["GET", "POST"]) def reports(ds): View=ds if View == 1: return render_template( "template.html") if View == 0: return render_template( "templateNew.html") Any suggestions to improve this please?
[ "http://127.0.0.1:8000/reportes looks like a typo (extra \"e\").\nAnyway you can add one more route to your function as follows:\[email protected](\"/reports\", methods=[\"GET\", \"POST\"])\[email protected](\"/reports/<int:ds>\", methods=[\"GET\", \"POST\"])\ndef reports(ds=1): # <-- provide here the default value you want ds to be\n View=ds\nif View == 1:\n return render_template(\n \"template.html\")\nif View == 0:\n return render_template(\n \"templateNew.html\")\n\nAnother option is to pass the default value in the route definition:\[email protected](\"/reports\", methods=[\"GET\", \"POST\"], defaults={'ds': 1})\[email protected](\"/reports/<int:ds>\", methods=[\"GET\", \"POST\"])\ndef reports(ds): to be\n View=ds\nif View == 1:\n return render_template(\n \"template.html\")\nif View == 0:\n return render_template(\n \"templateNew.html\")\n\n" ]
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074670576_flask_python.txt
Q: Copy cells based on cell value I have a spreadseet with quite a few refrences (lookups and links to data I extract from system) In cell B1 I have how many actually rows with data I have. i.e The sheet is called Raw Data and if B1=100 I need range B2:E102 copied into sheet Master The value in B1 is dynamic, depending on data in another sheet). Could someone please help me with this? Thanks A: Copy a Range Option Explicit Sub CopyRange() ' Reference the workbook. Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code ' Reference the Source range. Dim sws As Worksheet: Set sws = wb.Sheets("Raw Data") Dim slRow As Long: slRow = sws.Range("B1").Value + 2 Dim srg As Range: Set srg = sws.Range("B2", sws.Cells(slRow, "E")) ' Reference the first Destination cell. Dim dws As Worksheet: Set dws = wb.Sheets("Master") Dim dfCell As Range: Set dfCell = dws.Range("A1") ' adjust!? ' Either copy values, formulas and formats,... srg.Copy dfCell ' or copy only values (more efficient): 'dfCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value ' Inform. MsgBox "Range copied.", vbInformation End Sub A: I like to create a hard coded starting point for the Range. Then from there step into getting the last column then the last row. Something like this... Sub Main() strFile = "C:\Users\raw_data.xlsm" 'change this to your file name Workbooks.Open (strFile) 'Debug.Print strFile 'log the last column for paramters LastColumn = ActiveSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 'log the last rows for components LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row Dim WorksheetStartCell As String StartCellNum = 2 WorksheetHeadingStartCell = "A" & StartCellNum WorksheetValueStartCell = "A" & StartCellNum + 1 'Debug.Print "Worksheet Heading Start Cell: " & WorksheetHeadingStartCell 'Debug.Print "Worksheet Value Start Cell: " & WorksheetValueStartCell WorksheetHeadingEndCell = "G" & StartCellNum WorksheetValueEndCell = "G" & LastRow End Sub That will dynamically give you everything aside from it finding the very first cell of the range, which is easy enough but like you said you had it hard coded to "B2" so I thought it was relevant. Once you have the range that you actually want like written above, you can easily just copy and paste the range to that sheet. I assumed you needed more help with the dynamic range than the copying and pasting of the range, if that was not the case, I can reply again to that concern. I have not replied to many answers on here so sorry if I was not much help. I did try my best to address your concerns. I truly wish this helps you.
Copy cells based on cell value
I have a spreadseet with quite a few refrences (lookups and links to data I extract from system) In cell B1 I have how many actually rows with data I have. i.e The sheet is called Raw Data and if B1=100 I need range B2:E102 copied into sheet Master The value in B1 is dynamic, depending on data in another sheet). Could someone please help me with this? Thanks
[ "Copy a Range\nOption Explicit\n\nSub CopyRange()\n \n ' Reference the workbook.\n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n ' Reference the Source range.\n Dim sws As Worksheet: Set sws = wb.Sheets(\"Raw Data\")\n Dim slRow As Long: slRow = sws.Range(\"B1\").Value + 2\n Dim srg As Range: Set srg = sws.Range(\"B2\", sws.Cells(slRow, \"E\"))\n \n ' Reference the first Destination cell.\n Dim dws As Worksheet: Set dws = wb.Sheets(\"Master\")\n Dim dfCell As Range: Set dfCell = dws.Range(\"A1\") ' adjust!?\n \n ' Either copy values, formulas and formats,...\n srg.Copy dfCell\n ' or copy only values (more efficient):\n 'dfCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value\n \n ' Inform.\n MsgBox \"Range copied.\", vbInformation\n \nEnd Sub\n\n", "I like to create a hard coded starting point for the Range.\nThen from there step into getting the last column then the last row.\nSomething like this...\nSub Main()\nstrFile = \"C:\\Users\\raw_data.xlsm\" 'change this to your file name\nWorkbooks.Open (strFile)\n'Debug.Print strFile\n\n'log the last column for paramters\nLastColumn = ActiveSheet.Cells.Find(\"*\", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column\n\n'log the last rows for components\nLastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, \"A\").End(xlUp).Row\n\nDim WorksheetStartCell As String\n\nStartCellNum = 2\n\nWorksheetHeadingStartCell = \"A\" & StartCellNum\nWorksheetValueStartCell = \"A\" & StartCellNum + 1\n\n'Debug.Print \"Worksheet Heading Start Cell: \" & WorksheetHeadingStartCell\n'Debug.Print \"Worksheet Value Start Cell: \" & WorksheetValueStartCell\n\nWorksheetHeadingEndCell = \"G\" & StartCellNum\nWorksheetValueEndCell = \"G\" & LastRow\n\nEnd Sub\nThat will dynamically give you everything aside from it finding the very first cell of the range, which is easy enough but like you said you had it hard coded to \"B2\" so I thought it was relevant. Once you have the range that you actually want like written above, you can easily just copy and paste the range to that sheet. I assumed you needed more help with the dynamic range than the copying and pasting of the range, if that was not the case, I can reply again to that concern. I have not replied to many answers on here so sorry if I was not much help. I did try my best to address your concerns. I truly wish this helps you.\n" ]
[ 1, 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074671168_excel_vba.txt
Q: Use a scss class from a file in another scss file I have a day/night theme button that changes the main body color in App.scss in my React project. It's simple, it uses body.light and body.dark, but I also need to change some text in my navigation bar, which is in a different folder with Navbar.jsx and Navbar.scss. Because of how the button is made, I can only change App.scss, so how can I export/add the class from Navbar.scss (which is .site-nav) into my App.scss so i can add .site-nav.dark / .site-nav.light for it to work? I tried renaming it to _Navbar.scss, adding @mixin: @mixin nav { //code .site-nav { //code } } and I tried adding this to my App.scss: @use './Navbar/Navbar.scss' as Navi; body.dark { color: #a58c6f; background-color: #1c221f; @include Navi.site-nav; } but I get Invalid CSS after " @include Navi": expected "}", was ".site-nav;"Any help? A: if you are importing Navbar.scss with @use you don't need to @include, all classes inside Navbar will be available in into your App.scss. You can define the light and dark class into your App.scss or into Navbar.scss. @import also work to import sass files into other sass file. @use 'Navbar/Navbar'; .nav { .light { //...} .dark { //...} } or @import 'Navbar/Navbar'; .nav { .light { //...} .dark { //...} }
Use a scss class from a file in another scss file
I have a day/night theme button that changes the main body color in App.scss in my React project. It's simple, it uses body.light and body.dark, but I also need to change some text in my navigation bar, which is in a different folder with Navbar.jsx and Navbar.scss. Because of how the button is made, I can only change App.scss, so how can I export/add the class from Navbar.scss (which is .site-nav) into my App.scss so i can add .site-nav.dark / .site-nav.light for it to work? I tried renaming it to _Navbar.scss, adding @mixin: @mixin nav { //code .site-nav { //code } } and I tried adding this to my App.scss: @use './Navbar/Navbar.scss' as Navi; body.dark { color: #a58c6f; background-color: #1c221f; @include Navi.site-nav; } but I get Invalid CSS after " @include Navi": expected "}", was ".site-nav;"Any help?
[ "if you are importing Navbar.scss with @use you don't need to @include, all classes inside Navbar will be available in into your App.scss. You can define the light and dark class into your App.scss or into Navbar.scss. @import also work to import sass files into other sass file.\n@use 'Navbar/Navbar';\n.nav {\n .light { //...}\n .dark { //...}\n}\n\nor\n@import 'Navbar/Navbar';\n.nav {\n .light { //...}\n .dark { //...}\n}\n\n" ]
[ 0 ]
[]
[]
[ "css", "reactjs", "sass" ]
stackoverflow_0074671826_css_reactjs_sass.txt
Q: Get tomcat status with telegraf Is there a simple and efficient way to get the status of a tomcat server with telegraf? I already tried jolokia-agent over jmx with the "Uptime" property but the problem is when i stop my tomcat server i still get values for "Uptime". A: Yeah, you can use the telegraf jolokia2 input plugin to monitor your Tomcat server. This plugin allows you to query the Jolokia API, which provides a way to access JMX MBeans remotely. To get the status of your Tomcat server, you can query the Catalina:type=Server MBean and retrieve the stateName attribute. This attribute will have a value of STARTED when the server is running, and STOPPED when it is not. Here is an example configuration for the jolokia2 input plugin that you can use to monitor the status of your Tomcat server: [[inputs.jolokia2]] ## A list of URLs of Jolokia instances to poll. ## These URLs must use the http or https scheme. urls = ["http://localhost:8080/jolokia"] ## Timeout for HTTP requests. timeout = "5s" ## Optional TLS Config # tls_ca = "/etc/telegraf/ca.pem" # tls_cert = "/etc/telegraf/cert.pem" # tls_key = "/etc/telegraf/key.pem" ## Use TLS but skip chain & host verification # insecure_skip_verify = false ## HTTP Method # method = "POST" ## Optional basic HTTP authentication # username = "telegraf" # password = "mypassword" ## Optional HTTP headers # headers = {"X-Custom-Header" = "Value"} ## List of MBean names to gather metrics from. ## Wildcards can be used to match multiple MBeans. mbeans = [ "Catalina:type=Server:stateName" ] ## Optional list of JMX attribute name prefixes to exclude from the ## resulting metric names. # exclude_attribute_prefixes = ["java.lang"] ## Optional JMX property to extract value from. # value_property = "value" ## Optional JMX property to extract timestamp from. # timestamp_property = "timestamp"
Get tomcat status with telegraf
Is there a simple and efficient way to get the status of a tomcat server with telegraf? I already tried jolokia-agent over jmx with the "Uptime" property but the problem is when i stop my tomcat server i still get values for "Uptime".
[ "Yeah, you can use the telegraf jolokia2 input plugin to monitor your Tomcat server. This plugin allows you to query the Jolokia API, which provides a way to access JMX MBeans remotely. To get the status of your Tomcat server, you can query the Catalina:type=Server MBean and retrieve the stateName attribute. This attribute will have a value of STARTED when the server is running, and STOPPED when it is not.\nHere is an example configuration for the jolokia2 input plugin that you can use to monitor the status of your Tomcat server:\n[[inputs.jolokia2]]\n ## A list of URLs of Jolokia instances to poll.\n ## These URLs must use the http or https scheme.\n urls = [\"http://localhost:8080/jolokia\"]\n\n ## Timeout for HTTP requests.\n timeout = \"5s\"\n\n ## Optional TLS Config\n # tls_ca = \"/etc/telegraf/ca.pem\"\n # tls_cert = \"/etc/telegraf/cert.pem\"\n # tls_key = \"/etc/telegraf/key.pem\"\n ## Use TLS but skip chain & host verification\n # insecure_skip_verify = false\n\n ## HTTP Method\n # method = \"POST\"\n\n ## Optional basic HTTP authentication\n # username = \"telegraf\"\n # password = \"mypassword\"\n\n ## Optional HTTP headers\n # headers = {\"X-Custom-Header\" = \"Value\"}\n\n ## List of MBean names to gather metrics from.\n ## Wildcards can be used to match multiple MBeans.\n mbeans = [\n \"Catalina:type=Server:stateName\"\n ]\n\n ## Optional list of JMX attribute name prefixes to exclude from the\n ## resulting metric names.\n # exclude_attribute_prefixes = [\"java.lang\"]\n\n ## Optional JMX property to extract value from.\n # value_property = \"value\"\n\n ## Optional JMX property to extract timestamp from.\n # timestamp_property = \"timestamp\"\n\n\n" ]
[ 1 ]
[]
[]
[ "monitoring", "telegraf", "telegraf_plugins", "tomcat9" ]
stackoverflow_0074671904_monitoring_telegraf_telegraf_plugins_tomcat9.txt
Q: The tkinter window of my rotating cube animation does not showing anyting from tkinter import * from math import * import time root = Tk() canvas = Canvas(root, width=500, height=500, bg='black') canvas.pack() class Cube: def __init__(self, canvas, x, y, size, colors): self.x = x self.y = y self.size = size self.colors = colors self.canvas = canvas self.angleX, self.angleY = 0, 0 self.update() def project(self, x, y, z): return self.x + (x * self.size) / (z + self.size), self.y + (y * self.size) / (z + self.size) def update(self): points = [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]] t = [[0, 1, 2, 3], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], [4, 7, 6, 5]] self.polygons = [] for point in points: x, y = self.project(point[0], point[1], point[2]) points[points.index(point)] = [x, y] for triangle in t: p1 = points[triangle[0]] p2 = points[triangle[1]] p3 = points[triangle[2]] p4 = points[triangle[3]] self.polygons.append([p1, p2, p3, p4]) def rotateX(self, angle): self.angleX += angle for point in [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]: y = point[1] z = point[2] point[1] = y * cos(angle) - z * sin(angle) point[2] = z * cos(angle) + y * sin(angle) self.update() def rotateY(self, angle): self.angleY += angle for point in [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]: x = point[0] z = point[2] point[0] = x * cos(angle) - z * sin(angle) point[2] = z * cos(angle) + x * sin(angle) self.update() def draw(self): for polygon in self.polygons: self.canvas.create_polygon(polygon, fill=self.colors[self.polygons.index(polygon)], outline='black') colors = ["red", "green", "blue", "white", "yellow", "purple"] cube = Cube(canvas, 250, 250, 200, colors) while True: cube.rotateY(0.01) cube.rotateX(0.01) canvas.delete("all") cube.draw() root.update() time.sleep(0.01) root.mainloop() I don't get an errror but somehow the tkinter window stays black. The program was written by gpt3 and I also tryed to let gpt3 fix the code by itself but it wasn't able to. I wasn't able to find the reason for the black screen jet but I asume that it is caused by the root.mainloop() function not to execute propperly. If this was the reason I would still not be able to fix it so here I am. I hope for your help. Philipp
The tkinter window of my rotating cube animation does not showing anyting
from tkinter import * from math import * import time root = Tk() canvas = Canvas(root, width=500, height=500, bg='black') canvas.pack() class Cube: def __init__(self, canvas, x, y, size, colors): self.x = x self.y = y self.size = size self.colors = colors self.canvas = canvas self.angleX, self.angleY = 0, 0 self.update() def project(self, x, y, z): return self.x + (x * self.size) / (z + self.size), self.y + (y * self.size) / (z + self.size) def update(self): points = [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]] t = [[0, 1, 2, 3], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], [4, 7, 6, 5]] self.polygons = [] for point in points: x, y = self.project(point[0], point[1], point[2]) points[points.index(point)] = [x, y] for triangle in t: p1 = points[triangle[0]] p2 = points[triangle[1]] p3 = points[triangle[2]] p4 = points[triangle[3]] self.polygons.append([p1, p2, p3, p4]) def rotateX(self, angle): self.angleX += angle for point in [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]: y = point[1] z = point[2] point[1] = y * cos(angle) - z * sin(angle) point[2] = z * cos(angle) + y * sin(angle) self.update() def rotateY(self, angle): self.angleY += angle for point in [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]: x = point[0] z = point[2] point[0] = x * cos(angle) - z * sin(angle) point[2] = z * cos(angle) + x * sin(angle) self.update() def draw(self): for polygon in self.polygons: self.canvas.create_polygon(polygon, fill=self.colors[self.polygons.index(polygon)], outline='black') colors = ["red", "green", "blue", "white", "yellow", "purple"] cube = Cube(canvas, 250, 250, 200, colors) while True: cube.rotateY(0.01) cube.rotateX(0.01) canvas.delete("all") cube.draw() root.update() time.sleep(0.01) root.mainloop() I don't get an errror but somehow the tkinter window stays black. The program was written by gpt3 and I also tryed to let gpt3 fix the code by itself but it wasn't able to. I wasn't able to find the reason for the black screen jet but I asume that it is caused by the root.mainloop() function not to execute propperly. If this was the reason I would still not be able to fix it so here I am. I hope for your help. Philipp
[]
[]
[ "I don't think your looop works like you expect it to\nYou never exit the while loop to start the main loop.\ninstead you might wanna try something like this:\ndef update_cube():\n cube.rotate_y(0.01)\n cube.rotate_x(0.01)\n canvas.delete(\"all\")\n cube.draw()\n root.update()\n root.after(10, update_cube())\n\nroot.after(0, update_cube())\nroot.mainloop()\n\nAnd I think there is someting wrong with your poligons in your draw method.\nThe attribute is supposed to hold tupples but you have multiple lists of values.\nCheck your self.polygons and make sure the values you put in the create_polygon method are correct. Depending on your IDE, if you tell self.canvas to be a Canvas, you might get some information about the argument error. At least in PyCharm this works.\ndef draw(self):\n for polygon in self.polygons:\n self.canvas: Canvas\n self.canvas.create_polygon(polygon, fill=self.colors[self.polygons.index(polygon)], outline='black')\n\n" ]
[ -1 ]
[ "python", "tkinter" ]
stackoverflow_0074671737_python_tkinter.txt
Q: RTK Query and Laravel Sanctum: CSRF Token Mismatch (Request has cookie) I'm implementing a Laravel API + React SPA with Sanctum authentication. With Sanctum, before requesting the actual login route, you need to send a request to /sanctum/csrf-cookie 'to initialize csrf protection'. Currently I have this RTK Query api: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; import { API_HOST } from "./config"; export const authApi = createApi({ reducerPath: "authApi", baseQuery: fetchBaseQuery({ baseUrl: `${API_HOST}`, }), endpoints: (builder) => ({ initCsrf: builder.mutation<void, void>({ query() { return { url: "sanctum/csrf-cookie", credentials: "include", headers: { "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", Accept: "application/json", }, }; }, }), loginUser: builder.mutation<{ access_token: string; status: string }, { username: string; password: string }>({ query(data) { return { url: "login", method: "POST", body: data, credentials: "include", headers: { "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", Accept: "application/json", }, }; }, async onQueryStarted(args, { dispatch, queryFulfilled }) { try { await queryFulfilled; } catch (err) { console.error(err); } }, }), logoutUser: builder.mutation<void, void>({ query() { return { url: "logout", credentials: "include", }; }, }), }), }); export const { useLoginUserMutation, useLogoutUserMutation, useInitCsrfMutation } = authApi; Then in my login page, when the user clicks the login button, I call: const onSubmitHandler: SubmitHandler<LoginInput> = (values) => { initCsrf() .then(() => { loginUser(values); }) .catch((err) => { console.error(err); }); }; The first request is working and sets the cookie but the second returns with a 419 CSRF Token mismatch exception. Examining the requests, the login request contains the XSRF-TOKEN cookie with the token that I got in the first request so it should work ok. This worked before with Axios using the same structure (first request to establish the cookie and the second including the cookie). A: You are sending the CSRF token as a cookie, but Laravel expects it to be sent as a X-XSRF-TOKEN header. Update your loginUser endpoint to include the token in the headers instead of sending it as a cookie: loginUser: builder.mutation<{ access_token: string; status: string }, { username: string; password: string }>({ query(data) { return { url: "login", method: "POST", body: data, headers: { "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", Accept: "application/json", "X-XSRF-TOKEN": document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1], // add this line }, }; }, async onQueryStarted(args, { dispatch, queryFulfilled }) { try { await queryFulfilled; } catch (err) { console.error(err); } }, }), extract the value of the XSRF-TOKEN cookie from the document.cookie string and include it in the headers of the loginUser request. A: I just found out that axios decodes the xsrf-token and rtk query does not. The token includes a = sign at the end which is encoded to %3D. Now I just had to decode the token with decodeURIComponent after reading it from the document and it did the trick. Source: https://github.com/laravel/framework/discussions/42729#discussioncomment-2939906
RTK Query and Laravel Sanctum: CSRF Token Mismatch (Request has cookie)
I'm implementing a Laravel API + React SPA with Sanctum authentication. With Sanctum, before requesting the actual login route, you need to send a request to /sanctum/csrf-cookie 'to initialize csrf protection'. Currently I have this RTK Query api: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; import { API_HOST } from "./config"; export const authApi = createApi({ reducerPath: "authApi", baseQuery: fetchBaseQuery({ baseUrl: `${API_HOST}`, }), endpoints: (builder) => ({ initCsrf: builder.mutation<void, void>({ query() { return { url: "sanctum/csrf-cookie", credentials: "include", headers: { "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", Accept: "application/json", }, }; }, }), loginUser: builder.mutation<{ access_token: string; status: string }, { username: string; password: string }>({ query(data) { return { url: "login", method: "POST", body: data, credentials: "include", headers: { "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", Accept: "application/json", }, }; }, async onQueryStarted(args, { dispatch, queryFulfilled }) { try { await queryFulfilled; } catch (err) { console.error(err); } }, }), logoutUser: builder.mutation<void, void>({ query() { return { url: "logout", credentials: "include", }; }, }), }), }); export const { useLoginUserMutation, useLogoutUserMutation, useInitCsrfMutation } = authApi; Then in my login page, when the user clicks the login button, I call: const onSubmitHandler: SubmitHandler<LoginInput> = (values) => { initCsrf() .then(() => { loginUser(values); }) .catch((err) => { console.error(err); }); }; The first request is working and sets the cookie but the second returns with a 419 CSRF Token mismatch exception. Examining the requests, the login request contains the XSRF-TOKEN cookie with the token that I got in the first request so it should work ok. This worked before with Axios using the same structure (first request to establish the cookie and the second including the cookie).
[ "You are sending the CSRF token as a cookie, but Laravel expects it to be sent as a X-XSRF-TOKEN header.\nUpdate your loginUser endpoint to include the token in the headers instead of sending it as a cookie:\nloginUser: builder.mutation<{ access_token: string; status: string }, { username: string; password: string }>({\n query(data) {\n return {\n url: \"login\",\n method: \"POST\",\n body: data,\n headers: {\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-XSRF-TOKEN\": document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1], // add this line\n },\n };\n },\n async onQueryStarted(args, { dispatch, queryFulfilled }) {\n try {\n await queryFulfilled;\n } catch (err) {\n console.error(err);\n }\n },\n }),\n\nextract the value of the XSRF-TOKEN cookie from the document.cookie string and include it in the headers of the loginUser request.\n", "I just found out that axios decodes the xsrf-token and rtk query does not. The token includes a = sign at the end which is encoded to %3D.\nNow I just had to decode the token with decodeURIComponent after reading it from the document and it did the trick.\nSource: https://github.com/laravel/framework/discussions/42729#discussioncomment-2939906\n" ]
[ 1, 0 ]
[]
[]
[ "laravel", "laravel_sanctum", "reactjs", "rtk_query" ]
stackoverflow_0074669902_laravel_laravel_sanctum_reactjs_rtk_query.txt
Q: Can anyone see the mistake in the SQL Command i am using to update a record in a local DB using JDBC? I am trying to update a DB Table at my college using JDBC and JAVAFx. I have tried everything to get the SQL Update command to work. I have a table where the player_id is the foreign key from the table - Player -, and is a child table to its parent namely - Player and Game Information -. I have set up the schema correctly for both tables as per instructions and am trying to update a record in the 'Player' table based off player_id since it is the foreign key for the 'Player'. I understand this is very rudimentary as a command and have researched 'preparedstatements' in Java, but i was asked to do it this way. The codebelow basically collects a player_id via an input dialogue for which the record is being updated and all the columns are nullable except for the player_id. The code i have is as follows : dbConnect(); JFrame frame; frame = new JFrame(); int searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, "Please enter the ID of the Player you would like to update")); String sql = "UPDATE player SET" +" first_name= '" + first_name + "'," + " last_name= '" + last_name + "'," + " address= '" + address + "'," + " postal_code= '" + postal_code + "'," + " province= '" + province + "'," + " phone_number= '" + phone_number + "'" + " WHERE player_id =" + searchP_id + ";" ; statement.executeUpdate(sql); if (statement != null) { //Close Statement statement.close(); } I tried verifying that i have the command right as per sql statements and when i run this within sqlDeveloper - it updates the record. I have a controller class that basically runs these commands as part of a method that runs during an actionevent onUpdatePlayerButtonClick. I tried checking he syntax and cannot see the problem, but the only error i get whenever running this line is - << Caused by: Error : 933, Position : 128, Sql = UPDATE player SET first_name= '', last_name= '', address= '', postal_code= '', province= '', phone_number= '' WHERE player_id =1;, OriginalSql = UPDATE player SET first_name= '', last_name= '', address= '', postal_code= '', province= '', phone_number= '' WHERE player_id =1;, Error Msg = ORA-00933: SQL command not properly ended >>. I tried reasearching the error code online and it said that there is a clause added that shouldnot be there and might be casuing the problem - this is a simple UPDATE query so where could it be going wrong ? The DB is getting connected to fine and the Insert command i have within my utility class works too. Thank you for any help provided ! A: It looks like you have an extra comma after the SET clause in your UPDATE query. This is causing the ORA-00933 error because the SQL parser is expecting another field to be updated after the comma. To fix this, you can simply remove the extra comma at the end of the SET clause like this: String sql = "UPDATE player SET" + " first_name= '" + first_name + "'," + " last_name= '" + last_name + "'," + " address= '" + address + "'," + " postal_code= '" + postal_code + "'," + " province= '" + province + "'," + " phone_number= '" + phone_number + "'" + " WHERE player_id =" + searchP_id + ";"; It is also a good idea to use a PreparedStatement instead of concatenating the values into the query string like this. This will help prevent SQL injection attacks and make your code more efficient. Here is an example of how you can use a PreparedStatement to update the player record: // Create the UPDATE query with placeholders for the values String sql = "UPDATE player SET" + " first_name= ?," + " last_name= ?," + " address= ?," + " postal_code= ?," + " province= ?," + " phone_number= ?" + " WHERE player_id = ?"; // Create a PreparedStatement object PreparedStatement pstmt = connection.prepareStatement(sql); // Set the values for the placeholders in the query pstmt.setString(1, first_name); pstmt.setString(2, last_name); pstmt.setString(3, address); pstmt.setString(4, postal_code); pstmt.setString(5, province); pstmt.setString(6, phone_number); pstmt.setInt(7, searchP_id); // Execute the UPDATE query pstmt.executeUpdate(); // Close the PreparedStatement pstmt.close(); A: Your query is not readable and you should use parameters in your JDBC statement. dbConnect(); JFrame frame; frame = new JFrame(); int searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, "Please enter the ID of the Player you would like to update")); String sql = "UPDATE player" + " SET first_name = ?, last_name = ?, address = ?," + " postal_code = ?, province = ?, phone_number = ?" + " WHERE player_id = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "the_first_name"); preparedStatement.setString(2, "the_last_name"); preparedStatement.setString(3, "the_address"); preparedStatement.setString(4, "the_postal_code"); preparedStatement.setString(5, "the_province"); preparedStatement.setString(6, "the_phone_number"); preparedStatement.setLong(7, "the_player_id"); preparedStatement.executeUpdate(sql); if (preparedStatement != null) { //Close Statement preparedStatement.close(); } Take look here for more details on parameters with JDBC.
Can anyone see the mistake in the SQL Command i am using to update a record in a local DB using JDBC?
I am trying to update a DB Table at my college using JDBC and JAVAFx. I have tried everything to get the SQL Update command to work. I have a table where the player_id is the foreign key from the table - Player -, and is a child table to its parent namely - Player and Game Information -. I have set up the schema correctly for both tables as per instructions and am trying to update a record in the 'Player' table based off player_id since it is the foreign key for the 'Player'. I understand this is very rudimentary as a command and have researched 'preparedstatements' in Java, but i was asked to do it this way. The codebelow basically collects a player_id via an input dialogue for which the record is being updated and all the columns are nullable except for the player_id. The code i have is as follows : dbConnect(); JFrame frame; frame = new JFrame(); int searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, "Please enter the ID of the Player you would like to update")); String sql = "UPDATE player SET" +" first_name= '" + first_name + "'," + " last_name= '" + last_name + "'," + " address= '" + address + "'," + " postal_code= '" + postal_code + "'," + " province= '" + province + "'," + " phone_number= '" + phone_number + "'" + " WHERE player_id =" + searchP_id + ";" ; statement.executeUpdate(sql); if (statement != null) { //Close Statement statement.close(); } I tried verifying that i have the command right as per sql statements and when i run this within sqlDeveloper - it updates the record. I have a controller class that basically runs these commands as part of a method that runs during an actionevent onUpdatePlayerButtonClick. I tried checking he syntax and cannot see the problem, but the only error i get whenever running this line is - << Caused by: Error : 933, Position : 128, Sql = UPDATE player SET first_name= '', last_name= '', address= '', postal_code= '', province= '', phone_number= '' WHERE player_id =1;, OriginalSql = UPDATE player SET first_name= '', last_name= '', address= '', postal_code= '', province= '', phone_number= '' WHERE player_id =1;, Error Msg = ORA-00933: SQL command not properly ended >>. I tried reasearching the error code online and it said that there is a clause added that shouldnot be there and might be casuing the problem - this is a simple UPDATE query so where could it be going wrong ? The DB is getting connected to fine and the Insert command i have within my utility class works too. Thank you for any help provided !
[ "It looks like you have an extra comma after the SET clause in your UPDATE query. This is causing the ORA-00933 error because the SQL parser is expecting another field to be updated after the comma.\nTo fix this, you can simply remove the extra comma at the end of the SET clause like this:\nString sql = \"UPDATE player SET\" +\n\" first_name= '\" + first_name + \"',\" +\n\" last_name= '\" + last_name + \"',\" +\n\" address= '\" + address + \"',\" +\n\" postal_code= '\" + postal_code + \"',\" +\n\" province= '\" + province + \"',\" +\n\" phone_number= '\" + phone_number + \"'\" +\n\" WHERE player_id =\" + searchP_id + \";\";\n\nIt is also a good idea to use a PreparedStatement instead of concatenating the values into the query string like this. This will help prevent SQL injection attacks and make your code more efficient. Here is an example of how you can use a PreparedStatement to update the player record:\n// Create the UPDATE query with placeholders for the values\nString sql = \"UPDATE player SET\" +\n\" first_name= ?,\" +\n\" last_name= ?,\" +\n\" address= ?,\" +\n\" postal_code= ?,\" +\n\" province= ?,\" +\n\" phone_number= ?\" +\n\" WHERE player_id = ?\";\n\n// Create a PreparedStatement object\nPreparedStatement pstmt = connection.prepareStatement(sql);\n\n// Set the values for the placeholders in the query\npstmt.setString(1, first_name);\npstmt.setString(2, last_name);\npstmt.setString(3, address);\npstmt.setString(4, postal_code);\npstmt.setString(5, province);\npstmt.setString(6, phone_number);\npstmt.setInt(7, searchP_id);\n\n// Execute the UPDATE query\npstmt.executeUpdate();\n\n// Close the PreparedStatement\npstmt.close();\n\n", "Your query is not readable and you should use parameters in your JDBC statement.\ndbConnect();\n\nJFrame frame;\nframe = new JFrame();\n\nint searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, \"Please enter the ID of the Player you would like to update\"));\n\nString sql = \"UPDATE player\" + \n \" SET first_name = ?, last_name = ?, address = ?,\" + \n \" postal_code = ?, province = ?, phone_number = ?\" +\n \" WHERE player_id = ?\";\n\nPreparedStatement preparedStatement =\n connection.prepareStatement(sql);\n\npreparedStatement.setString(1, \"the_first_name\");\npreparedStatement.setString(2, \"the_last_name\");\npreparedStatement.setString(3, \"the_address\");\npreparedStatement.setString(4, \"the_postal_code\");\npreparedStatement.setString(5, \"the_province\");\npreparedStatement.setString(6, \"the_phone_number\");\npreparedStatement.setLong(7, \"the_player_id\");\n\npreparedStatement.executeUpdate(sql);\n\nif (preparedStatement != null) {\n //Close Statement\n preparedStatement.close();\n}\n\nTake look here for more details on parameters with JDBC.\n" ]
[ 1, 0 ]
[]
[]
[ "java", "jdbc" ]
stackoverflow_0074671815_java_jdbc.txt
Q: I'm learning how to work with files in Python using Jupyter notebook. Why do I have to use open() each time to print what I'd like to? I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) lines = my_file.readlines() print(lines[1]) But the second print command did not print anything. then I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) my_file = open("test.txt") lines = my_file.readlines() print(lines[1]) and the second print command printed correctly. Why do I have to use open() each time? A: # See comments in line. fi = open("test.txt", 'w') for n in range(10): fi.write(str(n)) fi.close() my_file = open("test.txt") for line in my_file: print("Here it says: " + line) # The file indicates there are no more lines by setting the EOF # End of file marker lines = my_file.readlines() # reads the same end of file marker. print(lines[1])
I'm learning how to work with files in Python using Jupyter notebook. Why do I have to use open() each time to print what I'd like to?
I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) lines = my_file.readlines() print(lines[1]) But the second print command did not print anything. then I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) my_file = open("test.txt") lines = my_file.readlines() print(lines[1]) and the second print command printed correctly. Why do I have to use open() each time?
[ "# See comments in line.\nfi = open(\"test.txt\", 'w')\nfor n in range(10):\n fi.write(str(n))\nfi.close()\n\nmy_file = open(\"test.txt\")\nfor line in my_file:\n print(\"Here it says: \" + line)\n# The file indicates there are no more lines by setting the EOF\n# End of file marker\nlines = my_file.readlines() # reads the same end of file marker.\nprint(lines[1])\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074671890_jupyter_notebook_python.txt
Q: Linear Regression Model with Measurement Errors I have received this confusing task: You have two variables and , where y is a response variable which can be written as an explicit linear function of . However, the technique used for measuring is twice as better than that for measuring in the sense of error variance, i.e. the variance of the error in is twice as small as the variance of error in . The task is to model y as a function of x. How should I go about doing this? When I used a basic linear regression algorithm on the data, this was the result: When I removed the outliers, this was the result: The second one looks pretty good, but I think I am missing something. This is supposedly the data that has a "measurement error". What do you think I should do instead? A: It sounds like the task is asking you to incorporate the different error variances for the two variables, and , into your linear regression model. One way to do this would be to use weighted least squares regression, where the weights reflect the inverse of the error variances. In this case, since the error variance for is half that of , you would use weights of 2 for the values and 1 for the values. This would give more weight to the values in the regression, since they have smaller errors.
Linear Regression Model with Measurement Errors
I have received this confusing task: You have two variables and , where y is a response variable which can be written as an explicit linear function of . However, the technique used for measuring is twice as better than that for measuring in the sense of error variance, i.e. the variance of the error in is twice as small as the variance of error in . The task is to model y as a function of x. How should I go about doing this? When I used a basic linear regression algorithm on the data, this was the result: When I removed the outliers, this was the result: The second one looks pretty good, but I think I am missing something. This is supposedly the data that has a "measurement error". What do you think I should do instead?
[ "It sounds like the task is asking you to incorporate the different error variances for the two variables, and , into your linear regression model. One way to do this would be to use weighted least squares regression, where the weights reflect the inverse of the error variances. In this case, since the error variance for is half that of , you would use weights of 2 for the values and 1 for the values. This would give more weight to the values in the regression, since they have smaller errors.\n" ]
[ 0 ]
[]
[]
[ "linear_regression", "machine_learning", "variance" ]
stackoverflow_0074668125_linear_regression_machine_learning_variance.txt
Q: How can I make an int to add each value of the matrix and add 20% with input a = [ [200,300,5000,400],[554,500,1000,652],[800,500,650,800],[950,120,470,500],[500,600,2000,100]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() I am trying to increase each value by 20%, and then print the matrix with the increase, For example, this is the original matrix [200,300],[500,400] and I will increase 20% of each and show the matrix with new values [240,360],[600,480] A: This should work if you want to modify the original matrix; if not, Chris' answer is simpler. for x in a: for i in range(len(x)): x[i] = int(x[i] * 1.2) A: You may wish to generate a new "matrix" with your adjusted values, in which case list comprehensions can be useful: b = [[int(y * 1.2) for y in x] for x in a] Printing the matrix we can find the widest number, then use str.rjust to ensure columns are lined up. >>> w = len(str(max(max(x) for x in a))) >>> str(400).rjust(w) ' 400' >>> for x in a: ... print(*(str(y).rjust(w) for y in x), sep=' ', end='\n') ... 200 300 5000 400 554 500 1000 652 800 500 650 800 950 120 470 500 500 600 2000 100 >>>
How can I make an int to add each value of the matrix and add 20% with input
a = [ [200,300,5000,400],[554,500,1000,652],[800,500,650,800],[950,120,470,500],[500,600,2000,100]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() I am trying to increase each value by 20%, and then print the matrix with the increase, For example, this is the original matrix [200,300],[500,400] and I will increase 20% of each and show the matrix with new values [240,360],[600,480]
[ "This should work if you want to modify the original matrix; if not, Chris' answer is simpler.\nfor x in a:\n for i in range(len(x)):\n x[i] = int(x[i] * 1.2)\n\n", "You may wish to generate a new \"matrix\" with your adjusted values, in which case list comprehensions can be useful:\nb = [[int(y * 1.2) for y in x] for x in a]\n\nPrinting the matrix we can find the widest number, then use str.rjust to ensure columns are lined up.\n>>> w = len(str(max(max(x) for x in a)))\n>>> str(400).rjust(w)\n' 400'\n>>> for x in a:\n... print(*(str(y).rjust(w) for y in x), sep=' ', end='\\n')\n... \n 200 300 5000 400\n 554 500 1000 652\n 800 500 650 800\n 950 120 470 500\n 500 600 2000 100\n>>>\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671824_python.txt
Q: NodeJs: Write export in ES6 Sytax I am currently working on a bot, that I write with node.js However, I have this piece of code: commands/server.js const { SlashCommandBuilder } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("server") .setDescription("Provides information about the server."), async execute(interaction) { // interaction.guild is the object representing the Guild in which the command was run await interaction.reply( `This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.` ); }, }; I call it inside my index.js like this: //for every command we have for (const file of commandFiles) { //get the file path const filePath = path.join(commandsPath, file); //load our command_name.js const command = require(filePath); // Set a new item in the Collection with the key as the command name and the value as the exported module if ("data" in command && "execute" in command) { client.commands.set(command.data.name, command); } else { console.log( `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.` ); } } What would be the equivalent in ES6 syntax for server.js, when I set my type to module && want to use the import syntax - so I still got the data and execute property. A: Here is an example of how you could write the server.js file using the ES6 import syntax and export syntax: // Import the `SlashCommandBuilder` class from the `discord.js` module import { SlashCommandBuilder } from 'discord.js'; // Create an object with the data and execute properties const command = { // Create a new instance of the `SlashCommandBuilder` class and set its name and description properties data: new SlashCommandBuilder() .setName('server') .setDescription('Provides information about the server.'), // Define the `execute` method, which takes an `interaction` object as its argument async execute(interaction) { // Use the `interaction.guild` property to get information about the Guild in which the command was run await interaction.reply( `This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.` ); }, }; // Export the `command` object export default command; Then, in your index.js file, you can import the command object using the import syntax and destructure it to get the data and execute properties: // Import the `command` object from the `server.js` file import command from './commands/server'; // Destructure the `data` and `execute` properties from the `command` object const { data, execute } = command; // Set a new item in the Collection with the key as the command name and the value as the exported module if ("data" in command && "execute" in command) { client.commands.set(data.name, { data, execute }); } else { console.log( `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.` ); }
NodeJs: Write export in ES6 Sytax
I am currently working on a bot, that I write with node.js However, I have this piece of code: commands/server.js const { SlashCommandBuilder } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("server") .setDescription("Provides information about the server."), async execute(interaction) { // interaction.guild is the object representing the Guild in which the command was run await interaction.reply( `This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.` ); }, }; I call it inside my index.js like this: //for every command we have for (const file of commandFiles) { //get the file path const filePath = path.join(commandsPath, file); //load our command_name.js const command = require(filePath); // Set a new item in the Collection with the key as the command name and the value as the exported module if ("data" in command && "execute" in command) { client.commands.set(command.data.name, command); } else { console.log( `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.` ); } } What would be the equivalent in ES6 syntax for server.js, when I set my type to module && want to use the import syntax - so I still got the data and execute property.
[ "Here is an example of how you could write the server.js file using the ES6 import syntax and export syntax:\n// Import the `SlashCommandBuilder` class from the `discord.js` module\nimport { SlashCommandBuilder } from 'discord.js';\n\n// Create an object with the data and execute properties\nconst command = {\n // Create a new instance of the `SlashCommandBuilder` class and set its name and description properties\n data: new SlashCommandBuilder()\n .setName('server')\n .setDescription('Provides information about the server.'),\n\n // Define the `execute` method, which takes an `interaction` object as its argument\n async execute(interaction) {\n // Use the `interaction.guild` property to get information about the Guild in which the command was run\n await interaction.reply(\n `This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`\n );\n },\n};\n\n// Export the `command` object\nexport default command;\n\nThen, in your index.js file, you can import the command object using the import syntax and destructure it to get the data and execute properties:\n// Import the `command` object from the `server.js` file\nimport command from './commands/server';\n\n// Destructure the `data` and `execute` properties from the `command` object\nconst { data, execute } = command;\n\n// Set a new item in the Collection with the key as the command name and the value as the exported module\nif (\"data\" in command && \"execute\" in command) {\n client.commands.set(data.name, { data, execute });\n} else {\n console.log(\n `[WARNING] The command at ${filePath} is missing a required \"data\" or \"execute\" property.`\n );\n}\n\n" ]
[ 1 ]
[]
[]
[ "ecmascript_6", "javascript", "node.js" ]
stackoverflow_0074671946_ecmascript_6_javascript_node.js.txt
Q: I'm Having an Issue with Panels c# I have two pages: Drop Down List that User picks a Customer Name from and a load button (Panel 1) Page with Customer Order Information (Panel 2) On the 2nd page, I have a check box that will show Customer Details in a DetailsView if it is checked. My issue is when I go to click on the check box, it brings me back to my First Page with the DownDrop List, which is Panel 1. I have to click the load button to see the second panel again and once it's clicked again, it shows the DetailsView which the check box checked. I have tried everything, this is what my code looks like: protected void Page_Load(object sender, EventArgs e) { // always show first panel when page loads pnlFirstPage.Visible = true; pnlSecondPage.Visible = false; } protected void btnLoadOrders_Click(object sender, EventArgs e) { // hide the first page and continue to second page pnlSecondPage.Visible = true; pnlFirstPage.Visible = false; // if statement to show details view of customer details if (cbCustomerDetails.Checked == true) { dvCustomerDetails.Visible = true; dvCustomerDetails.DataBind(); pnlFirstPage.Visible = false; pnlSecondPage.Visible = true; } A: Ok, so the issue/problem is that keep in mind that EVERY post-back will trigger the page load event. In other words, any button any dropdown/combo box, or ANY code event that triggers a post-back will fire the page load even EACH time, and THEN your button/event code stub runs. Thus, for really what amounts to the last 200+ web form pages I built? EVERY page for setup/loading controls, data etc. will have a if not postback code stub on the page load command. So, say this markup in panel1 <asp:Panel ID="Panel1" runat="server"> <h3>Select Hotel</h3> <asp:DropDownList ID="cboHotels" runat="server" DataValueField="ID" DataTextField="HotelName" Width="198px"> </asp:DropDownList> <button runat="server" id="btnRun" title="Search" style="margin-left: 15px" type="button" class="btn" onserverclick="btnRun_ServerClick"> <span class="glyphicon glyphicon-home"></span>View <br /> </button> </asp:Panel> <asp:Panel ID="Panel2" runat="server" > <h3>Hotel Infomration</h3> <div id="EditRecord" runat="server" style="float:left;display: normal;border:solid 2px;padding:12px;border-radius:12px"> <h2>Edit Hotel</h2> <div style="float:left" class="iForm"> <label>HotelName</label> <asp:TextBox ID="txtHotel" runat="server" f="HOtelName" width="280" /> <br /> bla bla bla for panel2. so, now my code on startup can be to load up the combo box/dropdown list, and set Panel 1 visible, and panel 2 visible = false. We have this code: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Panel1.Visible = true; Panel2.Visible = false; LoadData(); // load our combo box } } void LoadData() { SqlCommand cmdSQL = new SqlCommand("SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName"); cboHotels.DataSource = MyRstP(cmdSQL); cboHotels.DataBind(); cboHotels.Items.Insert(0, new ListItem("Select", "")); } DataTable MyRstP(SqlCommand cmdSQL) { DataTable rstData = new DataTable(); using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4)) { using (cmdSQL) { cmdSQL.Connection = conn; conn.Open(); rstData.Load(cmdSQL.ExecuteReader()); } } return rstData; } And the button to view the details (in panel2), then can look like this: protected void btnRun_ServerClick(object sender, EventArgs e) { if (cboHotels.SelectedIndex > 0) { string strSQL = "SELECT * FROM tblHotelsA WHERE ID = @ID"; SqlCommand cmdSQL = new SqlCommand(strSQL); cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = cboHotels.SelectedItem.Value; DataTable rstData = MyRstP(cmdSQL); General.FLoader(EditRecord, rstData.Rows[0]); Panel1.Visible = false; Panel2.Visible = true; } } And now the results are this: So, just keep in mind that the REAL first page load has to be inside of that if !IsPostBack stub. You can think of that code stub the REAL or "first" page load. Thus, loading up a gridview, loading up a combo box, and say setting panel1 visible, and panel2 hidden all typical code that one would place in the real page startup code. It quite much means you can't really build a working page without taking into account that page-load fires each and every time a event occurs on the page. In fact, if you adopt a up-date panel, then the above will holds true.
I'm Having an Issue with Panels c#
I have two pages: Drop Down List that User picks a Customer Name from and a load button (Panel 1) Page with Customer Order Information (Panel 2) On the 2nd page, I have a check box that will show Customer Details in a DetailsView if it is checked. My issue is when I go to click on the check box, it brings me back to my First Page with the DownDrop List, which is Panel 1. I have to click the load button to see the second panel again and once it's clicked again, it shows the DetailsView which the check box checked. I have tried everything, this is what my code looks like: protected void Page_Load(object sender, EventArgs e) { // always show first panel when page loads pnlFirstPage.Visible = true; pnlSecondPage.Visible = false; } protected void btnLoadOrders_Click(object sender, EventArgs e) { // hide the first page and continue to second page pnlSecondPage.Visible = true; pnlFirstPage.Visible = false; // if statement to show details view of customer details if (cbCustomerDetails.Checked == true) { dvCustomerDetails.Visible = true; dvCustomerDetails.DataBind(); pnlFirstPage.Visible = false; pnlSecondPage.Visible = true; }
[ "Ok, so the issue/problem is that keep in mind that EVERY post-back will trigger the page load event.\nIn other words, any button any dropdown/combo box, or ANY code event that triggers a post-back will fire the page load even EACH time, and THEN your button/event code stub runs.\nThus, for really what amounts to the last 200+ web form pages I built?\nEVERY page for setup/loading controls, data etc. will have a if not postback code stub on the page load command.\nSo, say this markup in panel1\n <asp:Panel ID=\"Panel1\" runat=\"server\">\n\n <h3>Select Hotel</h3>\n <asp:DropDownList ID=\"cboHotels\" runat=\"server\"\n DataValueField=\"ID\"\n DataTextField=\"HotelName\" Width=\"198px\">\n </asp:DropDownList>\n\n <button runat=\"server\" id=\"btnRun\" title=\"Search\"\n style=\"margin-left: 15px\"\n type=\"button\" class=\"btn\"\n onserverclick=\"btnRun_ServerClick\">\n <span class=\"glyphicon glyphicon-home\"></span>View\n <br />\n </button>\n\n </asp:Panel>\n\n <asp:Panel ID=\"Panel2\" runat=\"server\" >\n <h3>Hotel Infomration</h3>\n <div id=\"EditRecord\" runat=\"server\" \n style=\"float:left;display: normal;border:solid 2px;padding:12px;border-radius:12px\">\n\n <h2>Edit Hotel</h2>\n <div style=\"float:left\" class=\"iForm\">\n <label>HotelName</label>\n <asp:TextBox ID=\"txtHotel\" runat=\"server\" f=\"HOtelName\" width=\"280\" /> <br />\n\nbla bla bla for panel2.\nso, now my code on startup can be to load up the combo box/dropdown list, and set Panel 1 visible, and panel 2 visible = false.\nWe have this code:\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n Panel1.Visible = true;\n Panel2.Visible = false;\n LoadData(); // load our combo box\n }\n }\n\n void LoadData() \n {\n SqlCommand cmdSQL = \n new SqlCommand(\"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName\");\n\n cboHotels.DataSource = MyRstP(cmdSQL);\n cboHotels.DataBind();\n cboHotels.Items.Insert(0, new ListItem(\"Select\", \"\"));\n }\n\n\n\n DataTable MyRstP(SqlCommand cmdSQL)\n {\n DataTable rstData = new DataTable();\n using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))\n {\n using (cmdSQL)\n {\n cmdSQL.Connection = conn;\n conn.Open();\n rstData.Load(cmdSQL.ExecuteReader());\n }\n }\n return rstData;\n }\n\nAnd the button to view the details (in panel2), then can look like this:\n protected void btnRun_ServerClick(object sender, EventArgs e)\n {\n if (cboHotels.SelectedIndex > 0)\n {\n string strSQL = \"SELECT * FROM tblHotelsA WHERE ID = @ID\";\n SqlCommand cmdSQL = new SqlCommand(strSQL);\n cmdSQL.Parameters.Add(\"@ID\", SqlDbType.Int).Value = cboHotels.SelectedItem.Value;\n\n DataTable rstData = MyRstP(cmdSQL);\n\n General.FLoader(EditRecord, rstData.Rows[0]);\n Panel1.Visible = false;\n Panel2.Visible = true;\n }\n }\n\nAnd now the results are this:\n\nSo, just keep in mind that the REAL first page load has to be inside of that if !IsPostBack stub.\nYou can think of that code stub the REAL or \"first\" page load. Thus, loading up a gridview, loading up a combo box, and say setting panel1 visible, and panel2 hidden all typical code that one would place in the real page startup code.\nIt quite much means you can't really build a working page without taking into account that page-load fires each and every time a event occurs on the page.\nIn fact, if you adopt a up-date panel, then the above will holds true.\n" ]
[ 0 ]
[]
[]
[ "asp.net", "c#", "webforms" ]
stackoverflow_0074664028_asp.net_c#_webforms.txt
Q: Live Auto Reload of golang apps - Cosmtrek/air I am trying to auto-reload golang apps inside docker. I am using cosmtrek/air for doing it and it seems to be fine in my windows 10 machine. But when I am using docker for doing it, the code is not rebuilding. Here is the file structure -cmd -api -main.go .air.toml docker-compose.dev.yml Dockerfile.dev go.mod go.sum This is my dockerfile FROM golang:1.18.3-alpine3.15 WORKDIR /app COPY go.mod go.sum /app/ RUN go mod download && go mod verify RUN go install github.com/cosmtrek/air@latest COPY ./ /app/ CMD "air" Here is my docker-compose.dev.yml file version: '3.8' services: backend: container_name: go-backend-test build: context: . dockerfile: ./Dockerfile.dev volumes: - ./:/app This is the output I get in the logs The issue is if I change anything in the main.go or any go files, the logs are not getting updating with the new code even through I have sh into the docker-container where the volumes are getting updating. Its seems to be not rebuilding. However it works fine and rebuilds in my windows machine. This is my .air.toml file root = "." testdata_dir = "testdata" tmp_dir = "tmp" [build] args_bin = [] bin = "tmp/main.exe" cmd = "go build -o ./tmp/main.exe ./cmd/api/." delay = 1000 exclude_dir = ["assets", "tmp", "vendor", "testdata"] exclude_file = [] exclude_regex = ["_test.go"] exclude_unchanged = false follow_symlink = false full_bin = "" include_dir = [] include_ext = ["go", "tpl", "tmpl", "html"] kill_delay = "0s" log = "build-errors.log" send_interrupt = false stop_on_error = true [color] app = "" build = "yellow" main = "magenta" runner = "green" watcher = "cyan" [log] time = false [misc] clean_on_exit = true [screen] clear_on_rebuild = true Just burning my head on the topic all day. Thanks in advance for ideas! A: Try with bin = "./tmp/main.exe instead of bin = "tmp/main.exe" Hope that this will help you. A: Your code is okay. The problem is with the technology docker uses for file sharing between a host system and containers. I have had the same issues on mac when tried to use not the Docker Desktop but an alternative like Rancher which even uses docker CLI via moby. When I switched back to the original Docker Desktop which uses gRPC FUSE, osxfs, and VirtioFS — with all of them worked like a charm.
Live Auto Reload of golang apps - Cosmtrek/air
I am trying to auto-reload golang apps inside docker. I am using cosmtrek/air for doing it and it seems to be fine in my windows 10 machine. But when I am using docker for doing it, the code is not rebuilding. Here is the file structure -cmd -api -main.go .air.toml docker-compose.dev.yml Dockerfile.dev go.mod go.sum This is my dockerfile FROM golang:1.18.3-alpine3.15 WORKDIR /app COPY go.mod go.sum /app/ RUN go mod download && go mod verify RUN go install github.com/cosmtrek/air@latest COPY ./ /app/ CMD "air" Here is my docker-compose.dev.yml file version: '3.8' services: backend: container_name: go-backend-test build: context: . dockerfile: ./Dockerfile.dev volumes: - ./:/app This is the output I get in the logs The issue is if I change anything in the main.go or any go files, the logs are not getting updating with the new code even through I have sh into the docker-container where the volumes are getting updating. Its seems to be not rebuilding. However it works fine and rebuilds in my windows machine. This is my .air.toml file root = "." testdata_dir = "testdata" tmp_dir = "tmp" [build] args_bin = [] bin = "tmp/main.exe" cmd = "go build -o ./tmp/main.exe ./cmd/api/." delay = 1000 exclude_dir = ["assets", "tmp", "vendor", "testdata"] exclude_file = [] exclude_regex = ["_test.go"] exclude_unchanged = false follow_symlink = false full_bin = "" include_dir = [] include_ext = ["go", "tpl", "tmpl", "html"] kill_delay = "0s" log = "build-errors.log" send_interrupt = false stop_on_error = true [color] app = "" build = "yellow" main = "magenta" runner = "green" watcher = "cyan" [log] time = false [misc] clean_on_exit = true [screen] clear_on_rebuild = true Just burning my head on the topic all day. Thanks in advance for ideas!
[ "Try with\n\nbin = \"./tmp/main.exe\n\ninstead of\n\nbin = \"tmp/main.exe\"\n\nHope that this will help you.\n", "Your code is okay.\nThe problem is with the technology docker uses for file sharing between a host system and containers.\nI have had the same issues on mac when tried to use not the Docker Desktop but an alternative like Rancher which even uses docker CLI via moby. When I switched back to the original Docker Desktop which uses gRPC FUSE, osxfs, and VirtioFS — with all of them worked like a charm.\n" ]
[ 0, 0 ]
[]
[]
[ "docker", "docker_compose", "dockerfile", "go" ]
stackoverflow_0072546523_docker_docker_compose_dockerfile_go.txt
Q: Using VBA, how do I create a custom field in Word that uses the current page number? I'm trying to add a custom field in Word (in the shape { CUSTOM_FIELD } ) that uses the current page number and outputs its text representation (12 => twelve), but in multiple exotic (not supported) languages, which is why the built-in English variant (page * cardtext) isn't sufficient. The VBA code won't be a problem, but I need to know how to create a custom field. The field would be added to the footer template, before 100s of pages would be added programmatically. I tried using a custom DocProperty, but wasn't able to find a way to integrate the needed behavior. Another linked answer seems to be using the existing { PAGE } field, which wouldn't help, as I need to insert the new field (once only) into the footer template. A: This isn't the only possible way to do this, but if you have a reasonably small maximum page count then you could use a { DOCVARIABLE } field something like this, where "LANG" is just a piece of text that identifies the language you want to use: { DOCVARIABLE "LANG{ PAGE }" } You would then need to use VBA to set up 1 Document variable to store the text verion of each page number. Document variables are in essence key-value pairs stored invisibly in the document. e.g. Let's suppose you were wanted the text versions of numbers from one to three in English, French and German. So you could have document variables with the following names and values EN1 One EN2 Two EN3 Three FR1 Un FR2 Deux FR3 Trois DE1 Ein DE2 Zwei DE3 Drei Even if you need hundreds or thousands of these, the amount of text you can store in Document variables is very large. OTOH if you need to be able to generate the texts dynamically by building them using an algorothm (as \* Cardtext probably does) this won't work. To set up one of these variables youjust need, e.g. ActiveDocument.Variables("EN1").Value = "One" The field you would need for the English results would be { DOCVARIABLE "EN{ PAGE }" } As long as you only need to use one language in each document, you could just change the "EN" to "FR" to get the French version, etc. - after all, if you only have one footer layout, you would only need to make one change. Otherwise, you could consider storing the language code somewhere else in the document, e.g. in a bookmark called LANG, in which case you might use { DOCVARIABLE "{ LANG }{ PAGE }" } in a DOCVARIABLE called LANG, so you would use { DOCVARIABLE "{ DOCVARIABLE LANG }{ PAGE }" } in a Custom document property called LANG, so you would use { DOCVARIABLE "{ DOCPROPERTY LANG }{ PAGE }" } (The problem with using custom document properties for your numbers is that you can only have a small number of them). If that general approach can't be made to fit what you're trying to achieve, I think you'll probably need to clarify your Question some more. A: The Cardtext switch will give numbering in different languages, assuming that the language is applied to the text as proofing language. I would recommend saving a { Page * Cardtext } field as AutoText or another Building Block in your template and using code to insert it. Here is my writing on using vba to insert AutoText. The following creates the field at the insertion point. Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _ PreserveFormatting:=False Selection.TypeText Text:="Page \* CardText"
Using VBA, how do I create a custom field in Word that uses the current page number?
I'm trying to add a custom field in Word (in the shape { CUSTOM_FIELD } ) that uses the current page number and outputs its text representation (12 => twelve), but in multiple exotic (not supported) languages, which is why the built-in English variant (page * cardtext) isn't sufficient. The VBA code won't be a problem, but I need to know how to create a custom field. The field would be added to the footer template, before 100s of pages would be added programmatically. I tried using a custom DocProperty, but wasn't able to find a way to integrate the needed behavior. Another linked answer seems to be using the existing { PAGE } field, which wouldn't help, as I need to insert the new field (once only) into the footer template.
[ "This isn't the only possible way to do this, but if you have a reasonably small maximum page count then you could use a { DOCVARIABLE } field something like this, where \"LANG\" is just a piece of text that identifies the language you want to use:\n{ DOCVARIABLE \"LANG{ PAGE }\" }\n\nYou would then need to use VBA to set up 1 Document variable to store the text verion of each page number. Document variables are in essence key-value pairs stored invisibly in the document.\ne.g. Let's suppose you were wanted the text versions of numbers from one to three in English, French and German. So you could have document variables with the following names and values\nEN1 One\nEN2 Two\nEN3 Three\nFR1 Un\nFR2 Deux\nFR3 Trois\nDE1 Ein\nDE2 Zwei\nDE3 Drei\n\nEven if you need hundreds or thousands of these, the amount of text you can store in Document variables is very large. OTOH if you need to be able to generate the texts dynamically by building them using an algorothm (as \\* Cardtext probably does) this won't work.\nTo set up one of these variables youjust need, e.g.\nActiveDocument.Variables(\"EN1\").Value = \"One\"\n\nThe field you would need for the English results would be\n{ DOCVARIABLE \"EN{ PAGE }\" }\n\nAs long as you only need to use one language in each document, you could just change the \"EN\" to \"FR\" to get the French version, etc. - after all, if you only have one footer layout, you would only need to make one change. Otherwise, you could consider storing the language code somewhere else in the document, e.g.\n\nin a bookmark called LANG, in which case you might use\n{ DOCVARIABLE \"{ LANG }{ PAGE }\" }\n\nin a DOCVARIABLE called LANG, so you would use\n{ DOCVARIABLE \"{ DOCVARIABLE LANG }{ PAGE }\" }\n\nin a Custom document property called LANG, so you would use\n{ DOCVARIABLE \"{ DOCPROPERTY LANG }{ PAGE }\" }\n\n\n(The problem with using custom document properties for your numbers is that you can only have a small number of them).\nIf that general approach can't be made to fit what you're trying to achieve, I think you'll probably need to clarify your Question some more.\n", "The Cardtext switch will give numbering in different languages, assuming that the language is applied to the text as proofing language.\n\nI would recommend saving a { Page * Cardtext } field as AutoText or another Building Block in your template and using code to insert it. Here is my writing on using vba to insert AutoText.\nThe following creates the field at the insertion point.\nSelection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _\n PreserveFormatting:=False\nSelection.TypeText Text:=\"Page \\* CardText\"\n\n" ]
[ 1, 0 ]
[]
[]
[ "ms_word", "vba" ]
stackoverflow_0074668716_ms_word_vba.txt
Q: AttributeError: 'KerasTPUModel' object has no attribute '_ckpt_saved_epoch' I am training a keras model with google colab TPU. My code ran successfully on CPU and GPU before. However, when I changed the code to the TPU version, I met some error. Here is my transform code: model = tf.contrib.tpu.keras_to_tpu_model( model, strategy=tf.contrib.tpu.TPUDistributionStrategy( tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER))) Here is my compile code: model.compile(optimizer=tf.train.AdamOptimizer(learning_rate=1e-3), loss='categorical_crossentropy', metrics=['accuracy']) The error happened when I ran the following code: model.fit(X_train,y_train,epochs=10,batch_size=64*8,validation_data=(X_test,y_test)) The error: AttributeError: 'KerasTPUModel' object has no attribute '_ckpt_saved_epoch' Thank you advance for your help A: In my script, I resolved this error by downgrading Tensorflow from 1.14 to 1.12
AttributeError: 'KerasTPUModel' object has no attribute '_ckpt_saved_epoch'
I am training a keras model with google colab TPU. My code ran successfully on CPU and GPU before. However, when I changed the code to the TPU version, I met some error. Here is my transform code: model = tf.contrib.tpu.keras_to_tpu_model( model, strategy=tf.contrib.tpu.TPUDistributionStrategy( tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER))) Here is my compile code: model.compile(optimizer=tf.train.AdamOptimizer(learning_rate=1e-3), loss='categorical_crossentropy', metrics=['accuracy']) The error happened when I ran the following code: model.fit(X_train,y_train,epochs=10,batch_size=64*8,validation_data=(X_test,y_test)) The error: AttributeError: 'KerasTPUModel' object has no attribute '_ckpt_saved_epoch' Thank you advance for your help
[ "In my script, I resolved this error by downgrading Tensorflow from 1.14 to 1.12\n" ]
[ 0 ]
[]
[]
[ "python_3.x", "tf.keras" ]
stackoverflow_0057215427_python_3.x_tf.keras.txt
Q: Prolog How to write a predicate sum 3 max values in list? How to write a predicate sum 3 max values in list? max3(L,X) Example: max3([1,7,9,3,5],X). X = 21. A: As a starting point: % Can potentially change order of the list in Rest list_max_rest([H|T], Max, Rest) :- list_max_rest_(T, H, Max, Rest). list_max_rest_([], Max, Max, []). list_max_rest_([H|T], P, Max, [P|Rest]) :- H @> P, !, list_max_rest_(T, H, Max, Rest). list_max_rest_([H|T], P, Max, [H|Rest]) :- list_max_rest_(T, P, Max, Rest). Usage: ?- list_max_rest([2,1,200,9], Max, Res). Max = 200, Res = [1, 2, 9]. Use that 3 times... A: max3(Ls, X) :- select(A, Ls, Ls2), select(B, Ls2, Ls3), select(C, Ls3, Ls4), A >= B, B >= C, \+ (member(Q, Ls4), Q > C), X is A+B+C. Take A from the list, B from the remainder, C from that remainder, they must be A>=B>=C, and there must not be a member Q left in the remainder which is bigger than C. Add those up. This is not efficient; brebs' suggestion of: max3(Ls, X) :- sort(0, @>=, Ls, [A,B,C|_]), X is A+B+C. is neater
Prolog How to write a predicate sum 3 max values in list?
How to write a predicate sum 3 max values in list? max3(L,X) Example: max3([1,7,9,3,5],X). X = 21.
[ "As a starting point:\n% Can potentially change order of the list in Rest\nlist_max_rest([H|T], Max, Rest) :-\n list_max_rest_(T, H, Max, Rest).\n \nlist_max_rest_([], Max, Max, []).\nlist_max_rest_([H|T], P, Max, [P|Rest]) :-\n H @> P,\n !,\n list_max_rest_(T, H, Max, Rest).\nlist_max_rest_([H|T], P, Max, [H|Rest]) :-\n list_max_rest_(T, P, Max, Rest).\n\nUsage:\n?- list_max_rest([2,1,200,9], Max, Res).\nMax = 200,\nRes = [1, 2, 9].\n\nUse that 3 times...\n", "max3(Ls, X) :-\n select(A, Ls, Ls2),\n select(B, Ls2, Ls3),\n select(C, Ls3, Ls4),\n A >= B,\n B >= C,\n \\+ (member(Q, Ls4), Q > C),\n X is A+B+C.\n\nTake A from the list, B from the remainder, C from that remainder, they must be A>=B>=C, and there must not be a member Q left in the remainder which is bigger than C. Add those up.\nThis is not efficient; brebs' suggestion of:\nmax3(Ls, X) :-\n sort(0, @>=, Ls, [A,B,C|_]),\n X is A+B+C.\n\nis neater\n" ]
[ 0, 0 ]
[]
[]
[ "prolog" ]
stackoverflow_0074671476_prolog.txt
Q: How to extract the member from single-member set in python? I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach: element = list(myset)[0] But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but iteration seems unnatural as well, since there is only a single element. Am I missing something simple? A: Tuple unpacking works. (element,) = myset (By the way, python-dev has explored but rejected the addition of myset.get() to return an arbitrary element from a set. Discussion here, Guido van Rossum answers 1 and 2.) My personal favorite for getting an arbitrary element is (when you have an unknown number, but also works if you have just one): element = next(iter(myset)) ¹ 1: in Python 2.5 and before, you have to use iter(myset).next() A: Between making a tuple and making an iterator, it's almost a wash, but iteration wins by a nose...: $ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]' 1000000 loops, best of 3: 0.465 usec per loop $ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]' 1000000 loops, best of 3: 0.465 usec per loop $ python2.6 -mtimeit -s'x=set([1])' 'a=next(iter(x))' 1000000 loops, best of 3: 0.456 usec per loop $ python2.6 -mtimeit -s'x=set([1])' 'a=next(iter(x))' 1000000 loops, best of 3: 0.456 usec per loop Not sure why all the answers are using the older syntax iter(x).next() rather than the new one next(iter(x)), which seems preferable to me (and also works in Python 3.1). However, unpacking wins hands-down over both: $ python2.6 -mtimeit -s'x=set([1])' 'a,=x' 10000000 loops, best of 3: 0.174 usec per loop $ python2.6 -mtimeit -s'x=set([1])' 'a,=x' 10000000 loops, best of 3: 0.174 usec per loop This of course is for single-item sets (where the latter form, as others mentioned, has the advantage of failing fast if the set you "knew" had just one item actually had several). For sets with arbitrary N > 1 items, the tuple slows down, the iter doesn't: $ python2.6 -mtimeit -s'x=set(range(99))' 'a=next(iter(x))' 1000000 loops, best of 3: 0.417 usec per loop $ python2.6 -mtimeit -s'x=set(range(99))' 'a=tuple(x)[0]' 100000 loops, best of 3: 3.12 usec per loop So, unpacking for the singleton case, and next(iter(x)) for the general case, seem best. A: I reckon kaizer.se's answer is great. But if your set might contain more than one element, and you want a not-so-arbitrary element, you might want to use min or max. E.g.: element = min(myset) or: element = max(myset) (Don't use sorted, because that has unnecessary overhead for this usage.) A: I suggest: element = myset.pop() A: you can use element = tuple(myset)[0] which is a bit more efficient, or, you can do something like element = iter(myset).next() I guess constructing an iterator is more efficient than constructing a tuple/list. A: There is also Extended Iterable Unpacking which will work on a singleton set or a mulit-element set element, *_ = myset Though some bristle at the use of a throwaway variable. A: One way is to use reduce with lambda x: x. from functools import reduce > reduce(lambda x: x, {3}) 3 > reduce(lambda x: x, {1, 2, 3}) TypeError: <lambda>() takes 1 positional argument but 2 were given > reduce(lambda x: x, {}) TypeError: reduce() of empty sequence with no initial value Benefits: Fails for multiple and zero values Doesn't change the original set Doesn't require data transformations (e.g., to list or iterable) Doesn't need a new variable and can be passed as an argument Arguably less awkward and PEP-compliant A: You can use the more-itertools package. All functions below will return one item from the set, with different behaviors if the set does not contain exactly one item: more_itertools.one raises an exception if iterable is empty or has more than one item: element = more_itertools.one(myset) This works like (element,) = myset, but might not be as fast: $ python3.11 -m timeit -s 'myset = {42}' '(element,) = myset' 5000000 loops, best of 5: 57.9 nsec per loop $ python3.11 -m timeit -s 'from more_itertools import one myset = {42}' 'element = one(myset)' 500000 loops, best of 5: 611 nsec per loop more_itertools.only returns a default if iterable is empty or raises an exception if iterable has more than one item: element = more_itertools.only(myset) more_itertools.first raises an exception if iterable is empty, or a default when one is provided: element = more_itertools.first(myset) This works as element = next(iter(myset)), but is arguably more idiomatic. more_itertools.first_true returns the first "truthy" value in the iterable or a default if iterable is empty: element = more_itertools.first_true(myset) You can also use the first package: from first import first element = first(myset) This works like more_itertools.first_true, mentioned above.
How to extract the member from single-member set in python?
I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach: element = list(myset)[0] But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but iteration seems unnatural as well, since there is only a single element. Am I missing something simple?
[ "Tuple unpacking works.\n(element,) = myset\n\n(By the way, python-dev has explored but rejected the addition of myset.get() to return an arbitrary element from a set. Discussion here, Guido van Rossum answers 1 and 2.)\nMy personal favorite for getting an arbitrary element is (when you have an unknown number, but also works if you have just one):\nelement = next(iter(myset)) ¹\n\n1: in Python 2.5 and before, you have to use iter(myset).next()\n", "Between making a tuple and making an iterator, it's almost a wash, but iteration wins by a nose...:\n$ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]'\n1000000 loops, best of 3: 0.465 usec per loop\n$ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]'\n1000000 loops, best of 3: 0.465 usec per loop\n$ python2.6 -mtimeit -s'x=set([1])' 'a=next(iter(x))'\n1000000 loops, best of 3: 0.456 usec per loop\n$ python2.6 -mtimeit -s'x=set([1])' 'a=next(iter(x))'\n1000000 loops, best of 3: 0.456 usec per loop\n\nNot sure why all the answers are using the older syntax iter(x).next() rather than the new one next(iter(x)), which seems preferable to me (and also works in Python 3.1).\nHowever, unpacking wins hands-down over both:\n$ python2.6 -mtimeit -s'x=set([1])' 'a,=x'\n10000000 loops, best of 3: 0.174 usec per loop\n$ python2.6 -mtimeit -s'x=set([1])' 'a,=x'\n10000000 loops, best of 3: 0.174 usec per loop\n\nThis of course is for single-item sets (where the latter form, as others mentioned, has the advantage of failing fast if the set you \"knew\" had just one item actually had several). For sets with arbitrary N > 1 items, the tuple slows down, the iter doesn't:\n$ python2.6 -mtimeit -s'x=set(range(99))' 'a=next(iter(x))'\n1000000 loops, best of 3: 0.417 usec per loop\n$ python2.6 -mtimeit -s'x=set(range(99))' 'a=tuple(x)[0]'\n100000 loops, best of 3: 3.12 usec per loop\n\nSo, unpacking for the singleton case, and next(iter(x)) for the general case, seem best.\n", "I reckon kaizer.se's answer is great. But if your set might contain more than one element, and you want a not-so-arbitrary element, you might want to use min or max. E.g.:\nelement = min(myset)\n\nor:\nelement = max(myset)\n\n(Don't use sorted, because that has unnecessary overhead for this usage.)\n", "I suggest:\nelement = myset.pop()\n\n", "you can use element = tuple(myset)[0] which is a bit more efficient, or, you can do something like \nelement = iter(myset).next()\n\nI guess constructing an iterator is more efficient than constructing a tuple/list.\n", "There is also Extended Iterable Unpacking which will work on a singleton set or a mulit-element set\nelement, *_ = myset\nThough some bristle at the use of a throwaway variable.\n", "One way is to use reduce with lambda x: x.\nfrom functools import reduce\n\n> reduce(lambda x: x, {3})\n3\n\n> reduce(lambda x: x, {1, 2, 3})\nTypeError: <lambda>() takes 1 positional argument but 2 were given\n\n> reduce(lambda x: x, {})\nTypeError: reduce() of empty sequence with no initial value\n\nBenefits:\n\nFails for multiple and zero values\nDoesn't change the original set\nDoesn't require data transformations (e.g., to list or iterable)\nDoesn't need a new variable and can be passed as an argument\nArguably less awkward and PEP-compliant\n\n", "You can use the more-itertools package. All functions below will return one item from the set, with different behaviors if the set does not contain exactly one item:\n\nmore_itertools.one raises an exception if iterable is empty or has more than one item:\nelement = more_itertools.one(myset)\n\nThis works like (element,) = myset, but might not be as fast:\n$ python3.11 -m timeit -s 'myset = {42}' '(element,) = myset'\n5000000 loops, best of 5: 57.9 nsec per loop\n$ python3.11 -m timeit -s 'from more_itertools import one\nmyset = {42}' 'element = one(myset)'\n500000 loops, best of 5: 611 nsec per loop\n\n\nmore_itertools.only returns a default if iterable is empty or raises an exception if iterable has more than one item:\nelement = more_itertools.only(myset)\n\n\nmore_itertools.first raises an exception if iterable is empty, or a default when one is provided:\nelement = more_itertools.first(myset)\n\nThis works as element = next(iter(myset)), but is arguably more idiomatic.\n\nmore_itertools.first_true returns the first \"truthy\" value in the iterable or a default if iterable is empty:\nelement = more_itertools.first_true(myset)\n\n\n\nYou can also use the first package:\nfrom first import first\n\nelement = first(myset)\n\nThis works like more_itertools.first_true, mentioned above.\n" ]
[ 129, 31, 25, 15, 2, 2, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0001619514_python_set.txt
Q: Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE Phonegap Installation I'm trying to install Phonegap in Ubuntu. The installation of NodeJS was successful, however I can't install Phonegap itself. Here is the error output of terminal: test@test-VirtualBox:~$ sudo npm install -g phonegap npm http GET https://registry.npmjs.org/phonegap npm http GET https://registry.npmjs.org/phonegap npm http GET https://registry.npmjs.org/phonegap npm ERR! Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! at SecurePair.<anonymous> (tls.js:1350:32) npm ERR! at SecurePair.EventEmitter.emit (events.js:92:17) npm ERR! at SecurePair.maybeInitFinished (tls.js:963:10) npm ERR! at CleartextStream.read [as _read] (tls.js:463:15) npm ERR! at CleartextStream.Readable.read (_stream_readable.js:320:10) npm ERR! at EncryptedStream.write [as _write] (tls.js:366:25) npm ERR! at doWrite (_stream_writable.js:219:10) npm ERR! at writeOrBuffer (_stream_writable.js:209:5) npm ERR! at EncryptedStream.Writable.write (_stream_writable.js:180:11) npm ERR! at write (_stream_readable.js:573:24) npm ERR! If you need help, you may report this log at: npm ERR! <http://bugs.debian.org/npm> npm ERR! or use npm ERR! reportbug --attach /home/test/npm-debug.log npm npm ERR! System Linux 3.11.0-14-generic npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "phonegap" npm ERR! cwd /home/test npm ERR! node -v v0.10.15 npm ERR! npm -v 1.2.18 npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /home/test/npm-debug.log npm ERR! not ok code 0 Any help would be appreciated. A: I got the same error, given I was behind a corporate firewall/proxy and my connection was passed the proxy's certificate. In your command line run: npm config set strict-ssl false NOTE: that this is not best practice to blindly accept untrusted or invalid SSL certificates, which is what the command does (turn off certificate checking). You can run npm config set strict-ssl true to turn it back on. ref: https://thomashunter.name/blog/npm-ssl-errors/ A: This can be fixed without disabling strict SSL, however it is non-trivial. Find the certificates actually being used, likely you're behind a corporate SSL intercepting proxy. You might be able to use a browser, some CLI tool etc. I ended up running certmgr.msc in Windows as the certificates are distributed via Group policy and export as p7b files. Convert the certificates if necessary, I used openssl tool to convert from p7b to PEM (aka .crt) openssl pkcs7 -print_certs -inform DER -in /mnt/adam/certs/my-company-root.p7b -outform PEM -out my-company-root.crt Merge, if there is more than one certificate, into a single PEM file, taking care to order from leaf to root. cat my-company-leaf.crt my-company-intermediate.crt my-company-root.crt > my-company-single.crt Configure npm at the certificate file npm config set cafile my-company-single.crt (or globally) sudo npm config set -g cafile my-company-single.crt A: running npm config set strict-ssl false solved my problem. I'm using Vagrant (Linux precise32 Ubuntu ), and Windows 7 as host. Thanks A: in case anyone is as clumsy as me, I got UNABLE_TO_VERIFY_LEAF_SIGNATURE on npm install when I forgot to add the git+ before the url of my project. I had npm install --save https://myserv.er/my/project-path.git instead of npm install --save git+https://myserv.er/my/project-path.git A: You can also disable SSL check in your code using node environment variable : in your index.js file, add : process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; Note that this is not a good habits as it will not try to check the validity of https certificate A: Make sure that root has configuration properties. When using sudo, you're running under the environment configured for root. Root may not have the same node configuration, and may not be aware of your certificates. Try passing your environment configuration to root with -E: $ sudo -E npm install -g phonegap A: It happens to me. It turned out my cooperation proxy restricted the official NPM registry, and returned a blocked HTML warning. Just updated my npm registry to cooperate one, and the problem was solved. A: The error you are encountering indicates that there is a problem with the SSL certificate used by the registry from which you are trying to install Phonegap. This could be caused by a variety of issues, including an outdated certificate on the registry's end or a problem with your network connection. To resolve this error, you can try the following steps: Check your network connection and ensure that it is stable and functioning properly. Try installing Phonegap again using the npm install -g phonegap command. If the error persists, try using the --no-check-certificate flag with the npm command, like so: npm --no-check-certificate install -g phonegap. This will disable SSL certificate checking, which may allow the installation to proceed. If the above steps do not work, you can try using a different registry for installing Phonegap. To do this, run the following command: npm set registry https://registry.npmjs.org/, replacing https://registry.npmjs.org/ with the URL of the registry you want to use. If none of the above steps work, you can try installing Phonegap manually by downloading the source code from the Phonegap website and installing it on your system using the instructions provided.
Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE Phonegap Installation
I'm trying to install Phonegap in Ubuntu. The installation of NodeJS was successful, however I can't install Phonegap itself. Here is the error output of terminal: test@test-VirtualBox:~$ sudo npm install -g phonegap npm http GET https://registry.npmjs.org/phonegap npm http GET https://registry.npmjs.org/phonegap npm http GET https://registry.npmjs.org/phonegap npm ERR! Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! at SecurePair.<anonymous> (tls.js:1350:32) npm ERR! at SecurePair.EventEmitter.emit (events.js:92:17) npm ERR! at SecurePair.maybeInitFinished (tls.js:963:10) npm ERR! at CleartextStream.read [as _read] (tls.js:463:15) npm ERR! at CleartextStream.Readable.read (_stream_readable.js:320:10) npm ERR! at EncryptedStream.write [as _write] (tls.js:366:25) npm ERR! at doWrite (_stream_writable.js:219:10) npm ERR! at writeOrBuffer (_stream_writable.js:209:5) npm ERR! at EncryptedStream.Writable.write (_stream_writable.js:180:11) npm ERR! at write (_stream_readable.js:573:24) npm ERR! If you need help, you may report this log at: npm ERR! <http://bugs.debian.org/npm> npm ERR! or use npm ERR! reportbug --attach /home/test/npm-debug.log npm npm ERR! System Linux 3.11.0-14-generic npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "phonegap" npm ERR! cwd /home/test npm ERR! node -v v0.10.15 npm ERR! npm -v 1.2.18 npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /home/test/npm-debug.log npm ERR! not ok code 0 Any help would be appreciated.
[ "I got the same error, given I was behind a corporate firewall/proxy and my connection was passed the proxy's certificate. \nIn your command line run:\nnpm config set strict-ssl false\n\nNOTE: that this is not best practice to blindly accept untrusted or invalid SSL certificates, which is what the command does (turn off certificate checking). You can run\nnpm config set strict-ssl true\n\nto turn it back on.\nref: https://thomashunter.name/blog/npm-ssl-errors/\n", "This can be fixed without disabling strict SSL, however it is non-trivial.\nFind the certificates actually being used, likely you're behind a corporate SSL intercepting proxy. You might be able to use a browser, some CLI tool etc. I ended up running certmgr.msc in Windows as the certificates are distributed via Group policy and export as p7b files.\nConvert the certificates if necessary, I used openssl tool to convert from p7b to PEM (aka .crt)\nopenssl pkcs7 -print_certs -inform DER -in /mnt/adam/certs/my-company-root.p7b -outform PEM -out my-company-root.crt\n\nMerge, if there is more than one certificate, into a single PEM file, taking care to order from leaf to root.\ncat my-company-leaf.crt my-company-intermediate.crt my-company-root.crt > my-company-single.crt\n\nConfigure npm at the certificate file\nnpm config set cafile my-company-single.crt\n\n(or globally)\nsudo npm config set -g cafile my-company-single.crt\n\n", "running\nnpm config set strict-ssl false\n\nsolved my problem. \nI'm using Vagrant (Linux precise32 Ubuntu ), and Windows 7 as host.\nThanks \n", "in case anyone is as clumsy as me, I got UNABLE_TO_VERIFY_LEAF_SIGNATURE on npm install when I forgot to add the git+ before the url of my project.\nI had \nnpm install --save https://myserv.er/my/project-path.git\n\ninstead of\nnpm install --save git+https://myserv.er/my/project-path.git\n\n", "You can also disable SSL check in your code using node environment variable :\nin your index.js file, add :\nprocess.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\nNote that this is not a good habits as it will not try to check the validity of https certificate\n", "Make sure that root has configuration properties.\nWhen using sudo, you're running under the environment configured for root. Root may not have the same node configuration, and may not be aware of your certificates. Try passing your environment configuration to root with -E:\n$ sudo -E npm install -g phonegap\n\n", "It happens to me. It turned out my cooperation proxy restricted the official NPM registry, and returned a blocked HTML warning. Just updated my npm registry to cooperate one, and the problem was solved.\n", "The error you are encountering indicates that there is a problem with the SSL certificate used by the registry from which you are trying to install Phonegap. This could be caused by a variety of issues, including an outdated certificate on the registry's end or a problem with your network connection.\nTo resolve this error, you can try the following steps:\n\nCheck your network connection and ensure that it is stable and\nfunctioning properly.\nTry installing Phonegap again using the npm install -g phonegap\ncommand. If the error persists, try using the --no-check-certificate\nflag with the npm command, like so: npm --no-check-certificate\ninstall -g phonegap. This will disable SSL certificate checking,\nwhich may allow the installation to proceed.\nIf the above steps do not work, you can try using a different\nregistry for installing Phonegap. To do this, run the following\ncommand: npm set registry https://registry.npmjs.org/, replacing\nhttps://registry.npmjs.org/ with the URL of the registry you want to\nuse.\nIf none of the above steps work, you can try installing Phonegap\nmanually by downloading the source code from the Phonegap website\nand installing it on your system using the instructions provided.\n\n" ]
[ 158, 36, 7, 2, 2, 0, 0, 0 ]
[]
[]
[ "cordova", "node.js", "npm", "ubuntu_13.10" ]
stackoverflow_0020747817_cordova_node.js_npm_ubuntu_13.10.txt
Q: Reading a json file asynchronously, the object property results are always null I have a Json file, it contains connectionstring. I want to asynchronously read the file and deserialize it to a ConnectionString object and I always get a null result. I'm using .NET Core 6 and System.Text.Json. Here is contents of my Json file: { "ConnectionStrings": { "ConnStr": "Data Source=(local);Initial Catalog=MyData;Integrated Security=False;TrustServerCertificate=True;Persist Security Info=False;Async=True;MultipleActiveResultSets=true;User ID=sa;Password=MySecret;", "ProviderName": "SQLServer" } } Here are the contents of my classes: internal class DBConnectionString { [JsonPropertyName("ConnStr")] public string ConnStr { get; set; } [JsonPropertyName("ProviderName")] public string ProviderName { get; set; } public DBConnectionString() { } } public class DBConnStr { private static string AppSettingFilePath => "appsettings.json"; public static async Task<string> GetConnectionStringAsync() { string connStr = ""; if (File.Exists((DBConnStr.AppSettingFilePath))) { using (FileStream sr = new FileStream(AppSettingFilePath, FileMode.Open, FileAccess.Read)) { //string json = await sr.ReadToEndAsync(); System.Text.Json.JsonDocumentOptions docOpt = new System.Text.Json.JsonDocumentOptions() { AllowTrailingCommas = true }; using (var document = await System.Text.Json.JsonDocument.ParseAsync(sr, docOpt)) { System.Text.Json.JsonSerializerOptions opt = new System.Text.Json.JsonSerializerOptions() { AllowTrailingCommas = true, PropertyNameCaseInsensitive = true }; System.Text.Json.JsonElement root = document.RootElement; System.Text.Json.JsonElement element = root.GetProperty("ConnectionStrings"); sr.Position = 0; var dbConStr = await System.Text.Json.JsonSerializer.DeserializeAsync<DBConnectionString>(sr, opt); if (dbConStr != null) { connStr = dbConStr.ConnStr; } } } } return connStr; } } The following is the syntax that I use to call the GetConnectionStringAsync method: string ConnectionString = DBConnStr.GetConnectionStringAsync().Result; When the application is running in debug mode, I checked, on line var dbConStr = await System.Text.Json.JsonSerializer.DeserializeAsync(sr, opt); The DBConnectionString object property is always empty. I also tried the reference on the Microsoft website, https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-6-0 but it doesn't work succeed. using System.Text.Json; namespace DeserializeFromFileAsync { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static async Task Main() { string fileName = "WeatherForecast.json"; using FileStream openStream = File.OpenRead(fileName); WeatherForecast? weatherForecast = await JsonSerializer.DeserializeAsync<WeatherForecast>(openStream); Console.WriteLine($"Date: {weatherForecast?.Date}"); Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}"); Console.WriteLine($"Summary: {weatherForecast?.Summary}"); } } } Do you have a solution for my problem or a better solution? I appreciate all your help. Thanks Sorry about my English if it's not good, because I'm not fluent in English and use google translate to translate it A: To begin with, if you want to read information from appSettings.json, you should explore more into reading configurations. There are helper classes provided by .Net for the same. Coming back to your code, if you want to use your own code for Json Deserialization, then you need to make the following change to it. var dbConStr = System.Text.Json.JsonSerializer.Deserialize<DBConnectionString>(element.GetRawText(), opt); where, element according to code shared in the question is defined as System.Text.Json.JsonElement element = root.GetProperty("ConnectionStrings"); This ensures the Raw Json associated with the JsonElement ConnectStrings is de-serialized. However, I recommend you to read more into Reading configurations using the IConfiguration and related .Net helpers. A: There are a few issues with the code you've provided. Firstly, the DBConnectionString class is missing the JsonPropertyName attribute on the ConnStr property. This attribute is necessary for the System.Text.Json serializer to correctly map the property to the corresponding JSON property. You should update your class as follows: internal class DBConnectionString { [JsonPropertyName("ConnStr")] public string ConnStr { get; set; } [JsonPropertyName("ProviderName")] public string ProviderName { get; set; } public DBConnectionString() { } } Secondly, you're trying to deserialize the JSON file twice. In the first case, you're using the JsonDocument class to get the ConnectionStrings property of the root element and then you're trying to deserialize the entire JSON file again to a DBConnectionString object. Instead, you should simply deserialize the ConnectionStrings property to a DBConnectionString object directly, like this: System.Text.Json.JsonSerializerOptions opt = new System.Text.Json.JsonSerializerOptions() { AllowTrailingCommas = true, PropertyNameCaseInsensitive = true }; System.Text.Json.JsonElement root = document.RootElement; System.Text.Json.JsonElement element = root.GetProperty("ConnectionStrings"); var dbConStr = System.Text.Json.JsonSerializer.Deserialize<DBConnectionString>(element.ToString(), opt); With these changes, your code should work correctly and you should be able to deserialize the JSON file to a DBConnectionString object as expected.
Reading a json file asynchronously, the object property results are always null
I have a Json file, it contains connectionstring. I want to asynchronously read the file and deserialize it to a ConnectionString object and I always get a null result. I'm using .NET Core 6 and System.Text.Json. Here is contents of my Json file: { "ConnectionStrings": { "ConnStr": "Data Source=(local);Initial Catalog=MyData;Integrated Security=False;TrustServerCertificate=True;Persist Security Info=False;Async=True;MultipleActiveResultSets=true;User ID=sa;Password=MySecret;", "ProviderName": "SQLServer" } } Here are the contents of my classes: internal class DBConnectionString { [JsonPropertyName("ConnStr")] public string ConnStr { get; set; } [JsonPropertyName("ProviderName")] public string ProviderName { get; set; } public DBConnectionString() { } } public class DBConnStr { private static string AppSettingFilePath => "appsettings.json"; public static async Task<string> GetConnectionStringAsync() { string connStr = ""; if (File.Exists((DBConnStr.AppSettingFilePath))) { using (FileStream sr = new FileStream(AppSettingFilePath, FileMode.Open, FileAccess.Read)) { //string json = await sr.ReadToEndAsync(); System.Text.Json.JsonDocumentOptions docOpt = new System.Text.Json.JsonDocumentOptions() { AllowTrailingCommas = true }; using (var document = await System.Text.Json.JsonDocument.ParseAsync(sr, docOpt)) { System.Text.Json.JsonSerializerOptions opt = new System.Text.Json.JsonSerializerOptions() { AllowTrailingCommas = true, PropertyNameCaseInsensitive = true }; System.Text.Json.JsonElement root = document.RootElement; System.Text.Json.JsonElement element = root.GetProperty("ConnectionStrings"); sr.Position = 0; var dbConStr = await System.Text.Json.JsonSerializer.DeserializeAsync<DBConnectionString>(sr, opt); if (dbConStr != null) { connStr = dbConStr.ConnStr; } } } } return connStr; } } The following is the syntax that I use to call the GetConnectionStringAsync method: string ConnectionString = DBConnStr.GetConnectionStringAsync().Result; When the application is running in debug mode, I checked, on line var dbConStr = await System.Text.Json.JsonSerializer.DeserializeAsync(sr, opt); The DBConnectionString object property is always empty. I also tried the reference on the Microsoft website, https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-6-0 but it doesn't work succeed. using System.Text.Json; namespace DeserializeFromFileAsync { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static async Task Main() { string fileName = "WeatherForecast.json"; using FileStream openStream = File.OpenRead(fileName); WeatherForecast? weatherForecast = await JsonSerializer.DeserializeAsync<WeatherForecast>(openStream); Console.WriteLine($"Date: {weatherForecast?.Date}"); Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}"); Console.WriteLine($"Summary: {weatherForecast?.Summary}"); } } } Do you have a solution for my problem or a better solution? I appreciate all your help. Thanks Sorry about my English if it's not good, because I'm not fluent in English and use google translate to translate it
[ "To begin with, if you want to read information from appSettings.json, you should explore more into reading configurations. There are helper classes provided by .Net for the same.\nComing back to your code, if you want to use your own code for Json Deserialization, then you need to make the following change to it.\nvar dbConStr = System.Text.Json.JsonSerializer.Deserialize<DBConnectionString>(element.GetRawText(), opt);\n\nwhere, element according to code shared in the question is defined as\nSystem.Text.Json.JsonElement element = root.GetProperty(\"ConnectionStrings\");\n\n\nThis ensures the Raw Json associated with the JsonElement ConnectStrings is de-serialized.\nHowever, I recommend you to read more into Reading configurations using the IConfiguration and related .Net helpers.\n", "There are a few issues with the code you've provided. Firstly, the DBConnectionString class is missing the JsonPropertyName attribute on the ConnStr property. This attribute is necessary for the System.Text.Json serializer to correctly map the property to the corresponding JSON property. You should update your class as follows:\ninternal class DBConnectionString\n{\n [JsonPropertyName(\"ConnStr\")]\n public string ConnStr { get; set; }\n\n [JsonPropertyName(\"ProviderName\")]\n public string ProviderName { get; set; }\n\n public DBConnectionString()\n {\n\n }\n}\n\nSecondly, you're trying to deserialize the JSON file twice. In the first case, you're using the JsonDocument class to get the ConnectionStrings property of the root element and then you're trying to deserialize the entire JSON file again to a DBConnectionString object. Instead, you should simply deserialize the ConnectionStrings property to a DBConnectionString object directly, like this:\nSystem.Text.Json.JsonSerializerOptions opt = new System.Text.Json.JsonSerializerOptions() { AllowTrailingCommas = true, PropertyNameCaseInsensitive = true };\n\nSystem.Text.Json.JsonElement root = document.RootElement;\nSystem.Text.Json.JsonElement element = root.GetProperty(\"ConnectionStrings\");\n\nvar dbConStr = System.Text.Json.JsonSerializer.Deserialize<DBConnectionString>(element.ToString(), opt);\n\nWith these changes, your code should work correctly and you should be able to deserialize the JSON file to a DBConnectionString object as expected.\n" ]
[ 0, 0 ]
[]
[]
[ "asp.net_core", "c#" ]
stackoverflow_0074671673_asp.net_core_c#.txt
Q: Parse date in pandas with unit='D' What is wrong with this? pd.to_datetime('2022-01-01',unit='D') If I do it without the unit pd.to_datetime('2022-01-01') no error is raised. However, insted of the standard unit ns I rather want D. A: There is a quite clear description and examples on the official documentaiton. Let's take an example from it: pd.to_datetime([1, 2, 3], unit='D', origin=pd.Timestamp('1960-01-01')) Output: DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None) What has happened here? Basically we are taking origin as the base date, and this list in the beginning as a… multiplier? By unit='D' we set it to days, no problem, let's see how it behaves on a different list: pd.to_datetime([0, 30, 64], unit='D', origin=pd.Timestamp('1960-01-01')) Output: DatetimeIndex(['1960-01-01', '1960-01-31', '1960-03-05'], dtype='datetime64[ns]', freq=None) Now look. 0 means there is no change. 30 means we are adding 30 days to our starting date. Finally 64 means we are adding 64 days to our base date. Let's do it in Excel: var value Base= 01-01-60 +64 05-03-60 So, feels legit, does not it? Let's try it on some different unit, e.g. s which stands for seconds: pd.to_datetime([0, 30, 64], unit='s', origin=pd.Timestamp('1960-01-01')) Output: DatetimeIndex(['1960-01-01 00:00:00', '1960-01-01 00:00:30', '1960-01-01 00:01:04'], dtype='datetime64[ns]', freq=None) That was expected. Basically same thing, we are rather taking the base value, or add 30 seconds or get 00:01:04 by adding 64 seconds To sum it up You are misusing this unit= key, it's meant to add up to the base datetime by providing a list of values of how much you want to add up. Your date should be featured in origin= key as origin='2022-01-01'. If you don't want this functionality and you want to cast this value to a day, than look at the other answer. Basically: pd.to_datetime('2022-01-01', format='%Y-%m-%d').day Output: 1 One is the first day of Jan 2022. Update From the comments I remember you wanted to cast you datetime with seconds to date. You can do it with .ceil('1D').
Parse date in pandas with unit='D'
What is wrong with this? pd.to_datetime('2022-01-01',unit='D') If I do it without the unit pd.to_datetime('2022-01-01') no error is raised. However, insted of the standard unit ns I rather want D.
[ "There is a quite clear description and examples on the official documentaiton.\nLet's take an example from it:\npd.to_datetime([1, 2, 3], unit='D',\n origin=pd.Timestamp('1960-01-01'))\n\nOutput:\nDatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None)\n\nWhat has happened here? Basically we are taking origin as the base date, and this list in the beginning as a… multiplier? By unit='D' we set it to days, no problem, let's see how it behaves on a different list:\npd.to_datetime([0, 30, 64], unit='D',\n origin=pd.Timestamp('1960-01-01'))\n\nOutput:\nDatetimeIndex(['1960-01-01', '1960-01-31', '1960-03-05'], dtype='datetime64[ns]', freq=None)\n\nNow look. 0 means there is no change.\n30 means we are adding 30 days to our starting date.\nFinally 64 means we are adding 64 days to our base date.\nLet's do it in Excel:\n\n\n\n\nvar\nvalue\n\n\n\n\nBase=\n01-01-60\n\n\n+64\n05-03-60\n\n\n\n\n\nSo, feels legit, does not it?\nLet's try it on some different unit, e.g. s which stands for seconds:\npd.to_datetime([0, 30, 64], unit='s',\n origin=pd.Timestamp('1960-01-01'))\n\nOutput:\nDatetimeIndex(['1960-01-01 00:00:00', '1960-01-01 00:00:30',\n '1960-01-01 00:01:04'],\n dtype='datetime64[ns]', freq=None)\n\nThat was expected. Basically same thing, we are rather taking the base value, or add 30 seconds or get 00:01:04 by adding 64 seconds\nTo sum it up\nYou are misusing this unit= key, it's meant to add up to the base datetime by providing a list of values of how much you want to add up. Your date should be featured in origin= key as origin='2022-01-01'.\nIf you don't want this functionality and you want to cast this value to a day, than look at the other answer. Basically:\npd.to_datetime('2022-01-01', format='%Y-%m-%d').day\n\nOutput:\n1\n\nOne is the first day of Jan 2022.\nUpdate\nFrom the comments I remember you wanted to cast you datetime with seconds to date. You can do it with .ceil('1D').\n" ]
[ 1 ]
[]
[]
[ "datetime", "pandas", "parsing", "python", "timestamp" ]
stackoverflow_0074671728_datetime_pandas_parsing_python_timestamp.txt
Q: Changing bash PS1 colors ruins bash command line Hi I am using Fedora 37 and came across next problem. Adding export PS1="\e[43;39m[\t]\w\r\n[\u@\h]\\$\e[40m \[$(tput sgr0)\]" to my .bashrc file in /home/username in my case led up to this unexpected behaviour. As I start typing bash commands and fill the whole line the characters don't go to the next line but just continue to get outprinted in the same line overriding the content at the begging of the line. As example: 1 I'm not really familiar with bash syntax so I would appreciate help from a fellow expert. A: As pynexj indicated, you need braces. However, the tput is probably nullifying more than you expect. You should keep it simple with the basic escape sequence. Also you have "[40m" in your original string. I believe that was a mistype and should be "[0m", which is the sequence for "reset attributes". Try using this instead: export PS1="\[\e[43;39m\][\t]\w\r\n[\u@\h]\\$\[\e[0m\]" Also, I would personally use ";30m" instead of ";39m". The corresponding definition would be: export PS1="\[\e[43;30m\][\t]\w\r\n[\u@\h]\\$\[\e[0m\]" For comparison, on Ubuntu MATE 20.04, the .bashrc definition is: export PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ " Since I experienced the same problem using your original string, I can explain what happened. As you let the input buffer fill, it wrapped-around early, before reaching the terminal width, and this for the distance equivalent to the count of characters that were not properly "framed" by the square brackets. Not being framed properly, while not visible, they were counted as part of the linewidth for line buffer character count, so it did a "carriage return" to column one, overwriting what was there. Because of that, the curses logic didn't encounter the "line end" condition, so it did not kick in for the expected linefeed.
Changing bash PS1 colors ruins bash command line
Hi I am using Fedora 37 and came across next problem. Adding export PS1="\e[43;39m[\t]\w\r\n[\u@\h]\\$\e[40m \[$(tput sgr0)\]" to my .bashrc file in /home/username in my case led up to this unexpected behaviour. As I start typing bash commands and fill the whole line the characters don't go to the next line but just continue to get outprinted in the same line overriding the content at the begging of the line. As example: 1 I'm not really familiar with bash syntax so I would appreciate help from a fellow expert.
[ "As pynexj indicated, you need braces. However, the tput is probably nullifying more than you expect. You should keep it simple with the basic escape sequence.\nAlso you have \"[40m\" in your original string. I believe that was a mistype and should be \"[0m\", which is the sequence for \"reset attributes\".\nTry using this instead:\nexport PS1=\"\\[\\e[43;39m\\][\\t]\\w\\r\\n[\\u@\\h]\\\\$\\[\\e[0m\\]\"\n\nAlso, I would personally use \";30m\" instead of \";39m\". The corresponding definition would be:\nexport PS1=\"\\[\\e[43;30m\\][\\t]\\w\\r\\n[\\u@\\h]\\\\$\\[\\e[0m\\]\"\n\nFor comparison, on Ubuntu MATE 20.04, the .bashrc definition is:\nexport PS1=\"\\[\\e]0;${debian_chroot:+($debian_chroot)}\\u@\\h: \\w\\a\\]\\[\\033[01;32m\\]\\u@\\h\\[\\033[00m\\]:\\[\\033[01;34m\\]\\w\\[\\033[00m\\]\\$ \"\n\nSince I experienced the same problem using your original string, I can explain what happened.\nAs you let the input buffer fill, it wrapped-around early, before reaching the terminal width, and this for the distance equivalent to the count of characters that were not properly \"framed\" by the square brackets. Not being framed properly, while not visible, they were counted as part of the linewidth for line buffer character count, so it did a \"carriage return\" to column one, overwriting what was there. Because of that, the curses logic didn't encounter the \"line end\" condition, so it did not kick in for the expected linefeed.\n" ]
[ 0 ]
[]
[]
[ "bash", "colors", "ps1" ]
stackoverflow_0074666770_bash_colors_ps1.txt
Q: Solving an ODE with a Time-Dependent Variable For the 2 systems of ODE, I am using RK4 to solve. From 0 <= t <= 30, b is a constant. But at t >= 30, b is a time-dependent variable where b = 1.2 * exp(-0.5 * (t - 30)). I tried to implement it, but there's an error saying setting an array element with a sequence. How should I implement the time-variable? a = 0.05 b = 1.2 def fA(A, F, t): return -A + a * F + A**2 * F def fF(A, F, t): return b - a * F - A**2 * F h = 0.1 t = np.arange(0, 100 + h, h) A = np.zeros(t.shape) F = np.zeros(t.shape) A[0] = 1 F[0] = 1 for i in range(len(t) - 1): if t[i] >= 30: b = 1.2 * np.exp(-0.5 * (t - 30)) # <-- error here kA1 = fA(A[i], F[i], t[i]) kF1 = fF(A[i], F[i], t[i]) kA2 = fA(A[i] + h * kA1 / 2, F[i] + h * kF1 / 2, t[i] + h / 2) kF2 = fF(A[i] + h * kA1 / 2, F[i] + h * kF1 / 2, t[i] + h / 2) kA3 = fA(A[i] + h * kA2 / 2, F[i] + h * kF2 / 2, t[i] + h / 2) kF3 = fF(A[i] + h * kA2 / 2, F[i] + h * kF2 / 2, t[i] + h / 2) kA4 = fA(A[i] + h * kA3 / 2, F[i] + h * kF3 / 2, t[i] + h / 2) kF4 = fF(A[i] + h * kA3 / 2, F[i] + h * kF3 / 2, t[i] + h / 2) kA = (kA1 + 2 * kA2 + 2 * kA3 + kA4) / 6 kF = (kF1 + 2 * kF2 + 2 * kF3 + kF4) / 6 A[i + 1] = A[i] + h * kA F[i + 1] = F[i] + h * kF plt.plot(t, A) plt.plot(t, F) A: In the first code I use the integrator developed in scipy.integrate.solve_ivp from scipy. Code 1. ########################################## # AUTHOR : CARLOS DUARDO DA SILVA LIMA # # DATE : 03/12/2022 # # LANGUAGE: python # # IDE : GOOGLE COLAB # # CODE 1 : # ########################################## import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint, solve_ivp # Ordinary Differential Equations a = 0.05 b = 1.20 def B(t): return 1.2*np.exp(-0.5*(t-30)) def f(t,r): x,y=r if t>=0 and t<=30: ode1 = -x+a*y+x**2*y ode2 = b-a*y-x**2*y s = np.array([ode1,ode2]) return s elif t>30: b_ = B(t) ode1 = -x+a*y+x**2*y ode2 = b_-a*y-x**2*y s = np.array([ode1,ode2]) return s # Time t0<=t<=tf ti = 0.0 tf = 100.0 t = np.array([ti,tf]) # Initial conditions x0 = 1.0 y0 = 1.0 r0 = np.array([x0,y0]) # Solving the set of ordinary differential equations (Initial Value Problem) #sol = solve_ivp(f, t_span = t, y0 = r0,method='Radau', rtol=1E-09, atol=1e-09) #sol = solve_ivp(f, t_span = t, y0 = r0,method='DOP853', rtol=1E-09, atol=1e-09) #sol = solve_ivp(f, t_span = t, y0 = r0,method='RK23', rtol=1E-09, atol=1e-09) sol = solve_ivp(f, t_span = t, y0 = r0,method='RK45', rtol=1E-09, atol=1e-09) t_= sol.t x = sol.y[0, :] y = sol.y[1, :] # graphic plt.figure(figsize = (8,8)) plt.style.use('dark_background') plt.title('scipy.integrate.solve_ivp - RK45') plt.plot(t_,x,'y.',t_,y,'g.') plt.xlabel('t') plt.ylabel('x, y') plt.legend(['x', 'y'], shadow=True) plt.grid(lw = 0.95,color = 'white',linestyle = '--') plt.show() Figure 1: Output graph using scipy.integrate.solve_ivp In the second code I try to solve the problem following his reasoning, creating the fourth order Runge-Kutta method in the initial value problem. Heads up! The initial conditions for x0 and y0 were informed and I use them in both codes (code 1 and code 2), x0 = 1.0 and y0 = 1.0. ########################################## # AUTHOR : CARLOS DUARDO DA SILVA LIMA # # DATE : 03/12/2022 # # LANGUAGE: python # # IDE : GOOGLE COLAB # # CODE 2 : # ########################################## import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint, solve_ivp # Ordinary Differential Equations a = 0.05 b = 1.20 def B(t): return 1.2*np.exp(-0.5*(t-30)) def f(t,x,y): if t>=0 and t<=30: ode1 = -x+a*y+x**2*y ode2 = b-a*y-x**2*y s = np.array([ode1,ode2]) return s elif t>30: b_ = B(t) ode1 = -x+a*y+x**2*y ode2 = b_-a*y-x**2*y s = np.array([ode1,ode2]) return s # Initial conditions ti = 0.0 x0 = 1.0 y0 = 1.0 N = 1000000 h = 1E-4 # Step t = np.zeros(N) x = np.zeros(N) y = np.zeros(N) t[0] = ti x[0] = x0 y[0] = y0 for i in range(0,N-1,1): k11 = h*f(t[i],x[i],y[i])[0] k12 = h*f(t[i],x[i],y[i])[1] k21 = h*f(t[i]+(h/2),x[i]+(k11/2),y[i]+(k12/2))[0] k22 = h*f(t[i]+(h/2),x[i]+(k11/2),y[i]+(k12/2))[1] k31 = h*f(t[i]+(h/2),x[i]+(k21/2),y[i]+(k22/2))[0] k32 = h*f(t[i]+(h/2),x[i]+(k21/2),y[i]+(k22/2))[1] k41 = h*f(t[i]+h,x[i]+k31,y[i]+k32)[0] k42 = h*f(t[i]+h,x[i]+k31,y[i]+k32)[1] x[i+1] = x[i] + ((k11+2*(k21+k31)+k41)/6) y[i+1] = y[i] + ((k12+2*(k22+k32)+k42)/6) t[i+1] = t[i] + h # graphic t_ = t plt.figure(figsize = (8,8)) plt.style.use('dark_background') plt.title('4-Order Runge-Kutta') plt.plot(t_,x,'r.',t_,y,'b.') plt.xlabel('t') plt.ylabel('x, y') plt.legend(['x', 'y'], shadow=True) plt.grid(lw = 0.95,color = 'white',linestyle = '--') plt.show() Figure 2: Output graph 4-Order Runge-Kutta In case you don't want to be limited only between 0<=t<=30, we can use a simple logic, like. def f(t,r): x,y=r if t>=30: b_ = B(t) ode1 = -x+a*y+x**2*y ode2 = b_-a*y-x**2*y s = np.array([ode1,ode2]) return s else: ode1 = -x+a*y+x**2*y ode2 = b-a*y-x**2*y s = np.array([ode1,ode2]) return s You can apply them to both of the above codes by replacing the function f, bounded between 0<=t<=30 and t>30. One last note! I replaced variables A and F with x and y. Up until :).
Solving an ODE with a Time-Dependent Variable
For the 2 systems of ODE, I am using RK4 to solve. From 0 <= t <= 30, b is a constant. But at t >= 30, b is a time-dependent variable where b = 1.2 * exp(-0.5 * (t - 30)). I tried to implement it, but there's an error saying setting an array element with a sequence. How should I implement the time-variable? a = 0.05 b = 1.2 def fA(A, F, t): return -A + a * F + A**2 * F def fF(A, F, t): return b - a * F - A**2 * F h = 0.1 t = np.arange(0, 100 + h, h) A = np.zeros(t.shape) F = np.zeros(t.shape) A[0] = 1 F[0] = 1 for i in range(len(t) - 1): if t[i] >= 30: b = 1.2 * np.exp(-0.5 * (t - 30)) # <-- error here kA1 = fA(A[i], F[i], t[i]) kF1 = fF(A[i], F[i], t[i]) kA2 = fA(A[i] + h * kA1 / 2, F[i] + h * kF1 / 2, t[i] + h / 2) kF2 = fF(A[i] + h * kA1 / 2, F[i] + h * kF1 / 2, t[i] + h / 2) kA3 = fA(A[i] + h * kA2 / 2, F[i] + h * kF2 / 2, t[i] + h / 2) kF3 = fF(A[i] + h * kA2 / 2, F[i] + h * kF2 / 2, t[i] + h / 2) kA4 = fA(A[i] + h * kA3 / 2, F[i] + h * kF3 / 2, t[i] + h / 2) kF4 = fF(A[i] + h * kA3 / 2, F[i] + h * kF3 / 2, t[i] + h / 2) kA = (kA1 + 2 * kA2 + 2 * kA3 + kA4) / 6 kF = (kF1 + 2 * kF2 + 2 * kF3 + kF4) / 6 A[i + 1] = A[i] + h * kA F[i + 1] = F[i] + h * kF plt.plot(t, A) plt.plot(t, F)
[ "In the first code I use the integrator developed in scipy.integrate.solve_ivp from scipy.\nCode 1.\n##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 03/12/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# CODE 1 : #\n##########################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint, solve_ivp\n\n# Ordinary Differential Equations\na = 0.05\nb = 1.20\n\ndef B(t):\n return 1.2*np.exp(-0.5*(t-30))\n\ndef f(t,r):\n x,y=r\n if t>=0 and t<=30:\n ode1 = -x+a*y+x**2*y\n ode2 = b-a*y-x**2*y\n s = np.array([ode1,ode2])\n return s\n elif t>30:\n b_ = B(t)\n ode1 = -x+a*y+x**2*y\n ode2 = b_-a*y-x**2*y\n s = np.array([ode1,ode2])\n return s\n\n# Time t0<=t<=tf\nti = 0.0\ntf = 100.0\nt = np.array([ti,tf])\n\n# Initial conditions\nx0 = 1.0\ny0 = 1.0\nr0 = np.array([x0,y0])\n\n# Solving the set of ordinary differential equations (Initial Value Problem)\n#sol = solve_ivp(f, t_span = t, y0 = r0,method='Radau', rtol=1E-09, atol=1e-09)\n#sol = solve_ivp(f, t_span = t, y0 = r0,method='DOP853', rtol=1E-09, atol=1e-09)\n#sol = solve_ivp(f, t_span = t, y0 = r0,method='RK23', rtol=1E-09, atol=1e-09)\nsol = solve_ivp(f, t_span = t, y0 = r0,method='RK45', rtol=1E-09, atol=1e-09)\n\nt_= sol.t\nx = sol.y[0, :]\ny = sol.y[1, :]\n\n# graphic\nplt.figure(figsize = (8,8))\nplt.style.use('dark_background')\nplt.title('scipy.integrate.solve_ivp - RK45')\nplt.plot(t_,x,'y.',t_,y,'g.')\nplt.xlabel('t')\nplt.ylabel('x, y')\nplt.legend(['x', 'y'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\nFigure 1: Output graph using scipy.integrate.solve_ivp\nIn the second code I try to solve the problem following his reasoning, creating the fourth order Runge-Kutta method in the initial value problem. Heads up! The initial conditions for x0 and y0 were informed and I use them in both codes (code 1 and code 2), x0 = 1.0 and y0 = 1.0.\n##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 03/12/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# CODE 2 : #\n##########################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint, solve_ivp\n\n# Ordinary Differential Equations\na = 0.05\nb = 1.20\n\ndef B(t):\n return 1.2*np.exp(-0.5*(t-30))\n\ndef f(t,x,y):\n if t>=0 and t<=30:\n ode1 = -x+a*y+x**2*y\n ode2 = b-a*y-x**2*y\n s = np.array([ode1,ode2])\n return s\n elif t>30:\n b_ = B(t)\n ode1 = -x+a*y+x**2*y\n ode2 = b_-a*y-x**2*y\n s = np.array([ode1,ode2])\n return s\n\n# Initial conditions\nti = 0.0\nx0 = 1.0\ny0 = 1.0\nN = 1000000\nh = 1E-4 # Step\n\nt = np.zeros(N)\nx = np.zeros(N)\ny = np.zeros(N)\nt[0] = ti\nx[0] = x0\ny[0] = y0\n\nfor i in range(0,N-1,1):\n k11 = h*f(t[i],x[i],y[i])[0]\n k12 = h*f(t[i],x[i],y[i])[1]\n\n k21 = h*f(t[i]+(h/2),x[i]+(k11/2),y[i]+(k12/2))[0]\n k22 = h*f(t[i]+(h/2),x[i]+(k11/2),y[i]+(k12/2))[1]\n\n k31 = h*f(t[i]+(h/2),x[i]+(k21/2),y[i]+(k22/2))[0]\n k32 = h*f(t[i]+(h/2),x[i]+(k21/2),y[i]+(k22/2))[1]\n\n k41 = h*f(t[i]+h,x[i]+k31,y[i]+k32)[0]\n k42 = h*f(t[i]+h,x[i]+k31,y[i]+k32)[1]\n\n x[i+1] = x[i] + ((k11+2*(k21+k31)+k41)/6)\n y[i+1] = y[i] + ((k12+2*(k22+k32)+k42)/6)\n t[i+1] = t[i] + h \n\n# graphic\nt_ = t\nplt.figure(figsize = (8,8))\nplt.style.use('dark_background')\nplt.title('4-Order Runge-Kutta')\nplt.plot(t_,x,'r.',t_,y,'b.')\nplt.xlabel('t')\nplt.ylabel('x, y')\nplt.legend(['x', 'y'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\nFigure 2: Output graph 4-Order Runge-Kutta\nIn case you don't want to be limited only between 0<=t<=30, we can use a simple logic, like.\ndef f(t,r):\n x,y=r\n if t>=30:\n b_ = B(t)\n ode1 = -x+a*y+x**2*y\n ode2 = b_-a*y-x**2*y\n s = np.array([ode1,ode2])\n return s\n else:\n ode1 = -x+a*y+x**2*y\n ode2 = b-a*y-x**2*y\n s = np.array([ode1,ode2])\n return s\n\nYou can apply them to both of the above codes by replacing the function f, bounded between 0<=t<=30 and t>30. One last note! I replaced variables A and F with x and y. Up until :).\n" ]
[ 0 ]
[]
[]
[ "math", "ode", "python" ]
stackoverflow_0074647657_math_ode_python.txt
Q: Reading invalid data from dynamic array, maybe its logical problem but i don`t see it pls help, thx for your time Task is: create dynamic array, enter data in it and use data for calculation. The error is in the condition declaration line of the second "for" loop. Error code:"С6385", error text:"reading invalid data" #include <iostream> using namespace std; double s, u, h; int i = 0; s = 0; int main(){ int ar_size; cout << "Enter array size" << endl; cin >> ar_size; int* a = new int[ar_size]; for (int i = 0; i < ar_size; i++) { cout << "Enter array data" << endl; cin >> a[i]; cout << "Value of " << i << " element is " << a[i] << endl; //check data for (i = 0; a[i] > 0 && a[i] < 3.14; i++) { //problem here, error code:"С6385", error text:"reading invalid data" u = 2 * cos(a[i]); h = 1 - 2 * sin(a[i]); s = s + u / h; cout << "When i = " << i << "\t" << "s = " << s << endl; } } } A: I changed it to doubles because that seems more like you application but you had to many i's going on and needed a if block not a for loop. hope this helps #include<iostream> #include<cmath> using namespace std; double u, h, s = {}; int main() { int ar_size; cout << "Enter array size" << endl; cin >> ar_size; double* a = new double[ar_size]; cin.clear(); cin.ignore(); for (int i = 0; i < ar_size; i++) { cout << "Enter array data" << endl; string input; getline(cin, input); a[i] = stod(input); cout << "Value of " << i << " element is " << a[i] << endl; if(a[i] > 0 && a[i] < 3.14) { u = 2 * cos(a[i]); h = 1 - 2 * sin(a[i]); s = s + u / h; cout << "When i = " << a[i] << "\t" << "s = " << s << endl; } else { cout << "out of bounds\n"; } } }
Reading invalid data from dynamic array, maybe its logical problem but i don`t see it
pls help, thx for your time Task is: create dynamic array, enter data in it and use data for calculation. The error is in the condition declaration line of the second "for" loop. Error code:"С6385", error text:"reading invalid data" #include <iostream> using namespace std; double s, u, h; int i = 0; s = 0; int main(){ int ar_size; cout << "Enter array size" << endl; cin >> ar_size; int* a = new int[ar_size]; for (int i = 0; i < ar_size; i++) { cout << "Enter array data" << endl; cin >> a[i]; cout << "Value of " << i << " element is " << a[i] << endl; //check data for (i = 0; a[i] > 0 && a[i] < 3.14; i++) { //problem here, error code:"С6385", error text:"reading invalid data" u = 2 * cos(a[i]); h = 1 - 2 * sin(a[i]); s = s + u / h; cout << "When i = " << i << "\t" << "s = " << s << endl; } } }
[ "I changed it to doubles because that seems more like you application but you had to many i's going on and needed a if block not a for loop. hope this helps\n#include<iostream>\n#include<cmath>\n\nusing namespace std;\n\ndouble u, h, s = {};\n\nint main()\n{\n int ar_size;\n cout << \"Enter array size\" << endl;\n cin >> ar_size;\n double* a = new double[ar_size];\n cin.clear();\n cin.ignore();\n \n for (int i = 0; i < ar_size; i++)\n {\n cout << \"Enter array data\" << endl;\n string input;\n getline(cin, input);\n a[i] = stod(input);\n cout << \"Value of \" << i << \" element is \" << a[i] << endl;\n if(a[i] > 0 && a[i] < 3.14)\n {\n u = 2 * cos(a[i]);\n h = 1 - 2 * sin(a[i]);\n s = s + u / h;\n cout << \"When i = \" << a[i] << \"\\t\" << \"s = \" << s << endl;\n }\n else\n {\n cout << \"out of bounds\\n\";\n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "c++" ]
stackoverflow_0074671805_arrays_c++.txt
Q: Why my flask app can't handle more than one client? I created a simple flask application that needs authentication to have access to the data. When I run this application locally it works fine (accepts more than one client), however when I host the app on railway or heroku it can't handle more than one client. Ex: when I access the URL on a computer and log in, if I access the URL on my cellphone (different netowrk) I get to have access to that account logged in. I'm using the latest version of flask and using flask_login to manage authentication. Does anyone have any idea why it's happening? I've tried everything I found out on Internet, such as using app.run(threaded=True) I've also set the numbers of workers on gunicorn command for exemple Does anyone have any idea why it's happening? A: As official Flask's documentation says, never run your application in production in dev mode (what app.run() actually is). Please refer to this section if you are going to deploy in self-hosted machine: https://flask.palletsprojects.com/en/2.2.x/deploying/ And if you are going to deploy to Heroku, you need to prepare for correct Procfile, like this: web: gunicorn run:app
Why my flask app can't handle more than one client?
I created a simple flask application that needs authentication to have access to the data. When I run this application locally it works fine (accepts more than one client), however when I host the app on railway or heroku it can't handle more than one client. Ex: when I access the URL on a computer and log in, if I access the URL on my cellphone (different netowrk) I get to have access to that account logged in. I'm using the latest version of flask and using flask_login to manage authentication. Does anyone have any idea why it's happening? I've tried everything I found out on Internet, such as using app.run(threaded=True) I've also set the numbers of workers on gunicorn command for exemple Does anyone have any idea why it's happening?
[ "As official Flask's documentation says, never run your application in production in dev mode (what app.run() actually is).\nPlease refer to this section if you are going to deploy in self-hosted machine: https://flask.palletsprojects.com/en/2.2.x/deploying/\nAnd if you are going to deploy to Heroku, you need to prepare for correct Procfile, like this:\nweb: gunicorn run:app\n\n" ]
[ 0 ]
[]
[]
[ "flask", "gunicorn", "heroku", "python" ]
stackoverflow_0074671705_flask_gunicorn_heroku_python.txt
Q: Julia Jump : Getting all feasible solutions to mip I would like to have instead of only the vector of optimal solution to a mip , all the feasible (suboptimal) vectors. I found some old questions here, but I am not sure how they work. First of all, is there any new library tool/way to do that automatically ? I tried this but, it did nothing: if termination_status(m) == MOI.FEASIBLE_POINT println(x) end optimize!(m); If not, what's the easiest way? I thought of scanning the optimal solution till I find the first non -zero decision variable, then constraint this variable to be zero and solving the model again. for i in 1:active_variables if value.(z[i])==1 @constraint(m, x[i] == 0) break end end optimize!(m); But I see this problem with this method** : Ιf I constraint x[i] to be zero, in the next step I will want maybe to drop again this constraint? This comes down to whether there can exist two(or more) different solutions in which x[i]==1 A: JuMP supports returning multiple solutions. Documentation: https://jump.dev/JuMP.jl/stable/manual/solutions/#Multiple-solutions The workflow is something like: using JuMP model = Model() @variable(model, x[1:10] >= 0) # ... other constraints ... optimize!(model) if termination_status(model) != OPTIMAL error("The model was not solved correctly.") end an_optimal_solution = value.(x; result = 1) optimal_objective = objective_value(model; result = 1) for i in 2:result_count(model) @assert has_values(model; result = i) println("Solution $(i) = ", value.(x; result = i)) obj = objective_value(model; result = i) println("Objective $(i) = ", obj) if isapprox(obj, optimal_objective; atol = 1e-8) print("Solution $(i) is also optimal!") end end But you need a solver that supports returning multiple solutions, and to configure the right solver-specific options. See this blog post: https://jump.dev/tutorials/2021/11/02/tutorial-multi-jdf/ A: The following is an example of all-solution finder for a boolean problem. Such problems are easier to handle since the solution space is easily enumerated (even though it can still grow exponentially big). First, let's get the packages and define the sample problem: using Random, JuMP, HiGHS, MathOptInterface function example_knapsack() profit = [5, 3, 2, 7, 4] weight = [2, 8, 4, 2, 5] capacity = 10 minprofit = 10 model = Model(HiGHS.Optimizer) set_silent(model) @variable(model, x[1:5], Bin) @objective(model, FEASIBILITY_SENSE, 0) @constraint(model, weight' * x <= capacity) @constraint(model, profit' * x >= minprofit) return model end (it is a knapsack problem from the JuMP docs). Next, we use recursion to explore the tree of all possible solutions. The tree does not go down branches with no solution (so the running time is not always exponential): function findallsol(model, x) perm = shuffle(1:length(x)) res = Vector{Float64}[] _findallsol!(res, model, x, perm, 0) return res end function _findallsol!(res, model, x, perm, depth) n = length(x) depth > n && return optimize!(model) if termination_status(model) == MathOptInterface.OPTIMAL if depth == n push!(res, value.(x)) return else idx = perm[depth+1] v = value(x[idx]) newcon = @constraint(model, x[idx] == v) _findallsol!(res, model, x, perm, depth + 1) delete(model, newcon) newcon = @constraint(model, x[idx] == 1 - v) _findallsol!(res, model, x, perm, depth + 1) delete(model, newcon) end end return end Now we can: julia> m = example_knapsack() A JuMP Model Maximization problem with: Variables: 5 ... Names registered in the model: x julia> res = findallsol(m, m.obj_dict[:x]) 5-element Vector{Vector{Float64}}: [1.0, 0.0, 0.0, 1.0, 1.0] [0.0, 0.0, 0.0, 1.0, 1.0] [1.0, 0.0, 1.0, 1.0, 0.0] [1.0, 0.0, 0.0, 1.0, 0.0] [0.0, 1.0, 0.0, 1.0, 0.0] And we get a vector with all the solutions. If the problem in question is a boolean problem, this method might be used, as is. In case it has non-boolean variables, the recursion will have to split the feasible space in some even fashion. For example, choosing a variable and cutting its domain in half, and recursing to each half with a smaller domain on this variable (to ensure termination). P.S. This is not the optimal method. This problem has been well studied. Possible terms to search for are 'model counting' (especially in the boolean domain).
Julia Jump : Getting all feasible solutions to mip
I would like to have instead of only the vector of optimal solution to a mip , all the feasible (suboptimal) vectors. I found some old questions here, but I am not sure how they work. First of all, is there any new library tool/way to do that automatically ? I tried this but, it did nothing: if termination_status(m) == MOI.FEASIBLE_POINT println(x) end optimize!(m); If not, what's the easiest way? I thought of scanning the optimal solution till I find the first non -zero decision variable, then constraint this variable to be zero and solving the model again. for i in 1:active_variables if value.(z[i])==1 @constraint(m, x[i] == 0) break end end optimize!(m); But I see this problem with this method** : Ιf I constraint x[i] to be zero, in the next step I will want maybe to drop again this constraint? This comes down to whether there can exist two(or more) different solutions in which x[i]==1
[ "JuMP supports returning multiple solutions.\nDocumentation: https://jump.dev/JuMP.jl/stable/manual/solutions/#Multiple-solutions\nThe workflow is something like:\nusing JuMP\nmodel = Model()\n@variable(model, x[1:10] >= 0)\n# ... other constraints ...\noptimize!(model)\n\nif termination_status(model) != OPTIMAL\n error(\"The model was not solved correctly.\")\nend\n\nan_optimal_solution = value.(x; result = 1)\noptimal_objective = objective_value(model; result = 1)\nfor i in 2:result_count(model)\n @assert has_values(model; result = i)\n println(\"Solution $(i) = \", value.(x; result = i))\n obj = objective_value(model; result = i)\n println(\"Objective $(i) = \", obj)\n if isapprox(obj, optimal_objective; atol = 1e-8)\n print(\"Solution $(i) is also optimal!\")\n end\nend\n\nBut you need a solver that supports returning multiple solutions, and to configure the right solver-specific options.\nSee this blog post: https://jump.dev/tutorials/2021/11/02/tutorial-multi-jdf/\n", "The following is an example of all-solution finder for a boolean problem. Such problems are easier to handle since the solution space is easily enumerated (even though it can still grow exponentially big).\nFirst, let's get the packages and define the sample problem:\nusing Random, JuMP, HiGHS, MathOptInterface\n\nfunction example_knapsack()\n profit = [5, 3, 2, 7, 4]\n weight = [2, 8, 4, 2, 5]\n capacity = 10\n minprofit = 10\n model = Model(HiGHS.Optimizer)\n set_silent(model)\n @variable(model, x[1:5], Bin)\n @objective(model, FEASIBILITY_SENSE, 0)\n @constraint(model, weight' * x <= capacity)\n @constraint(model, profit' * x >= minprofit)\n return model\nend\n\n(it is a knapsack problem from the JuMP docs).\nNext, we use recursion to explore the tree of all possible solutions. The tree does not go down branches with no solution (so the running time is not always exponential):\nfunction findallsol(model, x)\n perm = shuffle(1:length(x))\n res = Vector{Float64}[]\n _findallsol!(res, model, x, perm, 0)\n return res\nend\n\nfunction _findallsol!(res, model, x, perm, depth)\n n = length(x)\n depth > n && return\n optimize!(model)\n if termination_status(model) == MathOptInterface.OPTIMAL\n if depth == n\n push!(res, value.(x))\n return\n else\n idx = perm[depth+1]\n v = value(x[idx])\n newcon = @constraint(model, x[idx] == v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n newcon = @constraint(model, x[idx] == 1 - v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n end\n end\n return\nend\n\nNow we can:\njulia> m = example_knapsack()\nA JuMP Model\nMaximization problem with:\nVariables: 5\n...\nNames registered in the model: x\n\njulia> res = findallsol(m, m.obj_dict[:x])\n5-element Vector{Vector{Float64}}:\n [1.0, 0.0, 0.0, 1.0, 1.0]\n [0.0, 0.0, 0.0, 1.0, 1.0]\n [1.0, 0.0, 1.0, 1.0, 0.0]\n [1.0, 0.0, 0.0, 1.0, 0.0]\n [0.0, 1.0, 0.0, 1.0, 0.0]\n\nAnd we get a vector with all the solutions.\nIf the problem in question is a boolean problem, this method might be used, as is. In case it has non-boolean variables, the recursion will have to split the feasible space in some even fashion. For example, choosing a variable and cutting its domain in half, and recursing to each half with a smaller domain on this variable (to ensure termination).\nP.S. This is not the optimal method. This problem has been well studied. Possible terms to search for are 'model counting' (especially in the boolean domain).\n" ]
[ 4, 2 ]
[]
[]
[ "julia", "julia_jump", "mixed_integer_programming", "optimization" ]
stackoverflow_0074660418_julia_julia_jump_mixed_integer_programming_optimization.txt
Q: Web app using youtube_player_iframe, video won't play if it's the only one in the playlist I’m trying to understand why youtube_player_iframe 3.1.0 isn’t working for me. I used the sample app verbatim from here except I modified initState() to add my video to the playlist (and changed startSeconds to 0). (The unmodified sample app works fine.) If my video is the only one in the playlist the YouTube thumbnail doesn't appear and clicking 'play' fails with "An error occurred. Please try again later. (Playback ID: qpAJu2DzWFdK9whg)". However, if I add another video to the playlist my video works fine. (Very strange.) The test video I'm using also describes the problem (with screenshots) https://youtu.be/FC4x8mdbbXE. This initState() FAILS: @override void initState() { super.initState(); _controller = YoutubePlayerController( params: const YoutubePlayerParams( showControls: true, mute: false, showFullscreenButton: true, loop: false, ), ) ..onInit = () { _controller.loadPlaylist( list: [ 'FC4x8mdbbXE', // <-- if my video is the only one in the list is does NOT work // 'tcodrIK2P_I', // 'nPt8bK2gbaU', // 'K18cpp_-gP8', // 'iLnmTe5Q2Qw', // '_WoCV4c6XOE', // 'KmzdUe0RSJo', // '6jZDSSZZxjQ', // 'p2lYr3vM_1w', // '7QUtEmBT_-w', // '34_PXCzGw1M', ], listType: ListType.playlist, startSeconds: 0, ); } ..onFullscreenChange = (isFullScreen) { log('${isFullScreen ? 'Entered' : 'Exited'} Fullscreen.'); }; } This initState() WORKS: @override void initState() { super.initState(); _controller = YoutubePlayerController( params: const YoutubePlayerParams( showControls: true, mute: false, showFullscreenButton: true, loop: false, ), ) ..onInit = () { _controller.loadPlaylist( list: [ 'FC4x8mdbbXE', // <-- my video 'tcodrIK2P_I', // <-- if there's at least one other video in the list mine works // 'nPt8bK2gbaU', // 'K18cpp_-gP8', // 'iLnmTe5Q2Qw', // '_WoCV4c6XOE', // 'KmzdUe0RSJo', // '6jZDSSZZxjQ', // 'p2lYr3vM_1w', // '7QUtEmBT_-w', // '34_PXCzGw1M', ], listType: ListType.playlist, startSeconds: 0, ); } ..onFullscreenChange = (isFullScreen) { log('${isFullScreen ? 'Entered' : 'Exited'} Fullscreen.'); }; } A: This appears to be a bug in the playlist feature of youtube_player_iframe (or perhaps an underlying library). For anyone who, like me, ran across this issue because you just used the example to play a single YouTube video (and, like me, didn't bother to look at the other methods), there's an easy work-around, just replace loadPlaylist() with cueVideoById() followed by playVideo(). @override void initState() { super.initState(); _controller = YoutubePlayerController( params: const YoutubePlayerParams( showControls: true, mute: false, showFullscreenButton: true, loop: false, ), )..onInit = () { _controller.cueVideoById(videoId: 'xxxxxx'); // your YouTube video id _controller.playVideo(); }; setState(() {}); }); }
Web app using youtube_player_iframe, video won't play if it's the only one in the playlist
I’m trying to understand why youtube_player_iframe 3.1.0 isn’t working for me. I used the sample app verbatim from here except I modified initState() to add my video to the playlist (and changed startSeconds to 0). (The unmodified sample app works fine.) If my video is the only one in the playlist the YouTube thumbnail doesn't appear and clicking 'play' fails with "An error occurred. Please try again later. (Playback ID: qpAJu2DzWFdK9whg)". However, if I add another video to the playlist my video works fine. (Very strange.) The test video I'm using also describes the problem (with screenshots) https://youtu.be/FC4x8mdbbXE. This initState() FAILS: @override void initState() { super.initState(); _controller = YoutubePlayerController( params: const YoutubePlayerParams( showControls: true, mute: false, showFullscreenButton: true, loop: false, ), ) ..onInit = () { _controller.loadPlaylist( list: [ 'FC4x8mdbbXE', // <-- if my video is the only one in the list is does NOT work // 'tcodrIK2P_I', // 'nPt8bK2gbaU', // 'K18cpp_-gP8', // 'iLnmTe5Q2Qw', // '_WoCV4c6XOE', // 'KmzdUe0RSJo', // '6jZDSSZZxjQ', // 'p2lYr3vM_1w', // '7QUtEmBT_-w', // '34_PXCzGw1M', ], listType: ListType.playlist, startSeconds: 0, ); } ..onFullscreenChange = (isFullScreen) { log('${isFullScreen ? 'Entered' : 'Exited'} Fullscreen.'); }; } This initState() WORKS: @override void initState() { super.initState(); _controller = YoutubePlayerController( params: const YoutubePlayerParams( showControls: true, mute: false, showFullscreenButton: true, loop: false, ), ) ..onInit = () { _controller.loadPlaylist( list: [ 'FC4x8mdbbXE', // <-- my video 'tcodrIK2P_I', // <-- if there's at least one other video in the list mine works // 'nPt8bK2gbaU', // 'K18cpp_-gP8', // 'iLnmTe5Q2Qw', // '_WoCV4c6XOE', // 'KmzdUe0RSJo', // '6jZDSSZZxjQ', // 'p2lYr3vM_1w', // '7QUtEmBT_-w', // '34_PXCzGw1M', ], listType: ListType.playlist, startSeconds: 0, ); } ..onFullscreenChange = (isFullScreen) { log('${isFullScreen ? 'Entered' : 'Exited'} Fullscreen.'); }; }
[ "This appears to be a bug in the playlist feature of youtube_player_iframe (or perhaps an underlying library). For anyone who, like me, ran across this issue because you just used the example to play a single YouTube video (and, like me, didn't bother to look at the other methods), there's an easy work-around, just replace loadPlaylist() with cueVideoById() followed by playVideo().\n@override\n void initState() {\n super.initState();\n _controller = YoutubePlayerController(\n params: const YoutubePlayerParams(\n showControls: true,\n mute: false,\n showFullscreenButton: true,\n loop: false,\n ),\n )..onInit = () {\n _controller.cueVideoById(videoId: 'xxxxxx'); // your YouTube video id\n _controller.playVideo();\n };\n setState(() {});\n });\n }\n\n" ]
[ 0 ]
[]
[]
[ "youtube_player_flutter" ]
stackoverflow_0074652422_youtube_player_flutter.txt
Q: Triangulation Plot python curved scattered data I'm trying to get a interpolated contour surface with triangulation from matplotlib. My data looks like a curve and I can't get rid of the data below the curve. I would like to have the outside datapoints as boundaries. I got the code from this tutorial import matplotlib.tri as tri fig, (ax1, ax2) = plt.subplots(nrows=2) xi = np.linspace(-10,150,2000) yi = np.linspace(-10,60,2000) triang = tri.Triangulation(x_after, y_after) interpolator = tri.LinearTriInterpolator(triang, strain_after) Xi, Yi = np.meshgrid(xi, yi) zi = interpolator(Xi, Yi) ax1.triplot(triang, 'ro-', lw=5) ax1.contour(xi, yi, zi, levels=30, linewidths=0.5, colors='k') cntr1 = ax1.contourf(xi, yi, zi, levels=30, cmap="jet") fig.colorbar(cntr1, ax=ax1) ax1.plot(x_after, y_after, 'ko', ms=3) ax2.tricontour(x_after, y_after, strain_after, levels=30, linewidths=0.5, colors='k') cntr2 = ax2.tricontourf(x_after, y_after, strain_after, levels=30, cmap="jet") fig.colorbar(cntr2, ax=ax2) ax2.plot(x_after, y_after, 'ko', ms=3) plt.subplots_adjust(hspace=0.5) plt.show() I found the option to mask the data with this code, but I can't figure out how to define the mask to get what I want triang.set_mask() These are the values for the inner curve: x_after y_after z_after strain_after 39 117.2757 8.7586 0.1904 7.164 40 119.9474 7.152 0.1862 6.6456 37 111.8319 12.0568 0.1671 6.273 38 114.5314 10.4186 0.1651 5.7309 41 122.7482 5.4811 0.1617 9.1563 36 108.8823 13.4417 0.1421 8.8683 42 125.5035 3.8309 0.141 9.7385 33 99.8064 17.6315 0.1357 9.8613 32 96.8869 18.6449 0.1197 4.4147 35 105.8846 14.6086 0.1079 7.7055 28 84.2221 22.0191 0.1076 6.2098 26 77.8689 23.158 0.1067 7.5833 29 87.354 21.2974 0.1044 11.4365 27 81.0778 22.6443 0.1019 8.3794 24 71.4004 23.7749 0.0968 8.6207 34 102.8772 15.9558 0.0959 18.2025 23 68.2124 23.962 0.0939 7.9201 25 74.6905 23.4465 0.0901 9.0361 30 90.5282 20.398 0.0864 14.1051 31 93.802 19.335 0.0794 10.4563 43 128.3489 2.1002 0.0689 9.0292 22 65.0282 24.1107 0.0654 7.99 21 61.7857 24.0129 0.0543 8.2589 20 58.5831 23.9527 0.0407 9.0087 0 -0.0498 -0.5159 0.0308 7.1073 19 55.3115 23.7794 0.0251 9.6441 5 12.5674 9.3369 0.0203 7.2051 2 4.8147 3.6074 0.0191 8.0103 1 2.363 1.5329 0.0184 7.8285 18 52.0701 23.526 0.016 8.0149 3 7.4067 5.5988 0.0111 8.9994 7 18.2495 12.5836 0.0098 9.771 9 23.9992 15.4145 0.0098 6.7995 16 45.5954 22.5274 0.0098 12.9428 4 9.9776 7.5563 0.0093 6.9804 17 48.9177 23.0669 0.0084 9.3782 13 35.9812 20.0588 0.0066 9.6005 6 15.3578 11.0027 0.0062 9.7801 15 42.2909 21.8663 0.0052 12.0288 11 29.816 17.8723 0.0049 8.9085 8 21.1241 14.0893 0.0032 6.5716 10 26.8691 16.7093 0.0014 6.9672 44 131.1371 0.4155 0.0 11.9578 14 39.0687 20.991 -0.0008 9.9907 12 32.9645 18.9796 -0.0102 9.3389 45 134.083 -1.3928 -0.0616 15.29 A: I managed to find a way to not plot the triangles at the bottom by using the following code: xtri = x_after[triangles] - np.roll(x_after[triangles], 1, axis=1) ytri = y_after[triangles] - np.roll(y_after[triangles], 1, axis=1) maxi = np.max(np.sqrt(xtri**2 + ytri**2), axis=1) max_radius = 4.5 triang.set_mask(maxi > max_radius) A: Most of my code is devoted to build the x, y arrays and the list of triangles in terms of the numbering of the nodes, but I suppose that you already have (or at least you can get) a list of triangles from the mesher program that you have used... if you have the triangles it's as simple as plt.tricontourf(x, y, triangles, z). And here it is the code complete of the boring stuff. import matplotlib.pyplot as plt import numpy as np th0 = th2 = np.linspace(-0.5, 0.5, 21) th1 = np.linspace(-0.475, 0.475, 20) r = np.array((30, 31, 32)) x = np.concatenate(( np.sin(th0)*r[0], np.sin(th1)*r[1], np.sin(th2)*r[2])) y = np.concatenate(( np.cos(th0)*r[0], np.cos(th1)*r[1], np.cos(th2)*r[2])) z = np.sin(x)-np.cos(y) nodes0 = np.arange( 0, 21, dtype=int) nodes1 = np.arange(21, 41, dtype=int) nodes2 = np.arange(41, 62, dtype=int) triangles = np.vstack(( np.vstack((nodes0[:-1],nodes0[1:],nodes1)).T, np.vstack((nodes0[1:-1],nodes1[1:],nodes1[:-1])).T, np.vstack((nodes2[:-1],nodes1,nodes2[1:])).T, np.vstack((nodes1[:-1],nodes1[1:],nodes2[1:-1])).T, (0, 21, 41), (20, 61, 40) )) fig, ax = plt.subplots() ax.set_aspect(1) tp = ax.triplot(x, y, triangles, color='k', lw=0.5, zorder=4) tc = ax.tricontourf(x, y, triangles, np.sin(x)-np.cos(y)) plt.colorbar(tc, location='bottom') plt.show()
Triangulation Plot python curved scattered data
I'm trying to get a interpolated contour surface with triangulation from matplotlib. My data looks like a curve and I can't get rid of the data below the curve. I would like to have the outside datapoints as boundaries. I got the code from this tutorial import matplotlib.tri as tri fig, (ax1, ax2) = plt.subplots(nrows=2) xi = np.linspace(-10,150,2000) yi = np.linspace(-10,60,2000) triang = tri.Triangulation(x_after, y_after) interpolator = tri.LinearTriInterpolator(triang, strain_after) Xi, Yi = np.meshgrid(xi, yi) zi = interpolator(Xi, Yi) ax1.triplot(triang, 'ro-', lw=5) ax1.contour(xi, yi, zi, levels=30, linewidths=0.5, colors='k') cntr1 = ax1.contourf(xi, yi, zi, levels=30, cmap="jet") fig.colorbar(cntr1, ax=ax1) ax1.plot(x_after, y_after, 'ko', ms=3) ax2.tricontour(x_after, y_after, strain_after, levels=30, linewidths=0.5, colors='k') cntr2 = ax2.tricontourf(x_after, y_after, strain_after, levels=30, cmap="jet") fig.colorbar(cntr2, ax=ax2) ax2.plot(x_after, y_after, 'ko', ms=3) plt.subplots_adjust(hspace=0.5) plt.show() I found the option to mask the data with this code, but I can't figure out how to define the mask to get what I want triang.set_mask() These are the values for the inner curve: x_after y_after z_after strain_after 39 117.2757 8.7586 0.1904 7.164 40 119.9474 7.152 0.1862 6.6456 37 111.8319 12.0568 0.1671 6.273 38 114.5314 10.4186 0.1651 5.7309 41 122.7482 5.4811 0.1617 9.1563 36 108.8823 13.4417 0.1421 8.8683 42 125.5035 3.8309 0.141 9.7385 33 99.8064 17.6315 0.1357 9.8613 32 96.8869 18.6449 0.1197 4.4147 35 105.8846 14.6086 0.1079 7.7055 28 84.2221 22.0191 0.1076 6.2098 26 77.8689 23.158 0.1067 7.5833 29 87.354 21.2974 0.1044 11.4365 27 81.0778 22.6443 0.1019 8.3794 24 71.4004 23.7749 0.0968 8.6207 34 102.8772 15.9558 0.0959 18.2025 23 68.2124 23.962 0.0939 7.9201 25 74.6905 23.4465 0.0901 9.0361 30 90.5282 20.398 0.0864 14.1051 31 93.802 19.335 0.0794 10.4563 43 128.3489 2.1002 0.0689 9.0292 22 65.0282 24.1107 0.0654 7.99 21 61.7857 24.0129 0.0543 8.2589 20 58.5831 23.9527 0.0407 9.0087 0 -0.0498 -0.5159 0.0308 7.1073 19 55.3115 23.7794 0.0251 9.6441 5 12.5674 9.3369 0.0203 7.2051 2 4.8147 3.6074 0.0191 8.0103 1 2.363 1.5329 0.0184 7.8285 18 52.0701 23.526 0.016 8.0149 3 7.4067 5.5988 0.0111 8.9994 7 18.2495 12.5836 0.0098 9.771 9 23.9992 15.4145 0.0098 6.7995 16 45.5954 22.5274 0.0098 12.9428 4 9.9776 7.5563 0.0093 6.9804 17 48.9177 23.0669 0.0084 9.3782 13 35.9812 20.0588 0.0066 9.6005 6 15.3578 11.0027 0.0062 9.7801 15 42.2909 21.8663 0.0052 12.0288 11 29.816 17.8723 0.0049 8.9085 8 21.1241 14.0893 0.0032 6.5716 10 26.8691 16.7093 0.0014 6.9672 44 131.1371 0.4155 0.0 11.9578 14 39.0687 20.991 -0.0008 9.9907 12 32.9645 18.9796 -0.0102 9.3389 45 134.083 -1.3928 -0.0616 15.29
[ "I managed to find a way to not plot the triangles at the bottom by using the following code:\nxtri = x_after[triangles] - np.roll(x_after[triangles], 1, axis=1)\nytri = y_after[triangles] - np.roll(y_after[triangles], 1, axis=1)\nmaxi = np.max(np.sqrt(xtri**2 + ytri**2), axis=1)\nmax_radius = 4.5\ntriang.set_mask(maxi > max_radius)\n\n\n", "\nMost of my code is devoted to build the x, y arrays and the list of triangles in terms of the numbering of the nodes, but I suppose that you already have (or at least you can get) a list of triangles from the mesher program that you have used... if you have the triangles it's as simple as plt.tricontourf(x, y, triangles, z).\nAnd here it is the code complete of the boring stuff.\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nth0 = th2 = np.linspace(-0.5, 0.5, 21)\nth1 = np.linspace(-0.475, 0.475, 20)\nr = np.array((30, 31, 32))\n\nx = np.concatenate(( np.sin(th0)*r[0], \n np.sin(th1)*r[1],\n np.sin(th2)*r[2]))\ny = np.concatenate(( np.cos(th0)*r[0], \n np.cos(th1)*r[1],\n np.cos(th2)*r[2]))\n\nz = np.sin(x)-np.cos(y)\n\nnodes0 = np.arange( 0, 21, dtype=int)\nnodes1 = np.arange(21, 41, dtype=int)\nnodes2 = np.arange(41, 62, dtype=int)\n\ntriangles = np.vstack((\n np.vstack((nodes0[:-1],nodes0[1:],nodes1)).T,\n np.vstack((nodes0[1:-1],nodes1[1:],nodes1[:-1])).T,\n np.vstack((nodes2[:-1],nodes1,nodes2[1:])).T,\n np.vstack((nodes1[:-1],nodes1[1:],nodes2[1:-1])).T,\n (0, 21, 41),\n (20, 61, 40)\n ))\n\nfig, ax = plt.subplots()\nax.set_aspect(1)\ntp = ax.triplot(x, y, triangles, color='k', lw=0.5, zorder=4)\ntc = ax.tricontourf(x, y, triangles, np.sin(x)-np.cos(y))\nplt.colorbar(tc, location='bottom')\nplt.show()\n\n" ]
[ 0, 0 ]
[]
[]
[ "interpolation", "matplotlib", "python", "triangulation" ]
stackoverflow_0074659764_interpolation_matplotlib_python_triangulation.txt
Q: Handle Error With Axios Async/Await in React I'm using Axios to fetch some data: export const getProducts = async () => { try { const { data } = await axios.get(`/api/products`) return data } catch (err) { console.log(err) return err } } Everything is fine, but I need to catch http errors inside try block. For example, when connection with the server is lost, Axios returns an AxiosError object: AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code: "ERR_BAD_REQUEST" config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message: "Request failed with status code 404" name: "AxiosError" request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response: {data: '\n\n\n<meta char…re>Cannot GET /api/prducts\n\n\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …} stack: "AxiosError: Request failed with status code 404\n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)" [[Prototype]]: Error The problem is: I want to render a div saying "There was an error fetching the data" if there is an error. If not, render a table with products as usual. I call my function like this: const productsArr = await getProducts() How can I recognize if productsArr is a valid product array, or an AxiosError? A: You can see in the official docs how to handle errors: https://axios-http.com/docs/handling_errors To see the error if no response was received (copied from the axios docs) else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); You can wrap your component with an error-handling boundary. You can either create your component which will wrap your other component in which the error occurs using the componentDidCatch lifecycle method, which is the same as using catch{} inside try-catch https://reactjs.org/docs/react-component.html#componentdidcatch. Or use a popular npm package https://www.npmjs.com/package/react-error-boundary A: I used this structure for fetching: export const getProducts = async () => { try { const { data } = await axios.get(/api/products) return data } catch (err) { console.log(err) return err } } I deleted the return in the catch block. So if an error happens, it returns undefined. I imported getProducts to my component. I did the fetching like this: useEffect(() => { (async function () { const productsArr = await getProducts() if (productsArr) { setProducts(productsArr) setLoading(false) } else { setLoading(false) setError(true) } })() }, []) So, I use conditional to validate if productsArr exist. If there was an error, since the fetching returns undefined, I activate setError(true). It is not the best solution, because I lose access to the error data. I hope there is a better solution.
Handle Error With Axios Async/Await in React
I'm using Axios to fetch some data: export const getProducts = async () => { try { const { data } = await axios.get(`/api/products`) return data } catch (err) { console.log(err) return err } } Everything is fine, but I need to catch http errors inside try block. For example, when connection with the server is lost, Axios returns an AxiosError object: AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code: "ERR_BAD_REQUEST" config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message: "Request failed with status code 404" name: "AxiosError" request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response: {data: '\n\n\n<meta char…re>Cannot GET /api/prducts\n\n\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …} stack: "AxiosError: Request failed with status code 404\n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)" [[Prototype]]: Error The problem is: I want to render a div saying "There was an error fetching the data" if there is an error. If not, render a table with products as usual. I call my function like this: const productsArr = await getProducts() How can I recognize if productsArr is a valid product array, or an AxiosError?
[ "You can see in the official docs how to handle errors: https://axios-http.com/docs/handling_errors\nTo see the error if no response was received (copied from the axios docs)\nelse if (error.request) {\n // The request was made but no response was received\n // `error.request` is an instance of XMLHttpRequest in the browser and an instance of\n // http.ClientRequest in node.js\n console.log(error.request);\n\nYou can wrap your component with an error-handling boundary. You can either create your component which will wrap your other component in which the error occurs using the componentDidCatch lifecycle method, which is the same as using catch{} inside try-catch https://reactjs.org/docs/react-component.html#componentdidcatch. Or use a popular npm package https://www.npmjs.com/package/react-error-boundary\n", "I used this structure for fetching:\nexport const getProducts = async () => {\n\ntry {\nconst { data } = await axios.get(/api/products)\nreturn data\n} catch (err) {\nconsole.log(err)\nreturn err\n}\n}\nI deleted the return in the catch block. So if an error happens, it returns undefined.\nI imported getProducts to my component. I did the fetching like this:\nuseEffect(() => {\n (async function () {\n const productsArr = await getProducts()\n if (productsArr) {\n setProducts(productsArr)\n setLoading(false)\n } else {\n setLoading(false)\n setError(true)\n }\n })()\n}, [])\n\nSo, I use conditional to validate if productsArr exist. If there was an error, since the fetching returns undefined, I activate setError(true).\nIt is not the best solution, because I lose access to the error data. I hope there is a better solution.\n" ]
[ 0, 0 ]
[]
[]
[ "axios", "error_handling", "http", "reactjs" ]
stackoverflow_0074657824_axios_error_handling_http_reactjs.txt
Q: Allow PHP to read GET with RewriteRule RewriteRule ^cards/([^/]*)/([^/]*)$ /cards/?name=$1&page=$2 [L] Hi. I have this inside my .htaccess. If I add ?extra=1 to the end of the url and then var_dump, it doesn't read the $_GET['extra']; Is there a flag that works? I saw here some extra flags but none seems of any use in this particular situation. A: I saw here some extra flags but none seems of any use in this particular situation. If you are expecting the query string on the original request to be merged with the query string in the RewriteRule substitution (2nd argument of the RewriteRule directive) then you need to add the QSA flag (Query String Append) to your rule. The default behaviour is that any query string in the substitution will override the request. However, you should be rewriting to the actual file that handles the request, not the directory (and presumably expecting mod_dir to issue an internal subrequest for the directory index). For example: RewriteRule ^cards/([^/]+)/([^/]*)$ /cards/index.php?name=$1&page=$2 [QSA,L] Aside: I also changed the first quantifier from * to + since the path segment cannot be empty for the rule to be successful.
Allow PHP to read GET with RewriteRule
RewriteRule ^cards/([^/]*)/([^/]*)$ /cards/?name=$1&page=$2 [L] Hi. I have this inside my .htaccess. If I add ?extra=1 to the end of the url and then var_dump, it doesn't read the $_GET['extra']; Is there a flag that works? I saw here some extra flags but none seems of any use in this particular situation.
[ "\nI saw here some extra flags but none seems of any use in this particular situation.\n\nIf you are expecting the query string on the original request to be merged with the query string in the RewriteRule substitution (2nd argument of the RewriteRule directive) then you need to add the QSA flag (Query String Append) to your rule. The default behaviour is that any query string in the substitution will override the request.\nHowever, you should be rewriting to the actual file that handles the request, not the directory (and presumably expecting mod_dir to issue an internal subrequest for the directory index).\nFor example:\nRewriteRule ^cards/([^/]+)/([^/]*)$ /cards/index.php?name=$1&page=$2 [QSA,L]\n\nAside: I also changed the first quantifier from * to + since the path segment cannot be empty for the rule to be successful.\n" ]
[ 0 ]
[]
[]
[ ".htaccess", "mod_rewrite" ]
stackoverflow_0074667877_.htaccess_mod_rewrite.txt
Q: What does the parent tag in Maven pom represent? E.g.: <parent> <groupId>mycompany.trade.com</groupId> <artifactId>mycompany.trade.</artifactId> <version>1.1.1.0-SNAPSHOT</version> </parent> Does it mean that Maven will search for parent pom? If yes, where, in which order? May be in folder up 1 level? Or in local repository or in repo? A: Yes, maven reads the parent POM from your local repository (or proxies like nexus) and creates an 'effective POM' by merging the information from parent and module POM. See also Introduction to the POM One reason to use a parent is that you have a central place to store information about versions of artifacts, compiler-settings etc. that should be used in all modules. A: The common dependencies,Properties,constants etc can be definded in central parent project pom.xml The main important thing is the parent project cannot be distributed and it looks quite similar to a regular "pom.xml" except that it also has a packaging tag <groupId>com.company.demo</groupId> <artifactId>MavenInheritance</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> The child now able to inherit this using <parent> <groupId>com.company.demo</groupId> <artifactId>MavenInheritance</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> A: As the name suggests, we can point out a parent pom.xml file for the current pom.xml file. Doing so, dependencies, properties, constants and many more defined at the parent pom.xml file also get merged with the current pom.xml (child pom.xml) file. Say you have a parent tag in your projects pom.xml that looks like below: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> </parent> Then maven reads that parent POM from your local repository (or from repository managers like sonatype, jfrog, etc that you have configured) and creates a Resultant POM by combining the parent POM and your module’s POM. To see the combined result use the following mvn command: mvn help:effective-pom A: This is the practice that is used in multi-modules projects where we need to inherit the dependencies from the parent projects.
What does the parent tag in Maven pom represent?
E.g.: <parent> <groupId>mycompany.trade.com</groupId> <artifactId>mycompany.trade.</artifactId> <version>1.1.1.0-SNAPSHOT</version> </parent> Does it mean that Maven will search for parent pom? If yes, where, in which order? May be in folder up 1 level? Or in local repository or in repo?
[ "Yes, maven reads the parent POM from your local repository (or proxies like nexus) and creates an 'effective POM' by merging the information from parent and module POM. \nSee also Introduction to the POM\nOne reason to use a parent is that you have a central place to store information about versions\nof artifacts, compiler-settings etc. that should be used in all modules.\n", "The common dependencies,Properties,constants etc can be definded in central parent project pom.xml\nThe main important thing is the parent project cannot be distributed and it looks quite similar to a regular \"pom.xml\" except that it also has a packaging tag\n <groupId>com.company.demo</groupId>\n <artifactId>MavenInheritance</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>pom</packaging>\n\nThe child now able to inherit this using\n <parent>\n <groupId>com.company.demo</groupId>\n <artifactId>MavenInheritance</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n </parent>\n\n", "As the name suggests, we can point out a parent pom.xml file for the current pom.xml file. Doing so, dependencies, properties, constants and many more defined at the parent pom.xml file also get merged with the current pom.xml (child pom.xml) file. Say you have a parent tag in your projects pom.xml that looks like below:\n<parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.1.8.RELEASE</version>\n</parent>\n\nThen maven reads that parent POM from your local repository (or from repository managers like sonatype, jfrog, etc that you have configured) and creates a Resultant POM by combining the parent POM and your module’s POM.\nTo see the combined result use the following mvn command:\nmvn help:effective-pom \n\n", "This is the practice that is used in multi-modules projects where we need to inherit the dependencies from the parent projects.\n" ]
[ 96, 19, 15, 0 ]
[]
[]
[ "artifact", "directory", "maven", "parent_pom", "pom.xml" ]
stackoverflow_0008026447_artifact_directory_maven_parent_pom_pom.xml.txt
Q: Go app (in docker container) not reflecting changes on page? I'm new to Go, but having an annoying issue where changes in the code are not reflected on the page, unless I do another --build when I bring up the container. Is this normal? I'm running`Windows 10, Go 1.19, AMD, Docker Desktop/Compose. If I change "Hello, World!" to some other string, CTRL+C the running app, and then run docker-compose up, the changes are NOT reflected on the page, even after clearing browser cache and using an incognito window. HOWEVER, if I run docker-compose up --build, the changes WILL be reflected. Reminder I'm new to Go, but is this normal behaviour? Do I have to re-build the project in docker-compose each time to see the changes? Or do you see anything "off" in my code? I'm following a few year old Udemy course, so of course every step there's a new "thing" to troubleshoot as it doesn't work as shown eye roll They suggest using Air for hot-reloading, which I'm also having an issue with as IT'S not working either, however I've opened a GitHub issue for that. Here is the code from the various files: main.go package main import ( "ambassador/src/database" "github.com/gofiber/fiber/v2" ) func main() { // Connect to the database database.Connect() // Migrate tables in the database database.AutoMigrate() // Create a new fiber app, which is based on Express.js app := fiber.New() app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello, World!") }) app.Listen(":3000") } Dockerfile FROM golang:1.19 WORKDIR /app COPY go.mod . COPY go.sum . RUN go mod download COPY . . # Use air for live go hot-reloading # This one doesn't work, use go install instead # RUN curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin # Air does not work for me. Opening github issue. Skip for now # RUN go install github.com/cosmtrek/air@latest # CMD ["air"] CMD ["go", "run", "main.go"] docker-compose.yaml version: '3.9' services: backend: build: . ports: - 8000:3000 # volumes: # - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: ambassador MYSQL_USER: root MYSQL_PASSWORD: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33066:3306 src > database > db.go package database import ( "ambassador/src/models" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB func Connect() { var err error DB, err = gorm.Open(mysql.Open("root:root@tcp(db:3306)/ambassador"), &gorm.Config{}) if err != nil { panic("Could not connect with the database!") } } func AutoMigrate() { DB.AutoMigrate(models.User{}) } src > models > user.go package models type User struct { Id uint FirstName string LastName string Email string Password string IsAmbassador bool } go.mod module ambassador go 1.19 require github.com/gofiber/fiber/v2 v2.36.0 require ( github.com/andybalholm/brotli v1.0.4 // indirect github.com/go-sql-driver/mysql v1.6.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/klauspost/compress v1.15.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.38.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 // indirect gorm.io/driver/mysql v1.3.5 // indirect gorm.io/gorm v1.23.8 // indirect ) The same code is included in this screenshot of my IDE. A: Go isn’t a script language and needs in rebuild and restart application to apply changes You can use Golang fresh for rebuild and restart your app https://github.com/gravityblast/fresh Add this to your Dockerfile RUN go install github.com/pilu/fresh@latest ... CMD [ "fresh" ] A: You are not mounting any files into your container, only copying them once on image build. This is why you are not seeing anychanges unless you build, or copy new files into the container. You've already commented out a volume from your docker-compose.yaml, but if you uncomment those lines you should see that changes are reflected without rebuilding. A: To answer your original question — NO, you DO NOT need to add the --build tag when running up your docker-compose file. It doesn't relate to Go, it relates only to docker containers working logic. If we come to the live-reload problem then the problem is with the technology docker uses for file sharing between a host system and containers. I have had the same issues on mac when tried to use not the Docker Desktop but an alternative like Rancher which even uses docker CLI via moby. When I switched back to the original Docker Desktop which uses gRPC FUSE, osxfs, and VirtioFS — with all of them worked like a charm. I don't know how this feature is implemented on windows, but I'm sure you could dig into this direction.
Go app (in docker container) not reflecting changes on page?
I'm new to Go, but having an annoying issue where changes in the code are not reflected on the page, unless I do another --build when I bring up the container. Is this normal? I'm running`Windows 10, Go 1.19, AMD, Docker Desktop/Compose. If I change "Hello, World!" to some other string, CTRL+C the running app, and then run docker-compose up, the changes are NOT reflected on the page, even after clearing browser cache and using an incognito window. HOWEVER, if I run docker-compose up --build, the changes WILL be reflected. Reminder I'm new to Go, but is this normal behaviour? Do I have to re-build the project in docker-compose each time to see the changes? Or do you see anything "off" in my code? I'm following a few year old Udemy course, so of course every step there's a new "thing" to troubleshoot as it doesn't work as shown eye roll They suggest using Air for hot-reloading, which I'm also having an issue with as IT'S not working either, however I've opened a GitHub issue for that. Here is the code from the various files: main.go package main import ( "ambassador/src/database" "github.com/gofiber/fiber/v2" ) func main() { // Connect to the database database.Connect() // Migrate tables in the database database.AutoMigrate() // Create a new fiber app, which is based on Express.js app := fiber.New() app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello, World!") }) app.Listen(":3000") } Dockerfile FROM golang:1.19 WORKDIR /app COPY go.mod . COPY go.sum . RUN go mod download COPY . . # Use air for live go hot-reloading # This one doesn't work, use go install instead # RUN curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin # Air does not work for me. Opening github issue. Skip for now # RUN go install github.com/cosmtrek/air@latest # CMD ["air"] CMD ["go", "run", "main.go"] docker-compose.yaml version: '3.9' services: backend: build: . ports: - 8000:3000 # volumes: # - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: ambassador MYSQL_USER: root MYSQL_PASSWORD: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33066:3306 src > database > db.go package database import ( "ambassador/src/models" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB func Connect() { var err error DB, err = gorm.Open(mysql.Open("root:root@tcp(db:3306)/ambassador"), &gorm.Config{}) if err != nil { panic("Could not connect with the database!") } } func AutoMigrate() { DB.AutoMigrate(models.User{}) } src > models > user.go package models type User struct { Id uint FirstName string LastName string Email string Password string IsAmbassador bool } go.mod module ambassador go 1.19 require github.com/gofiber/fiber/v2 v2.36.0 require ( github.com/andybalholm/brotli v1.0.4 // indirect github.com/go-sql-driver/mysql v1.6.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/klauspost/compress v1.15.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.38.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 // indirect gorm.io/driver/mysql v1.3.5 // indirect gorm.io/gorm v1.23.8 // indirect ) The same code is included in this screenshot of my IDE.
[ "Go isn’t a script language and needs in rebuild and restart application to apply changes\nYou can use Golang fresh for rebuild and restart your app\nhttps://github.com/gravityblast/fresh\nAdd this to your Dockerfile\nRUN go install github.com/pilu/fresh@latest\n...\nCMD [ \"fresh\" ]\n\n", "You are not mounting any files into your container, only copying them once on image build. This is why you are not seeing anychanges unless you build, or copy new files into the container.\nYou've already commented out a volume from your docker-compose.yaml, but if you uncomment those lines you should see that changes are reflected without rebuilding.\n", "To answer your original question — NO, you DO NOT need to add the --build tag when running up your docker-compose file. It doesn't relate to Go, it relates only to docker containers working logic.\nIf we come to the live-reload problem then the problem is with the technology docker uses for file sharing between a host system and containers.\nI have had the same issues on mac when tried to use not the Docker Desktop but an alternative like Rancher which even uses docker CLI via moby. When I switched back to the original Docker Desktop which uses gRPC FUSE, osxfs, and VirtioFS — with all of them worked like a charm.\nI don't know how this feature is implemented on windows, but I'm sure you could dig into this direction.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "docker_compose", "go" ]
stackoverflow_0073265597_docker_compose_go.txt
Q: Generating a histogram from column values in a database Let's say I have a database column 'grade' like this: |grade| | 1| | 2| | 1| | 3| | 4| | 5| Is there a non-trivial way in SQL to generate a histogram like this? |2,1,1,1,1,0| where 2 means the grade 1 occurs twice, the 1s mean grades {2..5} occur once and 0 means grade 6 does not occur at all. I don't mind if the histogram is one row per count. If that matters, the database is SQL Server accessed by a perl CGI through unixODBC/FreeTDS. EDIT: Thanks for your quick replies! It is okay if non-existing values (like grade 6 in the example above) do not occur as long as I can make out which histogram value belongs to which grade. A: SELECT COUNT(grade) FROM table GROUP BY grade ORDER BY grade Haven't verified it, but it should work.It will not, however, show count for 6s grade, since it's not present in the table at all... A: If there are a lot of data points, you can also group ranges together like this: SELECT FLOOR(grade/5.00)*5 As Grade, COUNT(*) AS [Grade Count] FROM TableName GROUP BY FLOOR(Grade/5.00)*5 ORDER BY 1 Additionally, if you wanted to label the full range, you can get the floor and ceiling ahead of time with a CTE. With GradeRanges As ( SELECT FLOOR(Score/5.00)*5 As GradeFloor, FLOOR(Score/5.00)*5 + 4 As GradeCeiling FROM TableName ) SELECT GradeFloor, CONCAT(GradeFloor, ' to ', GradeCeiling) AS GradeRange, COUNT(*) AS [Grade Count] FROM GradeRanges GROUP BY GradeFloor, CONCAT(GradeFloor, ' to ', GradeCeiling) ORDER BY GradeFloor Note: In some SQL engines, you can GROUP BY an Ordinal Column Index, but with MS SQL, if you want it in the SELECT statement, you're going to need to group by it also, hence copying the Range into the Group Expression as well. Option 2: You could use case statements to selectively count values into arbitrary bins and then unpivot them to get a row by row count of included values A: Use a temp table to get your missing values: CREATE TABLE #tmp(num int) DECLARE @num int SET @num = 0 WHILE @num < 10 BEGIN INSERT #tmp @num SET @num = @num + 1 END SELECT t.num as [Grade], count(g.Grade) FROM gradeTable g RIGHT JOIN #tmp t on g.Grade = t.num GROUP by t.num ORDER BY 1 A: Gamecat's use of DISTINCT seems a little odd to me, will have to try it out when I'm back in the office... The way I would do it is similar though... SELECT [table].grade AS [grade], COUNT(*) AS [occurances] FROM [table] GROUP BY [table].grade ORDER BY [table].grade To overcome the lack of data where there are 0 occurances, you can LEFT JOIN on to a table containing all valid grades. The COUNT(*) will count NULLS, but COUNT(grade) won't count the NULLS. DECLARE @grades TABLE ( val INT ) INSERT INTO @grades VALUES (1) INSERT INTO @grades VALUES (2) INSERT INTO @grades VALUES (3) INSERT INTO @grades VALUES (4) INSERT INTO @grades VALUES (5) INSERT INTO @grades VALUES (6) SELECT [grades].val AS [grade], COUNT([table].grade) AS [occurances] FROM @grades AS [grades] LEFT JOIN [table] ON [table].grade = [grades].val GROUP BY [grades].val ORDER BY [grades].val A: According to Shlomo Priymak's article How to Quickly Create a Histogram in MySQL, you can use the following query: SELECT grade, COUNT(*) AS 'Count', RPAD('', COUNT(*), '*') AS 'Bar' FROM grades GROUP BY grade Which will produce the following table: grade Count Bar 1 2 ** 2 1 * 3 1 * 4 1 * 5 1 * A: select Grade, count(Grade) from MyTable group by Grade A: I am building on what Ilya Volodin did above, that should allow you to select a range of grade you want to group together in your result: DECLARE @cnt INT = 0; WHILE @cnt < 100 -- Set max value BEGIN SELECT @cnt,COUNT(fe) FROM dbo.GEODATA_CB where fe >= @cnt-0.999 and fe <= @cnt+0.999 -- set tolerance SET @cnt = @cnt + 1; -- set step END; A: SELECT FLOOR(grade/5.00)*5 As Grade_Lower, FLOOR(grade/5.00)*5+5 As Grade_Upper COUNT(*) AS [Grade Count] FROM TableName GROUP BY FLOOR(Grade/5.00)*5, FLOOR(grade/5.00)*5+5 ORDER BY 1 Video tutorial if you like https://www.youtube.com/watch?v=ioc-NU4meu8
Generating a histogram from column values in a database
Let's say I have a database column 'grade' like this: |grade| | 1| | 2| | 1| | 3| | 4| | 5| Is there a non-trivial way in SQL to generate a histogram like this? |2,1,1,1,1,0| where 2 means the grade 1 occurs twice, the 1s mean grades {2..5} occur once and 0 means grade 6 does not occur at all. I don't mind if the histogram is one row per count. If that matters, the database is SQL Server accessed by a perl CGI through unixODBC/FreeTDS. EDIT: Thanks for your quick replies! It is okay if non-existing values (like grade 6 in the example above) do not occur as long as I can make out which histogram value belongs to which grade.
[ "SELECT COUNT(grade) FROM table GROUP BY grade ORDER BY grade\n\nHaven't verified it, but it should work.It will not, however, show count for 6s grade, since it's not present in the table at all...\n", "If there are a lot of data points, you can also group ranges together like this:\nSELECT FLOOR(grade/5.00)*5 As Grade, \n COUNT(*) AS [Grade Count]\nFROM TableName\nGROUP BY FLOOR(Grade/5.00)*5\nORDER BY 1\n\nAdditionally, if you wanted to label the full range, you can get the floor and ceiling ahead of time with a CTE. \nWith GradeRanges As (\n SELECT FLOOR(Score/5.00)*5 As GradeFloor, \n FLOOR(Score/5.00)*5 + 4 As GradeCeiling\n FROM TableName\n)\nSELECT GradeFloor,\n CONCAT(GradeFloor, ' to ', GradeCeiling) AS GradeRange,\n COUNT(*) AS [Grade Count]\nFROM GradeRanges\nGROUP BY GradeFloor, CONCAT(GradeFloor, ' to ', GradeCeiling)\nORDER BY GradeFloor\n\nNote: In some SQL engines, you can GROUP BY an Ordinal Column Index, but with MS SQL, if you want it in the SELECT statement, you're going to need to group by it also, hence copying the Range into the Group Expression as well.\nOption 2: You could use case statements to selectively count values into arbitrary bins and then unpivot them to get a row by row count of included values\n", "Use a temp table to get your missing values:\nCREATE TABLE #tmp(num int)\nDECLARE @num int\nSET @num = 0\nWHILE @num < 10\nBEGIN\n INSERT #tmp @num\n SET @num = @num + 1\nEND\n\n\nSELECT t.num as [Grade], count(g.Grade) FROM gradeTable g\nRIGHT JOIN #tmp t on g.Grade = t.num\nGROUP by t.num\nORDER BY 1\n\n", "Gamecat's use of DISTINCT seems a little odd to me, will have to try it out when I'm back in the office...\nThe way I would do it is similar though...\nSELECT\n [table].grade AS [grade],\n COUNT(*) AS [occurances]\nFROM\n [table]\nGROUP BY\n [table].grade\nORDER BY\n [table].grade\n\nTo overcome the lack of data where there are 0 occurances, you can LEFT JOIN on to a table containing all valid grades. The COUNT(*) will count NULLS, but COUNT(grade) won't count the NULLS.\nDECLARE @grades TABLE (\n val INT\n ) \n\nINSERT INTO @grades VALUES (1) \nINSERT INTO @grades VALUES (2) \nINSERT INTO @grades VALUES (3) \nINSERT INTO @grades VALUES (4) \nINSERT INTO @grades VALUES (5) \nINSERT INTO @grades VALUES (6) \n\nSELECT\n [grades].val AS [grade],\n COUNT([table].grade) AS [occurances]\nFROM\n @grades AS [grades]\nLEFT JOIN\n [table]\n ON [table].grade = [grades].val\nGROUP BY\n [grades].val\nORDER BY\n [grades].val\n\n", "According to Shlomo Priymak's article How to Quickly Create a Histogram in MySQL, you can use the following query: \nSELECT grade, \n COUNT(*) AS 'Count',\n RPAD('', COUNT(*), '*') AS 'Bar' \nFROM grades \nGROUP BY grade\n\nWhich will produce the following table:\ngrade Count Bar\n1 2 **\n2 1 *\n3 1 *\n4 1 *\n5 1 *\n\n", "select Grade, count(Grade)\nfrom MyTable\ngroup by Grade\n\n", "I am building on what Ilya Volodin did above, that should allow you to select a range of grade you want to group together in your result:\nDECLARE @cnt INT = 0;\n\nWHILE @cnt < 100 -- Set max value\nBEGIN\nSELECT @cnt,COUNT(fe) FROM dbo.GEODATA_CB where fe >= @cnt-0.999 and fe <= @cnt+0.999 -- set tolerance\nSET @cnt = @cnt + 1; -- set step\nEND;\n\n", "SELECT FLOOR(grade/5.00)*5 As Grade_Lower, \nFLOOR(grade/5.00)*5+5 As Grade_Upper\n COUNT(*) AS [Grade Count]\nFROM TableName\nGROUP BY FLOOR(Grade/5.00)*5, FLOOR(grade/5.00)*5+5\nORDER BY 1\n\nVideo tutorial if you like\nhttps://www.youtube.com/watch?v=ioc-NU4meu8\n" ]
[ 41, 16, 7, 4, 4, 2, 0, 0 ]
[]
[]
[ "histogram", "sql", "sql_server" ]
stackoverflow_0000485409_histogram_sql_sql_server.txt
Q: How to solve the problem 'zsh: command not found: jupyter' I bought Macbook air M1, and I tried to install jupyter notebook with this code. pip3 install --upgrade pip pip3 install jupyter and I tried to open jupyter notebook with this code. jupyter notebook but, then, this code appeared. zsh: command not found: jupyter enter image description here A: First, you need to find where it was installed. pip3 show jupyter | grep Location Example: $ pip3 show pip | grep Location Location: /usr/lib/python3/dist-packages Then you need to ensure that the path you get is in your PATH. Example: $ export PATH=/usr/lib/python3/dist-packages:$PATH A: Try adding Python's bin/ folder path to $PATH variable. You should be able to find it here - /Users/<your-username>/Library/Python/3.x/bin Step 1 : Open .bash_profile in text editor open ~/.bash_profile Step 2 : Add the following line at the end of the file export PATH="/Users/<your-username>/Library/Python/3.x/bin:$PATH" Step 3 : Save the edits made to .bash_profile and restart the terminal
How to solve the problem 'zsh: command not found: jupyter'
I bought Macbook air M1, and I tried to install jupyter notebook with this code. pip3 install --upgrade pip pip3 install jupyter and I tried to open jupyter notebook with this code. jupyter notebook but, then, this code appeared. zsh: command not found: jupyter enter image description here
[ "First, you need to find where it was installed.\npip3 show jupyter | grep Location\n\nExample:\n$ pip3 show pip | grep Location\n\nLocation: /usr/lib/python3/dist-packages\n\nThen you need to ensure that the path you get is in your PATH.\nExample:\n$ export PATH=/usr/lib/python3/dist-packages:$PATH\n\n", "Try adding Python's bin/ folder path to $PATH variable.\nYou should be able to find it here - /Users/<your-username>/Library/Python/3.x/bin\nStep 1 : Open .bash_profile in text editor\nopen ~/.bash_profile\n\nStep 2 : Add the following line at the end of the file\nexport PATH=\"/Users/<your-username>/Library/Python/3.x/bin:$PATH\"\n\nStep 3 : Save the edits made to .bash_profile and restart the terminal\n" ]
[ 6, 0 ]
[]
[]
[ "jupyter", "jupyter_notebook", "macos", "python" ]
stackoverflow_0069614802_jupyter_jupyter_notebook_macos_python.txt
Q: change firebase URL for FirebaseReference in Android get error: client is offline on api 29? I try to change FirebaseReference URL but i get this error com.google.android.gms.tasks.RuntimeExecutionException: java.lang.Exception: Client is offline When i run my code on emulator 33API it work, so i think there is a problem in my syntax. here is my code val database = FirebaseDatabase.getInstance("my url").reference database.child("Iasi").addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { Log.w(ContentValues.TAG, "data ${snapshot.value}") } override fun onCancelled(error: DatabaseError) { Log.w(ContentValues.TAG, "data ${error.message}") } }) i try another way too but still it is not work, i try with .get().addOnCompleteListener and i try with addListenerForSingleValueEvent. Anybody who know what i should do? A: It looks like you are trying to connect to a Firebase database, but the connection is failing with the error "Client is offline". This can happen if the device you are running the app on does not have an active internet connection, or if there is an issue with the Firebase server. To fix this issue, you can try the following steps: Make sure the device you are using has an active internet connection. You can check this by trying to access other websites or services that require an internet connection. Make sure you are using the correct URL for your Firebase database. The URL should be in the form https://[YOUR_FIREBASE_APP_NAME].firebaseio.com. You can find the correct URL in the Firebase console under the "Database" section. Check that the Firebase server is online and functioning properly. You can do this by visiting the Firebase console and checking the status of the service. If there is an outage or other issue, you may need to wait until it is resolved before you can connect to the database. If the above steps do not fix the issue, you can try using a different method to connect to the Firebase database. For example, instead of using addValueEventListener, you can try using addListenerForSingleValueEvent, which will only listen for a single change in the database before disconnecting. I hope this helps! Let me know if you have any other questions.
change firebase URL for FirebaseReference in Android get error: client is offline on api 29?
I try to change FirebaseReference URL but i get this error com.google.android.gms.tasks.RuntimeExecutionException: java.lang.Exception: Client is offline When i run my code on emulator 33API it work, so i think there is a problem in my syntax. here is my code val database = FirebaseDatabase.getInstance("my url").reference database.child("Iasi").addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { Log.w(ContentValues.TAG, "data ${snapshot.value}") } override fun onCancelled(error: DatabaseError) { Log.w(ContentValues.TAG, "data ${error.message}") } }) i try another way too but still it is not work, i try with .get().addOnCompleteListener and i try with addListenerForSingleValueEvent. Anybody who know what i should do?
[ "It looks like you are trying to connect to a Firebase database, but the connection is failing with the error \"Client is offline\". This can happen if the device you are running the app on does not have an active internet connection, or if there is an issue with the Firebase server.\nTo fix this issue, you can try the following steps:\nMake sure the device you are using has an active internet connection. You can check this by trying to access other websites or services that require an internet connection.\nMake sure you are using the correct URL for your Firebase database. The URL should be in the form https://[YOUR_FIREBASE_APP_NAME].firebaseio.com. You can find the correct URL in the Firebase console under the \"Database\" section.\nCheck that the Firebase server is online and functioning properly. You can do this by visiting the Firebase console and checking the status of the service. If there is an outage or other issue, you may need to wait until it is resolved before you can connect to the database.\nIf the above steps do not fix the issue, you can try using a different method to connect to the Firebase database. For example, instead of using addValueEventListener, you can try using addListenerForSingleValueEvent, which will only listen for a single change in the database before disconnecting.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 1 ]
[]
[]
[ "android", "firebase", "firebase_realtime_database", "kotlin" ]
stackoverflow_0074671855_android_firebase_firebase_realtime_database_kotlin.txt
Q: println() not printing a toString() version of a Job object and not erroring out, either I've been going through a Pluralsight course on coroutines in Kotlin, and got stuck on this little example, where I am trying to print out the job object passed into the coroutine context. My understanding is that, when faced with a complex object type, println() will default to a .toString() method or print some sort of an object reference. But what's going on here is that println() isn't printing anything inside of $launchParent, yet, the code execution never reaches println("exiting try block"). I've added a try..catch block, thinking there was an exception, but there wasn't. It's just that nothing gets printed after running that offending println() with the $launchParent in it.I am relatively new to Kotlin and feeling a bit mystified by this. I rebuilt the solution, invalidated the cache and restarted, but it didn't help. Any ideas why the println() with the $launchParent string substitution is bombing like this? import kotlinx.coroutines.* fun main(args: Array<String>) = runBlocking() { println("inside main function within JobsAndChildren module") val launchParent: Job = Job() val scope = CoroutineScope(Job()) val job = scope.launch(launchParent) { println("Inside the CoroutineScope launch block") val j1 = coroutineContext[Job] println("after accessing the job key in the coroutineContext array") try { println("inside the try block") println("job passed to the scope.launch as the new context: $launchParent") //println("job returned from scope.launch as the new job: $j1") println("exiting try block") } catch (e: Exception) { println("inside the catch block") println(e.message) } } } A: runBlocking and main finish execution before scope.launch does, because scope.launch coroutine is not a child of the runBlocking CoroutineScope. Add job.join()
println() not printing a toString() version of a Job object and not erroring out, either
I've been going through a Pluralsight course on coroutines in Kotlin, and got stuck on this little example, where I am trying to print out the job object passed into the coroutine context. My understanding is that, when faced with a complex object type, println() will default to a .toString() method or print some sort of an object reference. But what's going on here is that println() isn't printing anything inside of $launchParent, yet, the code execution never reaches println("exiting try block"). I've added a try..catch block, thinking there was an exception, but there wasn't. It's just that nothing gets printed after running that offending println() with the $launchParent in it.I am relatively new to Kotlin and feeling a bit mystified by this. I rebuilt the solution, invalidated the cache and restarted, but it didn't help. Any ideas why the println() with the $launchParent string substitution is bombing like this? import kotlinx.coroutines.* fun main(args: Array<String>) = runBlocking() { println("inside main function within JobsAndChildren module") val launchParent: Job = Job() val scope = CoroutineScope(Job()) val job = scope.launch(launchParent) { println("Inside the CoroutineScope launch block") val j1 = coroutineContext[Job] println("after accessing the job key in the coroutineContext array") try { println("inside the try block") println("job passed to the scope.launch as the new context: $launchParent") //println("job returned from scope.launch as the new job: $j1") println("exiting try block") } catch (e: Exception) { println("inside the catch block") println(e.message) } } }
[ "runBlocking and main finish execution before scope.launch does, because scope.launch coroutine is not a child of the runBlocking CoroutineScope. Add job.join()\n" ]
[ 2 ]
[]
[]
[ "kotlin", "kotlin_coroutines" ]
stackoverflow_0074671784_kotlin_kotlin_coroutines.txt
Q: Difference between defining typing.Dict and dict? I am practicing using type hints in Python 3.5. One of my colleague uses typing.Dict: import typing def change_bandwidths(new_bandwidths: typing.Dict, user_id: int, user_name: str) -> bool: print(new_bandwidths, user_id, user_name) return False def my_change_bandwidths(new_bandwidths: dict, user_id: int, user_name: str) ->bool: print(new_bandwidths, user_id, user_name) return True def main(): my_id, my_name = 23, "Tiras" simple_dict = {"Hello": "Moon"} change_bandwidths(simple_dict, my_id, my_name) new_dict = {"new": "energy source"} my_change_bandwidths(new_dict, my_id, my_name) if __name__ == "__main__": main() Both of them work just fine, there doesn't appear to be a difference. I have read the typing module documentation. Between typing.Dict or dict which one should I use in the program? A: There is no real difference between using a plain typing.Dict and dict, no. However, typing.Dict is a Generic type * that lets you specify the type of the keys and values too, making it more flexible: def change_bandwidths(new_bandwidths: typing.Dict[str, str], user_id: int, user_name: str) -> bool: As such, it could well be that at some point in your project lifetime you want to define the dictionary argument a little more precisely, at which point expanding typing.Dict to typing.Dict[key_type, value_type] is a 'smaller' change than replacing dict. You can make this even more generic by using Mapping or MutableMapping types here; since your function doesn't need to alter the mapping, I'd stick with Mapping. A dict is one mapping, but you could create other objects that also satisfy the mapping interface, and your function might well still work with those: def change_bandwidths(new_bandwidths: typing.Mapping[str, str], user_id: int, user_name: str) -> bool: Now you are clearly telling other users of this function that your code won't actually alter the new_bandwidths mapping passed in. Your actual implementation is merely expecting an object that is printable. That may be a test implementation, but as it stands your code would continue to work if you used new_bandwidths: typing.Any, because any object in Python is printable. *: Note: If you are using Python 3.7 or newer, you can use dict as a generic type if you start your module with from __future__ import annotations, and as of Python 3.9, dict (as well as other standard containers) supports being used as generic type even without that directive. A: typing.Dict is a generic version of dict: class typing.Dict(dict, MutableMapping[KT, VT]) A generic version of dict. The usage of this type is as follows: def get_position_in_index(word_list: Dict[str, int], word: str) -> int: return word_list[word] Here you can specify the type of key and values in the dict: Dict[str, int] A: as said in python org: class typing.Dict(dict, MutableMapping[KT, VT]) A generic version of dict. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Mapping. This type can be used as follows: def count_words(text: str) -> Dict[str, int]: ... But dict is less general and you will be able to alter the mapping passed in. In fact, in python.Dict you specify more details. Another tip: Deprecated since version 3.9: builtins.dict now supports []. See PEP 585 and Generic Alias Type. A: If you're coming from google for TypeError: Too few parameters for typing.Dict; actual 1, expected 2, you need to provide a type for both the key and value. So, Dict[str, str] instead of Dict[str]
Difference between defining typing.Dict and dict?
I am practicing using type hints in Python 3.5. One of my colleague uses typing.Dict: import typing def change_bandwidths(new_bandwidths: typing.Dict, user_id: int, user_name: str) -> bool: print(new_bandwidths, user_id, user_name) return False def my_change_bandwidths(new_bandwidths: dict, user_id: int, user_name: str) ->bool: print(new_bandwidths, user_id, user_name) return True def main(): my_id, my_name = 23, "Tiras" simple_dict = {"Hello": "Moon"} change_bandwidths(simple_dict, my_id, my_name) new_dict = {"new": "energy source"} my_change_bandwidths(new_dict, my_id, my_name) if __name__ == "__main__": main() Both of them work just fine, there doesn't appear to be a difference. I have read the typing module documentation. Between typing.Dict or dict which one should I use in the program?
[ "There is no real difference between using a plain typing.Dict and dict, no.\nHowever, typing.Dict is a Generic type * that lets you specify the type of the keys and values too, making it more flexible:\ndef change_bandwidths(new_bandwidths: typing.Dict[str, str],\n user_id: int,\n user_name: str) -> bool:\n\nAs such, it could well be that at some point in your project lifetime you want to define the dictionary argument a little more precisely, at which point expanding typing.Dict to typing.Dict[key_type, value_type] is a 'smaller' change than replacing dict.\nYou can make this even more generic by using Mapping or MutableMapping types here; since your function doesn't need to alter the mapping, I'd stick with Mapping. A dict is one mapping, but you could create other objects that also satisfy the mapping interface, and your function might well still work with those:\ndef change_bandwidths(new_bandwidths: typing.Mapping[str, str],\n user_id: int,\n user_name: str) -> bool:\n\nNow you are clearly telling other users of this function that your code won't actually alter the new_bandwidths mapping passed in.\nYour actual implementation is merely expecting an object that is printable. That may be a test implementation, but as it stands your code would continue to work if you used new_bandwidths: typing.Any, because any object in Python is printable.\n\n*: Note: If you are using Python 3.7 or newer, you can use dict as a generic type if you start your module with from __future__ import annotations, and as of Python 3.9, dict (as well as other standard containers) supports being used as generic type even without that directive.\n", "typing.Dict is a generic version of dict:\n\nclass typing.Dict(dict, MutableMapping[KT, VT])\nA generic version of dict. The usage of this type is as follows:\ndef get_position_in_index(word_list: Dict[str, int], word: str) -> int:\n return word_list[word]\n\n\nHere you can specify the type of key and values in the dict: Dict[str, int]\n", "as said in python org:\n\nclass typing.Dict(dict, MutableMapping[KT, VT])\n\n\nA generic version of dict. Useful for annotating return types. To\nannotate arguments it is preferred to use an abstract collection type\nsuch as Mapping.\n\nThis type can be used as follows:\ndef count_words(text: str) -> Dict[str, int]:\n ...\n\nBut dict is less general and you will be able to alter the mapping passed in.\nIn fact, in python.Dict you specify more details.\nAnother tip:\n\nDeprecated since version 3.9: builtins.dict now supports []. See PEP 585\nand Generic Alias Type.\n\n", "If you're coming from google for\nTypeError: Too few parameters for typing.Dict; actual 1, expected 2, you need to provide a type for both the key and value.\nSo, Dict[str, str] instead of Dict[str]\n" ]
[ 285, 39, 11, 0 ]
[]
[]
[ "dictionary", "python", "python_typing", "type_hinting" ]
stackoverflow_0037087457_dictionary_python_python_typing_type_hinting.txt
Q: Xcode: missing swift version from toolchain I am trying to use an old swift toolchain in Xcode 14: But then I am not able to use Swift 3.0 in a new project: Is this normal? If so, how can I know which old toolchains are compatible with Xcode (different from the toolchain included by default by Xcode)? A: You can find the list of compatible toolchains in the Xcode documentation. In the Overview section of the documentation, there is a link to the list of supported toolchains. You can check the list of supported toolchains for each version of Xcode. Generally, the release notes will include a section listing the toolchains that are compatible with the Xcode version. Additionally, you can search for the name of the toolchain you are interested in plus the word “Xcode” to see if there are any relevant resources that mention its compatibility with Xcode. Follows the link of the most recent document, and the list of previous versions also appears, to check what the version that you need: Xcode 14.1 Release Notes
Xcode: missing swift version from toolchain
I am trying to use an old swift toolchain in Xcode 14: But then I am not able to use Swift 3.0 in a new project: Is this normal? If so, how can I know which old toolchains are compatible with Xcode (different from the toolchain included by default by Xcode)?
[ "You can find the list of compatible toolchains in the Xcode documentation. In the Overview section of the documentation, there is a link to the list of supported toolchains. You can check the list of supported toolchains for each version of Xcode.\nGenerally, the release notes will include a section listing the toolchains that are compatible with the Xcode version. Additionally, you can search for the name of the toolchain you are interested in plus the word “Xcode” to see if there are any relevant resources that mention its compatibility with Xcode.\nFollows the link of the most recent document, and the list of previous versions also appears, to check what the version that you need: Xcode 14.1 Release Notes\n" ]
[ 0 ]
[]
[]
[ "ios", "swift", "xcode" ]
stackoverflow_0074639300_ios_swift_xcode.txt
Q: my raspberry pi pico oled display code is returning 'OSError: [Errno 5] EIO' I've been trying to use an ssd1306 oled display with a raspberry pi pico but every time I run the code it returns an error. I don't know what the error means and can't really find anything online for it. I was able to "fix" it yesterday by changing the address in the library file it uses, but although it worked, the issue came back for no apparent reason, despite me not even changing any of the code. this is the code that I am trying to use from machine import Pin, I2C from ssd1306 import SSD1306_I2C i2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000) oled = SSD1306_I2C(128, 64, i2c) oled.text("hello world", 0, 0) oled.show() this is the error Traceback (most recent call last): File "<stdin>", line 11, in <module> File "/lib/ssd1306.py", line 110, in __init__ File "/lib/ssd1306.py", line 36, in __init__ File "/lib/ssd1306.py", line 71, in init_display File "/lib/ssd1306.py", line 115, in write_cmd OSError: [Errno 5] EIO and the 'addr=0x3D' was originally 0x3C which is 60 in hex but since my i2c.scan returned 61, I changed it to 0x3D, which fixed it for a little bit but it stopped working again for some reason class SSD1306_I2C(SSD1306): def __init__(self, width, height, i2c, addr=0x3D, external_vcc=False): self.i2c = i2c self.addr = addr self.temp = bytearray(2) self.write_list = [b"\x40", None] # Co=0, D/C#=1 super().__init__(width, height, external_vcc) A: Thank you, odog, your error helped me track mine down. This simple example now works for me: from machine import Pin, I2C from ssd1306 import SSD1306_I2C i2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000) devices = i2c.scan() try: oled = SSD1306_I2C(128, 64, i2c,addr=devices[0]) oled.text("hello world", 0, 0) oled.show() except Exception as err: print(f"Unable to initialize oled: {err}") Since yours stopped responding to the address you found, I'm not sure if it will help you.
my raspberry pi pico oled display code is returning 'OSError: [Errno 5] EIO'
I've been trying to use an ssd1306 oled display with a raspberry pi pico but every time I run the code it returns an error. I don't know what the error means and can't really find anything online for it. I was able to "fix" it yesterday by changing the address in the library file it uses, but although it worked, the issue came back for no apparent reason, despite me not even changing any of the code. this is the code that I am trying to use from machine import Pin, I2C from ssd1306 import SSD1306_I2C i2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000) oled = SSD1306_I2C(128, 64, i2c) oled.text("hello world", 0, 0) oled.show() this is the error Traceback (most recent call last): File "<stdin>", line 11, in <module> File "/lib/ssd1306.py", line 110, in __init__ File "/lib/ssd1306.py", line 36, in __init__ File "/lib/ssd1306.py", line 71, in init_display File "/lib/ssd1306.py", line 115, in write_cmd OSError: [Errno 5] EIO and the 'addr=0x3D' was originally 0x3C which is 60 in hex but since my i2c.scan returned 61, I changed it to 0x3D, which fixed it for a little bit but it stopped working again for some reason class SSD1306_I2C(SSD1306): def __init__(self, width, height, i2c, addr=0x3D, external_vcc=False): self.i2c = i2c self.addr = addr self.temp = bytearray(2) self.write_list = [b"\x40", None] # Co=0, D/C#=1 super().__init__(width, height, external_vcc)
[ "Thank you, odog, your error helped me track mine down. This simple example now works for me:\nfrom machine import Pin, I2C\nfrom ssd1306 import SSD1306_I2C\n\ni2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000)\n\ndevices = i2c.scan()\ntry:\n oled = SSD1306_I2C(128, 64, i2c,addr=devices[0])\n oled.text(\"hello world\", 0, 0)\n oled.show()\nexcept Exception as err:\n print(f\"Unable to initialize oled: {err}\")\n\nSince yours stopped responding to the address you found, I'm not sure if it will help you.\n" ]
[ 0 ]
[]
[]
[ "python", "raspberry_pi_pico", "thonny" ]
stackoverflow_0074659614_python_raspberry_pi_pico_thonny.txt
Q: Django many to many model get none I have been dealing with a project for a few days and today I encountered an error. I wanted to write it here as I have no idea how to solve it. My first model: from django.db import models # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) video_slug = models.SlugField(unique=True) description = models.TextField(max_length=500) image = models.ImageField(upload_to='images/' , blank=True, null=True) video = models.FileField(upload_to='videos/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ManyToManyField('categories.Category', blank=True) def __str__(self): return self.title def get_absolute_url(self): return "/video/" + self.video_slug class Meta: verbose_name_plural = "Videos" ordering = ['-created_at'] get_latest_by = 'created_at' secondary model: class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) category_slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='category', blank=True, null=True) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return "/category/" + self.category_slug class Meta: verbose_name_plural = "categories" ordering = ['name'] and view.py ... class VideoListView(ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer When i send get request i got this [ { ... "category": "categories.Category.None", ... } ] What should i do? Please help me. A: Im assuming your mistake is you are using an empty Serializer and not including the queryset instance. So something like this will fix your issue: queryset = Video.objects.all() serializer_class = VideoSerializer(queryset, many=True)
Django many to many model get none
I have been dealing with a project for a few days and today I encountered an error. I wanted to write it here as I have no idea how to solve it. My first model: from django.db import models # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) video_slug = models.SlugField(unique=True) description = models.TextField(max_length=500) image = models.ImageField(upload_to='images/' , blank=True, null=True) video = models.FileField(upload_to='videos/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ManyToManyField('categories.Category', blank=True) def __str__(self): return self.title def get_absolute_url(self): return "/video/" + self.video_slug class Meta: verbose_name_plural = "Videos" ordering = ['-created_at'] get_latest_by = 'created_at' secondary model: class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) category_slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='category', blank=True, null=True) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return "/category/" + self.category_slug class Meta: verbose_name_plural = "categories" ordering = ['name'] and view.py ... class VideoListView(ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer When i send get request i got this [ { ... "category": "categories.Category.None", ... } ] What should i do? Please help me.
[ "Im assuming your mistake is you are using an empty Serializer and not including the queryset instance. So something like this will fix your issue:\nqueryset = Video.objects.all()\nserializer_class = VideoSerializer(queryset, many=True)\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "orm", "python" ]
stackoverflow_0074671896_django_django_models_django_rest_framework_orm_python.txt
Q: Is there any way to skip number request in telethon? Every time if my session is invalid i got this output: "Please enter your phone (or bot token): " Is there anyway to pass it or ignore it? I tried to edit telethon source code, but im bad at it)) A: So, for everyone who have the same problem client = TelegramClient(f"session", api_id, api_hash) client.connect() print(client) if client.is_user_authorized(): print("VALID") else: print('NO VALID') Everything was much easier, than i thought
Is there any way to skip number request in telethon?
Every time if my session is invalid i got this output: "Please enter your phone (or bot token): " Is there anyway to pass it or ignore it? I tried to edit telethon source code, but im bad at it))
[ "So, for everyone who have the same problem\nclient = TelegramClient(f\"session\", api_id, api_hash)\nclient.connect()\nprint(client)\nif client.is_user_authorized():\n print(\"VALID\")\nelse:\n print('NO VALID')\n\nEverything was much easier, than i thought\n" ]
[ 0 ]
[ "Telethon project implements Telegram API and there is no way to skip it since it's required by protocol.\nAs an option I can advice you to check if authenticating as a bot instead of a normal user can solve your problem depending on your task.\n" ]
[ -1 ]
[ "python", "telethon" ]
stackoverflow_0074671835_python_telethon.txt
Q: Inserting data to mysql database from function . api Highlevel:my program gets a long URL and makes it shorter(like tinyurl). But i have problem passing Long URL variable and shortURL variable from function to a mySQL database. I have tried looking it up on internet but noluck and information im getting is not close to what i have. im only posting some parts of my code the full code will be in playground var db *sql.DB //global variable func main(){ var db, err = sql.Open("mysql", dsn()) if err != nil { fmt.Println(err.Error()) } else { fmt.Printf("Connection established to MYSQL server\n%s\n", dsn()) } defer db.Close() linkList = map[string]string{} http.HandleFunc("/link", addLink) http.HandleFunc("/hpe/", getLink) http.HandleFunc("/", Home) // Flags to pass string ip or port to WEB app ip := flag.String("i", "0.0.0.0", "") port := flag.String("p", "8080", "") flag.Parse() fmt.Printf("Web application listening on %s \n", net.JoinHostPort(*ip, *port)) log.Fatal(http.ListenAndServe(net.JoinHostPort(*ip, *port), nil)) } function that creates short url. Every time this func is called it produces link func addLink(w http.ResponseWriter, r *http.Request) { log.Println("Add Link") key, ok := r.URL.Query()["ik"] if ok { if !validLink(key[0]) { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Could not create shortlink need absolute path link.") return } log.Println(key) if _, ok := linkList[key[0]]; !ok { genString := randomString(5) linkList[genString] = key[0] w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusAccepted) linkString := fmt.Sprintf("<a href=\"hpe/%s\">hpe/%s</a>", genString, genString) fmt.Fprintf(w, "Added shortlink\n") fmt.Fprintf(w, linkString) return // database function defer db.Close() s: result, err := db.Exec("insert into Url (LongUrl, ShortUrl) value(?,?);",genString,linkString) if err != nil { fmt.Print(err.Error()) } else { _,err:=result.LastInsertId() } } w.WriteHeader(http.StatusConflict) fmt.Fprintf(w, "Already have this link") return } w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Failed to add link") return } func getLink(w http.ResponseWriter, r *http.Request) { path := r.URL.Path log.Println("Get Link:", path) pathArgs := strings.Split(path, "/") if len(pathArgs[2]) < 1 { w.WriteHeader(http.StatusNotFound) http.Redirect(w, r, "0.0.0.0:8080", http.StatusTemporaryRedirect) return } log.Printf("Redirected to: %s", linkList[pathArgs[2]]) http.Redirect(w, r, linkList[pathArgs[2]], http.StatusTemporaryRedirect) //fmt.Printf("all %s", linkList) return } My expectation is when func addlink gets called the info that generated from long and short url gets put into database like in the code. A: If the problem is that nothing is getting added to the db when addLink is called, then the problem looks like it is because there is a return statement in addLink before right after creating and printing the linkString var, and before the call to db.Exec
Inserting data to mysql database from function . api
Highlevel:my program gets a long URL and makes it shorter(like tinyurl). But i have problem passing Long URL variable and shortURL variable from function to a mySQL database. I have tried looking it up on internet but noluck and information im getting is not close to what i have. im only posting some parts of my code the full code will be in playground var db *sql.DB //global variable func main(){ var db, err = sql.Open("mysql", dsn()) if err != nil { fmt.Println(err.Error()) } else { fmt.Printf("Connection established to MYSQL server\n%s\n", dsn()) } defer db.Close() linkList = map[string]string{} http.HandleFunc("/link", addLink) http.HandleFunc("/hpe/", getLink) http.HandleFunc("/", Home) // Flags to pass string ip or port to WEB app ip := flag.String("i", "0.0.0.0", "") port := flag.String("p", "8080", "") flag.Parse() fmt.Printf("Web application listening on %s \n", net.JoinHostPort(*ip, *port)) log.Fatal(http.ListenAndServe(net.JoinHostPort(*ip, *port), nil)) } function that creates short url. Every time this func is called it produces link func addLink(w http.ResponseWriter, r *http.Request) { log.Println("Add Link") key, ok := r.URL.Query()["ik"] if ok { if !validLink(key[0]) { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Could not create shortlink need absolute path link.") return } log.Println(key) if _, ok := linkList[key[0]]; !ok { genString := randomString(5) linkList[genString] = key[0] w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusAccepted) linkString := fmt.Sprintf("<a href=\"hpe/%s\">hpe/%s</a>", genString, genString) fmt.Fprintf(w, "Added shortlink\n") fmt.Fprintf(w, linkString) return // database function defer db.Close() s: result, err := db.Exec("insert into Url (LongUrl, ShortUrl) value(?,?);",genString,linkString) if err != nil { fmt.Print(err.Error()) } else { _,err:=result.LastInsertId() } } w.WriteHeader(http.StatusConflict) fmt.Fprintf(w, "Already have this link") return } w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Failed to add link") return } func getLink(w http.ResponseWriter, r *http.Request) { path := r.URL.Path log.Println("Get Link:", path) pathArgs := strings.Split(path, "/") if len(pathArgs[2]) < 1 { w.WriteHeader(http.StatusNotFound) http.Redirect(w, r, "0.0.0.0:8080", http.StatusTemporaryRedirect) return } log.Printf("Redirected to: %s", linkList[pathArgs[2]]) http.Redirect(w, r, linkList[pathArgs[2]], http.StatusTemporaryRedirect) //fmt.Printf("all %s", linkList) return } My expectation is when func addlink gets called the info that generated from long and short url gets put into database like in the code.
[ "If the problem is that nothing is getting added to the db when addLink is called, then the problem looks like it is because there is a return statement in addLink before right after creating and printing the linkString var, and before the call to db.Exec\n" ]
[ 0 ]
[]
[]
[ "go", "mysql" ]
stackoverflow_0074645024_go_mysql.txt
Q: NESTJS API dockerized with hot/live reaload in version 9 of nest In short, guys, I need an example of a NESTJS application in this latest version 9 dockerized with hot/live reload working (ie, saving a file locally and the container restarting) in a windows environment with WSL2. I open one issue here about this live/hot reload does not work on a dockerized nestJS API A: To create a NESTJS application in the latest version 9 and dockerize it with hot/live reload in a Windows environment with WSL2, you will need to first install Docker on your Windows system and then install WSL2. Once you have these tools installed, you can use the following steps to create a NESTJS application and dockerize it with hot/live reload: Open a terminal in WSL2 and run the following command to create a new NESTJS project: nest new my-nestjs-app Navigate to the project directory and install the required dependencies: cd my-nestjs-app npm install Create a Dockerfile in the project directory with the following content: FROM node:14-alpine WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["npm", "run", "start:dev"] Build the Docker image using the Dockerfile: docker build -t my-nestjs-app . Run the Docker image and mount the project directory to the container so that any changes made to the code are automatically reflected in the container: docker run -p 3000:3000 -v $(pwd):/usr/src/app my-nestjs-app Open the NESTJS application in a browser at http://localhost:3000 and make some changes to the code. You should see the changes reflected in the browser immediately, without the need to restart the container. You can also use the nodemon package to automatically restart the application whenever a file is changed. To do this, add the following script to the package.json file: "start:dev": "nodemon" Then, update the Dockerfile to run the start:dev script instead of npm run start:dev: CMD ["npm", "run", "start:dev"] With these changes, the application will automatically restart whenever a file is changed.
NESTJS API dockerized with hot/live reaload in version 9 of nest
In short, guys, I need an example of a NESTJS application in this latest version 9 dockerized with hot/live reload working (ie, saving a file locally and the container restarting) in a windows environment with WSL2. I open one issue here about this live/hot reload does not work on a dockerized nestJS API
[ "To create a NESTJS application in the latest version 9 and dockerize it with hot/live reload in a Windows environment with WSL2, you will need to first install Docker on your Windows system and then install WSL2. Once you have these tools installed, you can use the following steps to create a NESTJS application and dockerize it with hot/live reload:\n\nOpen a terminal in WSL2 and run the following command to create a\nnew NESTJS project:\n\nnest new my-nestjs-app\n\n\nNavigate to the project directory and install the required\ndependencies:\n\ncd my-nestjs-app\nnpm install\n\n\nCreate a Dockerfile in the project directory with the following\ncontent:\n\nFROM node:14-alpine\n\nWORKDIR /usr/src/app\n\nCOPY package*.json ./\n\nRUN npm install\n\nCOPY . .\n\nEXPOSE 3000\n\nCMD [\"npm\", \"run\", \"start:dev\"]\n\n\nBuild the Docker image using the Dockerfile:\n\ndocker build -t my-nestjs-app .\n\n\nRun the Docker image and mount the project directory to the\ncontainer so that any changes made to the code are automatically\nreflected in the container:\n\ndocker run -p 3000:3000 -v $(pwd):/usr/src/app my-nestjs-app\n\n\nOpen the NESTJS application in a browser at http://localhost:3000\nand make some changes to the code. You should see the changes\nreflected in the browser immediately, without the need to restart\nthe container.\n\nYou can also use the nodemon package to automatically restart the application whenever a file is changed. To do this, add the following script to the package.json file:\n\"start:dev\": \"nodemon\"\n\nThen, update the Dockerfile to run the start:dev script instead of npm run start:dev:\nCMD [\"npm\", \"run\", \"start:dev\"]\n\nWith these changes, the application will automatically restart whenever a file is changed.\n" ]
[ 0 ]
[]
[]
[ "docker", "docker_compose", "nestjs" ]
stackoverflow_0074671999_docker_docker_compose_nestjs.txt
Q: setState Updating all instances of Component React I'm trying to create a quizlet-learn kind of app, and I have multiple instances of Card components. I have it set so when I pick an answer on one of the cards, it updates the state and display based on what I picked. There are buttons at the bottom to change the card. The issue is when I pick an answer on a card, the state is updated for every card component and showAnswer is set to true. How can I prevent this from happening and make it only update the same card? My card component: export default class Card extends React.Component { constructor(props) { super(props); this.state = { option_correct: Math.random() > 0.5, showAnswer: false, optionPicked: 0 } } handleClick(optionPicked) { console.log(this.state.showAnswer); console.log(this.props.prompt + ' 1'); if (!this.props.hidden) { if (!this.state.showAnswer) this.setState({ optionPicked: optionPicked }); this.setState({ showAnswer: true }); } } handleKeyPress(event) { console.log(prompt + ' 2'); if (event.key === 'Enter') { this.props.onFinish(); event.preventDefault(); } } render() { console.log(this.props.prompt + ' ' + this.state.showAnswer); return ( <div className={`card ${this.state.showAnswer ? "show_answer" : ""}`} onKeyDown={this.handleKeyPress}> <div className='prompt'> {this.props.prompt} </div> <small className={'continue'}> Press Enter to Continue... </small> <div className='options'> <button className={'option ' + (this.state.option_correct ? 'correct' : 'wrong') + ' ' + (this.state.optionPicked === 1 ? 'picked' : 'not_picked')} onClick={() => { this.handleClick(1); }}> {this.state.option_correct ? this.props.answer : this.props.wrongAnswer} </button> <button className={'option ' + (this.state.option_correct ? 'wrong' : 'correct') + ' ' + (this.state.optionPicked === 2 ? 'picked' : 'not_picked')} onClick={() => { this.handleClick(2); }}> {this.state.option_correct ? this.props.wrongAnswer : this.props.answer} </button> </div> </div> ); } } My card container component: class CardData { constructor(prompt, answer, wrongAnswer) { this.prompt = prompt; this.answer = answer; this.wrongAnswer = wrongAnswer; } } export default function Cards() { const [flashcarddata, setFlashcarddata] = useState([]); const [current, setCurrent] = useState(0); useEffect(() => { setFlashcarddata([ new CardData('word1', 'correct', 'incorrect'), new CardData('word2', 'correct 2', 'incorrect 2'), new CardData('word3', 'correct 23', 'incorrect 23') ]) }, []); const cards = flashcarddata.map((card, index) => { return <Card prompt={card.prompt} answer={card.answer} wrongAnswer={card.wrongAnswer} hidden={current !== index} onFinish={() => { console.log('finished ' + card.prompt); nextCard(); }} />; }); function previousCard() { setCurrent(current - 1); } function nextCard() { setCurrent(current + 1); } const loading = <div className="loading">Loading card...</div>; return ( <div> {flashcarddata && flashcarddata.length > 0 ? cards[current] : loading} <div className="nav"> {current > 0 ? ( <button onClick={previousCard}>Previous card</button> ) : ( <button className="disabled" disabled> Previous card </button> )} {current < flashcarddata.length - 1 ? ( <button onClick={nextCard}>Next card</button> ) : ( <button className="disabled" disabled> Next card </button> )} </div> </div> ); } So far I've tried to change Card into a class from a function component, make the handleClick method only work if the card was the one being displayed, and changed from having every card being rendered and having most of them set display: block in css to having just one card rendered at a time. A: When you update the state of one Card component, it updates the state of all the Card components because they all have the same initial state. One way to fix this is to move the state out of the Card component and into the parent Cards component. Then, you can pass the current card's state as a prop to each Card component, and update the state in the Cards component when a card is clicked. Here's an example of how you could do this: class CardData { constructor(prompt, answer, wrongAnswer) { this.prompt = prompt; this.answer = answer; this.wrongAnswer = wrongAnswer; } } function Cards() { const [flashcarddata, setFlashcarddata] = useState([]); const [current, setCurrent] = useState(0); const [currentCardState, setCurrentCardState] = useState({ option_correct: Math.random() > 0.5, showAnswer: false, optionPicked: 0 }); useEffect(() => { setFlashcarddata([ new CardData('word1', 'correct', 'incorrect'), new CardData('word2', 'correct 2', 'incorrect 2'), new CardData('word3', 'correct 23', 'incorrect 23') ]); }, []); const cards = flashcarddata.map((card, index) => { return ( <Card prompt={card.prompt} answer={card.answer} wrongAnswer={card.wrongAnswer} hidden={current !== index} showAnswer={currentCardState.showAnswer} optionPicked={currentCardState.optionPicked} option_correct={currentCardState.option_correct} onFinish={() => { console.log('finished ' + card.prompt); nextCard(); }} onClick={() => { setCurrentCardState({ ...currentCardState, optionPicked: optionPicked, showAnswer: true }); }} /> ); }); function previousCard() { setCurrent(current - 1); } function nextCard() { setCurrent(current + 1); } const loading = ( <div className="loading">Loading card...</div> ); return ( <div> {cards} <button onClick={previousCard}>Previous</button> <button onClick={nextCard}>Next</button> </div> ); } In the code above, the state of the Card components is managed by the parent Cards component, and the Card components are rendered based on the current card's state. When a card is clicked, the state is updated in the Cards component, and the new state is passed down to the Card components as props. This ensures that each Card component has its own state and is updated independently of the other Card components.
setState Updating all instances of Component React
I'm trying to create a quizlet-learn kind of app, and I have multiple instances of Card components. I have it set so when I pick an answer on one of the cards, it updates the state and display based on what I picked. There are buttons at the bottom to change the card. The issue is when I pick an answer on a card, the state is updated for every card component and showAnswer is set to true. How can I prevent this from happening and make it only update the same card? My card component: export default class Card extends React.Component { constructor(props) { super(props); this.state = { option_correct: Math.random() > 0.5, showAnswer: false, optionPicked: 0 } } handleClick(optionPicked) { console.log(this.state.showAnswer); console.log(this.props.prompt + ' 1'); if (!this.props.hidden) { if (!this.state.showAnswer) this.setState({ optionPicked: optionPicked }); this.setState({ showAnswer: true }); } } handleKeyPress(event) { console.log(prompt + ' 2'); if (event.key === 'Enter') { this.props.onFinish(); event.preventDefault(); } } render() { console.log(this.props.prompt + ' ' + this.state.showAnswer); return ( <div className={`card ${this.state.showAnswer ? "show_answer" : ""}`} onKeyDown={this.handleKeyPress}> <div className='prompt'> {this.props.prompt} </div> <small className={'continue'}> Press Enter to Continue... </small> <div className='options'> <button className={'option ' + (this.state.option_correct ? 'correct' : 'wrong') + ' ' + (this.state.optionPicked === 1 ? 'picked' : 'not_picked')} onClick={() => { this.handleClick(1); }}> {this.state.option_correct ? this.props.answer : this.props.wrongAnswer} </button> <button className={'option ' + (this.state.option_correct ? 'wrong' : 'correct') + ' ' + (this.state.optionPicked === 2 ? 'picked' : 'not_picked')} onClick={() => { this.handleClick(2); }}> {this.state.option_correct ? this.props.wrongAnswer : this.props.answer} </button> </div> </div> ); } } My card container component: class CardData { constructor(prompt, answer, wrongAnswer) { this.prompt = prompt; this.answer = answer; this.wrongAnswer = wrongAnswer; } } export default function Cards() { const [flashcarddata, setFlashcarddata] = useState([]); const [current, setCurrent] = useState(0); useEffect(() => { setFlashcarddata([ new CardData('word1', 'correct', 'incorrect'), new CardData('word2', 'correct 2', 'incorrect 2'), new CardData('word3', 'correct 23', 'incorrect 23') ]) }, []); const cards = flashcarddata.map((card, index) => { return <Card prompt={card.prompt} answer={card.answer} wrongAnswer={card.wrongAnswer} hidden={current !== index} onFinish={() => { console.log('finished ' + card.prompt); nextCard(); }} />; }); function previousCard() { setCurrent(current - 1); } function nextCard() { setCurrent(current + 1); } const loading = <div className="loading">Loading card...</div>; return ( <div> {flashcarddata && flashcarddata.length > 0 ? cards[current] : loading} <div className="nav"> {current > 0 ? ( <button onClick={previousCard}>Previous card</button> ) : ( <button className="disabled" disabled> Previous card </button> )} {current < flashcarddata.length - 1 ? ( <button onClick={nextCard}>Next card</button> ) : ( <button className="disabled" disabled> Next card </button> )} </div> </div> ); } So far I've tried to change Card into a class from a function component, make the handleClick method only work if the card was the one being displayed, and changed from having every card being rendered and having most of them set display: block in css to having just one card rendered at a time.
[ "When you update the state of one Card component, it updates the state of all the Card components because they all have the same initial state.\nOne way to fix this is to move the state out of the Card component and into the parent Cards component. Then, you can pass the current card's state as a prop to each Card component, and update the state in the Cards component when a card is clicked.\nHere's an example of how you could do this:\nclass CardData {\n constructor(prompt, answer, wrongAnswer) {\n this.prompt = prompt;\n this.answer = answer;\n this.wrongAnswer = wrongAnswer;\n }\n}\n\nfunction Cards() {\n const [flashcarddata, setFlashcarddata] = useState([]);\n const [current, setCurrent] = useState(0);\n const [currentCardState, setCurrentCardState] = useState({\n option_correct: Math.random() > 0.5,\n showAnswer: false,\n optionPicked: 0\n });\n\n useEffect(() => {\n setFlashcarddata([\n new CardData('word1', 'correct', 'incorrect'),\n new CardData('word2', 'correct 2', 'incorrect 2'),\n new CardData('word3', 'correct 23', 'incorrect 23')\n ]);\n }, []);\n\n const cards = flashcarddata.map((card, index) => {\n return (\n <Card\n prompt={card.prompt}\n answer={card.answer}\n wrongAnswer={card.wrongAnswer}\n hidden={current !== index}\n showAnswer={currentCardState.showAnswer}\n optionPicked={currentCardState.optionPicked}\n option_correct={currentCardState.option_correct}\n onFinish={() => {\n console.log('finished ' + card.prompt);\n nextCard();\n }}\n onClick={() => {\n setCurrentCardState({\n ...currentCardState,\n optionPicked: optionPicked,\n showAnswer: true\n });\n }}\n />\n );\n });\n\n function previousCard() {\n setCurrent(current - 1);\n }\n function nextCard() {\n setCurrent(current + 1);\n }\n\n const loading = (\n <div className=\"loading\">Loading card...</div>\n );\n\n return (\n <div>\n {cards}\n <button onClick={previousCard}>Previous</button>\n <button onClick={nextCard}>Next</button>\n </div>\n );\n}\n\nIn the code above, the state of the Card components is managed by the parent Cards component, and the Card components are rendered based on the current card's state. When a card is clicked, the state is updated in the Cards component, and the new state is passed down to the Card components as props. This ensures that each Card component has its own state and is updated independently of the other Card components.\n" ]
[ 1 ]
[]
[]
[ "javascript", "reactjs", "setstate" ]
stackoverflow_0074671993_javascript_reactjs_setstate.txt
Q: Aspect Method is not triggered I'm trying to get my Aspect class to work but it gets completely ignored. I have following files: MyAnnotation.java package annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { } MyAspect.java package annotations; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class MyAspect { @Before("@annotation(annotations.MyAnnotation)*") public void interceptMethods(final JoinPoint thisJoinPoint) { System.out.println(thisJoinPoint); } } MyClass.java package annotations; import org.springframework.stereotype.Service; @Service public class MyClass { @MyAnnotation public int myMethod(final int i) { System.out.println("method: " + i); return i; } } MyRestController.java package annotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyRestController { @Autowired MyClass myClass; @GetMapping("/myClass") private int callMyMethod() { return myClass.myMethod(1); } } Application.java package annotations; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>experiments</groupId> <artifactId>annotations</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.2.11.RELEASE</version> </dependency> </dependencies> </project> Does anyone see the problem and how to fix it? I've tried multiple Before expressions ("execution(* annotations..(..))") but I just can't see to get it working. I've tried Around instead of Before. I've tried Pointcuts with Before. I've been through articles: AspectJ @Before annotation issue Spring AspectJ, pointcut before method execution where method OR class is annotated A: I finally did it. I'll leave the solution here for other people in need for a basic example. These are the files: MyAnnotation.java package annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { } MyAspect.java - it's tricky because: annotation @Aspect is not sufficient. The annotation @Component also needs to be added to aspect class. If annotation @Component is omitted, the application will ignore the class. in @Before annotation, there needs to be "and args(*)". If the args are omitted, there will be null pointer exception. Code: package annotations; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class MyAspect { @Before("execution(* annotations.*.*(..)) and args(*)") public void beforeExecution(final JoinPoint joinPoint) { System.out.println("5"); } } MyClass.java package annotations; import org.springframework.stereotype.Service; @Service public class MyClass { @MyAnnotation public int myMethod(final int i) { System.out.println("method: " + i); return i; } } MyRestController package annotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyRestController { @Autowired MyClass myClass; @GetMapping("/myClass") private int callMyMethod() { return myClass.myMethod(1); } } Application.java package annotations; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } } pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>experiments</groupId> <artifactId>annotations</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.2.11.RELEASE</version> </dependency> </dependencies>
Aspect Method is not triggered
I'm trying to get my Aspect class to work but it gets completely ignored. I have following files: MyAnnotation.java package annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { } MyAspect.java package annotations; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class MyAspect { @Before("@annotation(annotations.MyAnnotation)*") public void interceptMethods(final JoinPoint thisJoinPoint) { System.out.println(thisJoinPoint); } } MyClass.java package annotations; import org.springframework.stereotype.Service; @Service public class MyClass { @MyAnnotation public int myMethod(final int i) { System.out.println("method: " + i); return i; } } MyRestController.java package annotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyRestController { @Autowired MyClass myClass; @GetMapping("/myClass") private int callMyMethod() { return myClass.myMethod(1); } } Application.java package annotations; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>experiments</groupId> <artifactId>annotations</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.2.11.RELEASE</version> </dependency> </dependencies> </project> Does anyone see the problem and how to fix it? I've tried multiple Before expressions ("execution(* annotations..(..))") but I just can't see to get it working. I've tried Around instead of Before. I've tried Pointcuts with Before. I've been through articles: AspectJ @Before annotation issue Spring AspectJ, pointcut before method execution where method OR class is annotated
[ "I finally did it. I'll leave the solution here for other people in need for a basic example.\nThese are the files:\nMyAnnotation.java\npackage annotations;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.METHOD)\npublic @interface MyAnnotation {\n}\n\nMyAspect.java - it's tricky because:\n\nannotation @Aspect is not sufficient. The annotation @Component also needs to be added to aspect class. If annotation @Component is omitted, the application will ignore the class.\nin @Before annotation, there needs to be \"and args(*)\". If the args are omitted, there will be null pointer exception.\n\nCode:\npackage annotations;\n\nimport org.aspectj.lang.JoinPoint;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\nimport org.springframework.stereotype.Component;\n\n@Aspect\n@Component\npublic class MyAspect {\n @Before(\"execution(* annotations.*.*(..)) and args(*)\")\n public void beforeExecution(final JoinPoint joinPoint) {\n System.out.println(\"5\");\n }\n}\n\nMyClass.java\npackage annotations;\n\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class MyClass {\n\n @MyAnnotation\n public int myMethod(final int i) {\n System.out.println(\"method: \" + i);\n return i;\n }\n}\n\nMyRestController\npackage annotations;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class MyRestController {\n\n @Autowired\n MyClass myClass;\n\n @GetMapping(\"/myClass\")\n private int callMyMethod() {\n return myClass.myMethod(1);\n }\n}\n\nApplication.java\npackage annotations;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(final String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n\npom.xml\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n<modelVersion>4.0.0</modelVersion>\n<groupId>experiments</groupId>\n<artifactId>annotations</artifactId>\n<version>0.0.1-SNAPSHOT</version>\n\n<properties>\n <maven.compiler.source>1.8</maven.compiler.source>\n <maven.compiler.target>1.8</maven.compiler.target>\n</properties>\n\n<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-aop</artifactId>\n <version>2.2.11.RELEASE</version>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n <version>2.2.11.RELEASE</version>\n </dependency>\n</dependencies>\n\n" ]
[ 0 ]
[]
[]
[ "annotations", "aspect", "java", "spring_boot" ]
stackoverflow_0074668099_annotations_aspect_java_spring_boot.txt
Q: Golang and Cognito _ Invalid lambda function output I have the code func EjecutoLambda(event events.CognitoEventUserPoolsPostAuthentication) (events.CognitoEventUserPoolsPostAuthentication, error) { awsgo.InicializoAWS() if !validoParametros() { fmt.Println("Error en los parámetros. debe enviar 'SecretName'") err := errors.New("error en los parametros debe enviar secretname") return event, err } var datos models.SignUp for row, att := range event.Request.UserAttributes { switch row { case "email": datos.UserEmail = att fmt.Println("Email = " + datos.UserEmail) case "sub": datos.UserUUID = att fmt.Println("Sub = " + datos.UserUUID) } } err := bd.ReadSecret() if err != nil { return event, err } return event, bd.SignUp(datos) } But I receive the message Invalid lambda function output All the code works fine... the data is INSERTED into the database. But when the lambda need to finish, I receive this error from cognito trigger What's wrong ? Regards A: Was my Mistake. Using PostAuthentication, when the trigger is PostConfirmation
Golang and Cognito _ Invalid lambda function output
I have the code func EjecutoLambda(event events.CognitoEventUserPoolsPostAuthentication) (events.CognitoEventUserPoolsPostAuthentication, error) { awsgo.InicializoAWS() if !validoParametros() { fmt.Println("Error en los parámetros. debe enviar 'SecretName'") err := errors.New("error en los parametros debe enviar secretname") return event, err } var datos models.SignUp for row, att := range event.Request.UserAttributes { switch row { case "email": datos.UserEmail = att fmt.Println("Email = " + datos.UserEmail) case "sub": datos.UserUUID = att fmt.Println("Sub = " + datos.UserUUID) } } err := bd.ReadSecret() if err != nil { return event, err } return event, bd.SignUp(datos) } But I receive the message Invalid lambda function output All the code works fine... the data is INSERTED into the database. But when the lambda need to finish, I receive this error from cognito trigger What's wrong ? Regards
[ "Was my Mistake.\nUsing PostAuthentication, when the trigger is PostConfirmation\n" ]
[ 0 ]
[]
[]
[ "amazon_cognito", "go" ]
stackoverflow_0074669317_amazon_cognito_go.txt
Q: A column in a table is referred to by multiple physical column names I have a spring boot project using JPA, So I am trying to map two tables into a third one using their Id : for example I have a coupon class, I have a customer class I want to take customer id and coupon id into a third table. I have coupons: @Entity @Table(name = "coupons") public class Coupon { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long coup_id; private String title; private String start; private String end; private int amount; private String type; private String message; private double price; private String image; @ManyToMany(mappedBy = "coupons") private List<Customer> customers; I have customers: @Entity @Table(name="customers") public class Customer { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int cust_id; @Size(min=1,message="is required") private String cust_name; @Size(min = 1, message = "is required") private String password; @ManyToMany(cascade = { CascadeType.ALL }) @JoinTable( name = "customer_coupon", joinColumns = { @JoinColumn(name = "cust_id") }, inverseJoinColumns = { @JoinColumn(name = "coup_id") } ) private List<Coupon> coupons; and I have the connecting table customer_coupon: This is the error I am getting when starting the project: Caused by: org.hibernate.DuplicateMappingException: Table [coupons] contains physical column name [coup_id] referred to by multiple physical column names: [coupId], [coup_id] I have no idea where it comes from, would love if someone could help me ! A: To remove ambiguity use the @Column annotation: @Column(name = "coup_id") private long coupId; This way you can name your Java attributes as you like and don't let JPA alone for interpreting them. A: Found the problem...sorry. Had another class Company that was referring to coupId as well: @OneToMany( cascade = CascadeType.ALL, orphanRemoval = true ) @JoinColumn(name = "coupId") private List<Coupon> coupons = new ArrayList(); This is from the Company class. A: I had same problem. @Column(name = "coup_id") private long coupId; and column in db table called coup_id. I removed @Column annotation, and workin! Thats all. Hibernate convert xX to x_x itself. A: Another situation where I had this problem is due to case sensitivity. I mentioned a column name as ownerid and ownerId in two classes. As per Error: Table [] contains logical column name [ownerid] referring to multiple physical column names [ownerid] and [owner_id]. I ended up spending a lot of time searching for owner_id. A: I have join table, that is also entity and have ManyToOne relationships to two tables, so it is not exactly this issue, but could help someone. Adding @MapsId(property name) to @ManyToOne property worked for me. A: it might be because of miss the mapped by i was have the issue in this code @OneToMany @JsonManagedReference private List<TweetsEntity> userTweets; but after make it this way (add the mappedBy) @OneToMany(mappedBy = "user") @JsonManagedReference private List<TweetsEntity> userTweets; its solved for me
A column in a table is referred to by multiple physical column names
I have a spring boot project using JPA, So I am trying to map two tables into a third one using their Id : for example I have a coupon class, I have a customer class I want to take customer id and coupon id into a third table. I have coupons: @Entity @Table(name = "coupons") public class Coupon { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long coup_id; private String title; private String start; private String end; private int amount; private String type; private String message; private double price; private String image; @ManyToMany(mappedBy = "coupons") private List<Customer> customers; I have customers: @Entity @Table(name="customers") public class Customer { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int cust_id; @Size(min=1,message="is required") private String cust_name; @Size(min = 1, message = "is required") private String password; @ManyToMany(cascade = { CascadeType.ALL }) @JoinTable( name = "customer_coupon", joinColumns = { @JoinColumn(name = "cust_id") }, inverseJoinColumns = { @JoinColumn(name = "coup_id") } ) private List<Coupon> coupons; and I have the connecting table customer_coupon: This is the error I am getting when starting the project: Caused by: org.hibernate.DuplicateMappingException: Table [coupons] contains physical column name [coup_id] referred to by multiple physical column names: [coupId], [coup_id] I have no idea where it comes from, would love if someone could help me !
[ "To remove ambiguity use the @Column annotation:\n@Column(name = \"coup_id\")\nprivate long coupId;\n\nThis way you can name your Java attributes as you like and don't let JPA alone for interpreting them.\n", "Found the problem...sorry.\nHad another class Company that was referring to coupId as well:\n @OneToMany(\n cascade = CascadeType.ALL,\n orphanRemoval = true\n )\n @JoinColumn(name = \"coupId\")\nprivate List<Coupon> coupons = new ArrayList();\n\nThis is from the Company class.\n", "I had same problem.\n@Column(name = \"coup_id\") private long coupId;\nand column in db table called coup_id.\nI removed @Column annotation, and workin! Thats all.\nHibernate convert xX to x_x itself.\n", "Another situation where I had this problem is due to case sensitivity. I mentioned a column name as ownerid and ownerId in two classes. As per Error: Table [] contains logical column name [ownerid] referring to multiple physical column names [ownerid] and [owner_id]. I ended up spending a lot of time searching for owner_id. \n", "I have join table, that is also entity and have ManyToOne relationships to two tables, so it is not exactly this issue, but could help someone.\nAdding @MapsId(property name) to @ManyToOne property worked for me.\n", "it might be because of miss the mapped by\ni was have the issue in this code\n@OneToMany\n@JsonManagedReference\nprivate List<TweetsEntity> userTweets;\n\n\nbut after make it this way (add the mappedBy)\n@OneToMany(mappedBy = \"user\")\n@JsonManagedReference\nprivate List<TweetsEntity> userTweets;\n\nits solved for me\n" ]
[ 11, 4, 1, 0, 0, 0 ]
[]
[]
[ "hibernate", "java", "jpa", "mysql", "mysql_workbench" ]
stackoverflow_0057691377_hibernate_java_jpa_mysql_mysql_workbench.txt
Q: I'm doing some basic logic function + decimal rounding stuff, and this doesn't seem to work...why? temperature=int(input("What temperature are you?")) if temperature>=37 and temperature<50: print("your temperature is healthy, as it is" , "%.2f" %temperature) else: print("You said your temperature was" , "%.2f" %temperature , "You are unhealthy") #why is this not working??? when I input the temperature at a whole number, it's fine. When I type in 37.888888, the terminal spits out error. I tried adjusting it and it didn't work A: temperature=int(input("What temperature are you?")) When you pass a string to int(), it must be a whole number. Decimals like 37.8 aren't allowed. I think you could just use float() instead of int().
I'm doing some basic logic function + decimal rounding stuff, and this doesn't seem to work...why?
temperature=int(input("What temperature are you?")) if temperature>=37 and temperature<50: print("your temperature is healthy, as it is" , "%.2f" %temperature) else: print("You said your temperature was" , "%.2f" %temperature , "You are unhealthy") #why is this not working??? when I input the temperature at a whole number, it's fine. When I type in 37.888888, the terminal spits out error. I tried adjusting it and it didn't work
[ "temperature=int(input(\"What temperature are you?\"))\n\nWhen you pass a string to int(), it must be a whole number. Decimals like 37.8 aren't allowed.\nI think you could just use float() instead of int().\n" ]
[ 0 ]
[]
[]
[ "decimal", "logic", "python", "variables" ]
stackoverflow_0074672016_decimal_logic_python_variables.txt
Q: A-Frame Game Loop Basics: How can I seperate logic from rendering? I'm dabbling with A-Frame and my Quest 2 headset, trying to make a simple VR game. I'm having trouble wrapping my head around separating logic from rendering and implementing a proper game loop. I found this tutorial... https://medium.com/@mattnutsch/tutorial-how-to-make-webxr-games-with-a-frame-eedd98613a88 ...of a simple A-Frame game programmed in a non-OOP style that I initially found handy, coming from a past dabbling with basic C game programming, though I'm struggling with how I can create a basic game loop in that same non-OOP style that separates game logic from rendering. I cooked-up a game but didn't think of the consequences of lower FPS cases, plus the fun that is varying refresh rates on a Quest 2 headset, causing all kinds of issues with home-brewed movement and physics being tied to rendering capabilities. In particular, I made a ball throwing mechanic that's pretty broken with logic and rendering tied together. I distilled my problem into a very simple bouncing ball demo on this JSFiddle to demonstrate the issue... https://jsfiddle.net/mikegyoung/gny1w7mu/1/ I guess the portion I'm questioning is at/around line 115... ` // game loop AFRAME.registerComponent('game-loop', { init: function () { this.throttledFunction = AFRAME.utils.throttle(this.gameLoop, gameLoopSpeed, this); }, gameLoop: function () { }, tick: function (t, dt) { this.throttledFunction(); // called every frame. } }); ` In it, I have a bouncing ball in a cube, I add a ton of random triangles to the scene to simulate a low FPS situation, and when you move in (WASD) and use the mouse to glance away from the triangles and only look at the ball, the ball moves faster when at/near full FPS. I'm wondering how I'd go about having my logic independent from rendering, so the ball moves at the same speed regardless of low FPS situations. Not sure what I'm programmatically missing here from having very lacking JS chops. Thanks! I've tried looking for other simple examples of a proper game loop in A-Frame, in more of the non-OOP style I find easy to understand for starters, but didn't have any luck. I have dabbled with some basic 2D game programming with JS and HTML5, going off the handy example from Mozilla Developer Network Web Docs... https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript ...but it seems like A-Frame abstracts things away more. Thanks! A: I've ultimately decided that just moving to using three.js from the start would be the best route. I found this tremendously helpful example in an answer to another question posed on Stack Overflow... WebXR controllers for button pressing in three.js Thus far I've tried implementing a throwable, bouncing ball, with logic and rendering separated, based on information found here... https://isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing ...and I've tried implementing a HUD for debugging... https://jsfiddle.net/f7oa6r0t/ See line 296 for HUD snippets See line 430 for game loop snippets Undoubtedly a very simplistic set of additions on my part, and maybe not well implemented, but a starting point to building something more creative.
A-Frame Game Loop Basics: How can I seperate logic from rendering?
I'm dabbling with A-Frame and my Quest 2 headset, trying to make a simple VR game. I'm having trouble wrapping my head around separating logic from rendering and implementing a proper game loop. I found this tutorial... https://medium.com/@mattnutsch/tutorial-how-to-make-webxr-games-with-a-frame-eedd98613a88 ...of a simple A-Frame game programmed in a non-OOP style that I initially found handy, coming from a past dabbling with basic C game programming, though I'm struggling with how I can create a basic game loop in that same non-OOP style that separates game logic from rendering. I cooked-up a game but didn't think of the consequences of lower FPS cases, plus the fun that is varying refresh rates on a Quest 2 headset, causing all kinds of issues with home-brewed movement and physics being tied to rendering capabilities. In particular, I made a ball throwing mechanic that's pretty broken with logic and rendering tied together. I distilled my problem into a very simple bouncing ball demo on this JSFiddle to demonstrate the issue... https://jsfiddle.net/mikegyoung/gny1w7mu/1/ I guess the portion I'm questioning is at/around line 115... ` // game loop AFRAME.registerComponent('game-loop', { init: function () { this.throttledFunction = AFRAME.utils.throttle(this.gameLoop, gameLoopSpeed, this); }, gameLoop: function () { }, tick: function (t, dt) { this.throttledFunction(); // called every frame. } }); ` In it, I have a bouncing ball in a cube, I add a ton of random triangles to the scene to simulate a low FPS situation, and when you move in (WASD) and use the mouse to glance away from the triangles and only look at the ball, the ball moves faster when at/near full FPS. I'm wondering how I'd go about having my logic independent from rendering, so the ball moves at the same speed regardless of low FPS situations. Not sure what I'm programmatically missing here from having very lacking JS chops. Thanks! I've tried looking for other simple examples of a proper game loop in A-Frame, in more of the non-OOP style I find easy to understand for starters, but didn't have any luck. I have dabbled with some basic 2D game programming with JS and HTML5, going off the handy example from Mozilla Developer Network Web Docs... https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript ...but it seems like A-Frame abstracts things away more. Thanks!
[ "I've ultimately decided that just moving to using three.js from the start would be the best route. I found this tremendously helpful example in an answer to another question posed on Stack Overflow...\nWebXR controllers for button pressing in three.js\nThus far I've tried implementing a throwable, bouncing ball, with logic and rendering separated, based on information found here...\nhttps://isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing\n...and I've tried implementing a HUD for debugging...\nhttps://jsfiddle.net/f7oa6r0t/\nSee line 296 for HUD snippets\nSee line 430 for game loop snippets\n\nUndoubtedly a very simplistic set of additions on my part, and maybe not well implemented, but a starting point to building something more creative.\n" ]
[ 0 ]
[]
[]
[ "aframe", "game_development", "game_loop", "javascript", "three.js" ]
stackoverflow_0074588361_aframe_game_development_game_loop_javascript_three.js.txt
Q: Plotly Timeline not updating according to selected option of dropdown I have been trying to update the timeline as per the selected item from dropdown but it is not getting plotted as per the selected option. For example, in attached image i have selected B1 but C1 is extra here. I have tried printing x list too, for B1 it gives [False True False False False False False False False False]. Only 1 true at 2nd location, I am not sure where this C1 is coming from. Results get worst when I chose the options below B1. The current result: With the following dataframe used: Dataframe used def multi_plot2(df, addAll = True): grp=df['Group1'].unique() button_all = dict(label = 'All', method = 'update', args = [{'visible': df.columns.isin(df.columns), 'title': 'All', 'showlegend':True}]) def create_layout_button(column): labels=np.array(df['Label']) x=np.zeros(labels.size) i=0 for s in labels: if column in s: print (s) x[i]=1 i=i+1 x=x.astype(np.bool) print(x) return dict(label = column, method = 'restyle', args = [{'visible': x, 'showlegend': True}]) fig2.update_layout( updatemenus=[go.layout.Updatemenu( active = 0, buttons = ([button_all] * addAll) + list(df['Combined'].map(lambda column: create_layout_button(column))) ) ]) fig2.show() An sample of the dataframe used (that can be copy and pasted) {'ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, 'Company': {0: 'Joes', 1: 'Mary', 2: 'Georgia', 3: 'France', 4: 'Butter', 5: 'Player', 6: 'Fish', 7: 'Cattle', 8: 'Swim', 9: 'Seabass'}, 'Label': {0: 'Product_A-1', 1: 'Product_B-1', 2: 'Product_C-1', 3: 'Product_A-2', 4: 'Product_A-2', 5: 'Product_B-2', 6: 'Product_C-3', 7: 'Product_D-3', 8: 'Product_A-3', 9: 'Product_D-3'}, 'Start': {0: '2021-10-31', 1: '2021-05-31', 2: '2021-10-01', 3: '2021-08-21', 4: '2021-10-01', 5: '2021-08-21', 6: '2021-04-18', 7: '2021-10-31', 8: '2021-08-30', 9: '2021-03-31'}, 'End': {0: '2022-10-31', 1: '2022-05-31', 2: '2022-10-01', 3: '2022-08-21', 4: '2022-10-01', 5: '2022-08-21', 6: '2022-04-18', 7: '2022-10-31', 8: '2022-08-30', 9: '2022-03-31'}, 'Group1': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'A', 9: 'D'}, 'Group2': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 3}, 'Color': {0: 'Blue', 1: 'Red', 2: 'Green', 3: 'Yellow', 4: 'Green', 5: 'Yellow', 6: 'Red', 7: 'Green', 8: 'Green', 9: 'Yellow'}, 'Review': {0: 'Excellent', 1: 'Good', 2: 'Bad', 3: 'Fair', 4: 'Good', 5: 'Bad', 6: 'Fair', 7: 'Excellent', 8: 'Good', 9: 'Bad'}, 'url': {0: 'https://www.10xgenomics.com/', 1: 'http://www.3d-medicines.com', 2: 'https://www.89bio.com/', 3: 'https://www.acimmune.com/', 4: 'https://www.acastipharma.com', 5: 'https://acceleratediagnostics.com', 6: 'http://acceleronpharma.com/', 7: 'https://www.acell.com/', 8: 'https://www.acelrx.com', 9: 'https://achievelifesciences.com/'}, 'Combined': {0: 'A-1', 1: 'B-1', 2: 'C-1', 3: 'A-2', 4: 'A-2', 5: 'B-2', 6: 'C-3', 7: 'D-3', 8: 'A-3', 9: 'D-3'}} A: As far as I can tell, px.timeline produces a figure with one trace. This means that when you pass a boolean array to the visible argument for your buttons, clicking on these buttons these buttons won't correctly update the figure. Although it's not a very elegant solution, my suggestion would be that you recreate the px.timeline figure using multiple go.Bar traces – one trace for each product label. Then when you pass boolean array to the 'visible' argument as you did in your original code, the buttons should function correctly. It's not perfect because the horizontal bars don't quite align with the labels (not sure why - any improvements would be greatly appreciated), but here is an example of what you can accomplish: import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go df = pd.DataFrame( {'ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, 'Company': {0: 'Joes', 1: 'Mary', 2: 'Georgia', 3: 'France', 4: 'Butter', 5: 'Player', 6: 'Fish', 7: 'Cattle', 8: 'Swim', 9: 'Seabass'}, 'Label': {0: 'Product_A-1', 1: 'Product_B-1', 2: 'Product_C-1', 3: 'Product_A-2', 4: 'Product_A-2', 5: 'Product_B-2', 6: 'Product_C-3', 7: 'Product_D-3', 8: 'Product_A-3', 9: 'Product_D-3'}, 'Start': {0: '2021-10-31', 1: '2021-05-31', 2: '2021-10-01', 3: '2021-08-21', 4: '2021-10-01', 5: '2021-08-21', 6: '2021-04-18', 7: '2021-10-31', 8: '2021-08-30', 9: '2021-03-31'}, 'End': {0: '2022-10-31', 1: '2022-05-31', 2: '2022-10-01', 3: '2022-08-21', 4: '2022-10-01', 5: '2022-08-21', 6: '2022-04-18', 7: '2022-10-31', 8: '2022-08-30', 9: '2022-03-31'}, 'Group1': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'A', 9: 'D'}, 'Group2': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 3}, 'Color': {0: 'Blue', 1: 'Red', 2: 'Green', 3: 'Yellow', 4: 'Green', 5: 'Yellow', 6: 'Red', 7: 'Green', 8: 'Green', 9: 'Yellow'}, 'Review': {0: 'Excellent', 1: 'Good', 2: 'Bad', 3: 'Fair', 4: 'Good', 5: 'Bad', 6: 'Fair', 7: 'Excellent', 8: 'Good', 9: 'Bad'}, 'url': {0: 'https://www.10xgenomics.com/', 1: 'http://www.3d-medicines.com', 2: 'https://www.89bio.com/', 3: 'https://www.acimmune.com/', 4: 'https://www.acastipharma.com', 5: 'https://acceleratediagnostics.com', 6: 'http://acceleronpharma.com/', 7: 'https://www.acell.com/', 8: 'https://www.acelrx.com', 9: 'https://achievelifesciences.com/'}, 'Combined': {0: 'A-1', 1: 'B-1', 2: 'C-1', 3: 'A-2', 4: 'A-2', 5: 'B-2', 6: 'C-3', 7: 'D-3', 8: 'B-1', 9: 'D-3'}} ) # fig2 = px.timeline( # df, x_start='Start', x_end='End', y='Label' # ) fig2 = go.Figure() df['Start'] = pd.to_datetime(df['Start'], format="%Y-%m-%d") df['End'] = pd.to_datetime(df['End'], format="%Y-%m-%d") button_all = [ dict(label="All", method="update", args = [{'visible': [True]*len(df)}]) ] button_labels = [] for label in df['Combined'].unique(): df_label = df.loc[df['Combined'] == label, ['Start','End','Label']] # extract milliseconds df_label['Diff'] = [d.total_seconds()*10**3 for d in ( df_label['End'] - df_label['Start'] )] fig2.add_trace(go.Bar( base=df_label['Start'].tolist(), x=df_label['Diff'].tolist(), y=df_label['Label'].tolist(), xcalendar='gregorian', orientation='h' )) all_trace_labels = [trace['y'][0] for trace in fig2.data] for trace in fig2.data: label = trace['y'][0] visible_array = [t == label for t in all_trace_labels] button_labels.append( dict(label=label, method="update", args = [{'visible': visible_array}]) ) fig2.update_layout( updatemenus=[ dict( type="dropdown", direction="down", buttons=button_all + button_labels, ) ], xaxis = { 'anchor': 'y', 'automargin': True, 'autorange': True, 'autotypenumbers': 'strict', 'calendar': 'gregorian', 'domain': [0, 1], 'dtick': 'M3', 'tick0': '2000-01-01', 'type': 'date' }, yaxis = { 'anchor': 'x', 'automargin': True, 'autorange': True, 'autotypenumbers': 'strict', 'categoryorder': 'trace', 'domain': [0, 1], 'dtick': 1, 'side': 'left', 'tick0': 0, 'type': 'category' } ) fig2.show()
Plotly Timeline not updating according to selected option of dropdown
I have been trying to update the timeline as per the selected item from dropdown but it is not getting plotted as per the selected option. For example, in attached image i have selected B1 but C1 is extra here. I have tried printing x list too, for B1 it gives [False True False False False False False False False False]. Only 1 true at 2nd location, I am not sure where this C1 is coming from. Results get worst when I chose the options below B1. The current result: With the following dataframe used: Dataframe used def multi_plot2(df, addAll = True): grp=df['Group1'].unique() button_all = dict(label = 'All', method = 'update', args = [{'visible': df.columns.isin(df.columns), 'title': 'All', 'showlegend':True}]) def create_layout_button(column): labels=np.array(df['Label']) x=np.zeros(labels.size) i=0 for s in labels: if column in s: print (s) x[i]=1 i=i+1 x=x.astype(np.bool) print(x) return dict(label = column, method = 'restyle', args = [{'visible': x, 'showlegend': True}]) fig2.update_layout( updatemenus=[go.layout.Updatemenu( active = 0, buttons = ([button_all] * addAll) + list(df['Combined'].map(lambda column: create_layout_button(column))) ) ]) fig2.show() An sample of the dataframe used (that can be copy and pasted) {'ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, 'Company': {0: 'Joes', 1: 'Mary', 2: 'Georgia', 3: 'France', 4: 'Butter', 5: 'Player', 6: 'Fish', 7: 'Cattle', 8: 'Swim', 9: 'Seabass'}, 'Label': {0: 'Product_A-1', 1: 'Product_B-1', 2: 'Product_C-1', 3: 'Product_A-2', 4: 'Product_A-2', 5: 'Product_B-2', 6: 'Product_C-3', 7: 'Product_D-3', 8: 'Product_A-3', 9: 'Product_D-3'}, 'Start': {0: '2021-10-31', 1: '2021-05-31', 2: '2021-10-01', 3: '2021-08-21', 4: '2021-10-01', 5: '2021-08-21', 6: '2021-04-18', 7: '2021-10-31', 8: '2021-08-30', 9: '2021-03-31'}, 'End': {0: '2022-10-31', 1: '2022-05-31', 2: '2022-10-01', 3: '2022-08-21', 4: '2022-10-01', 5: '2022-08-21', 6: '2022-04-18', 7: '2022-10-31', 8: '2022-08-30', 9: '2022-03-31'}, 'Group1': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'A', 9: 'D'}, 'Group2': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 3}, 'Color': {0: 'Blue', 1: 'Red', 2: 'Green', 3: 'Yellow', 4: 'Green', 5: 'Yellow', 6: 'Red', 7: 'Green', 8: 'Green', 9: 'Yellow'}, 'Review': {0: 'Excellent', 1: 'Good', 2: 'Bad', 3: 'Fair', 4: 'Good', 5: 'Bad', 6: 'Fair', 7: 'Excellent', 8: 'Good', 9: 'Bad'}, 'url': {0: 'https://www.10xgenomics.com/', 1: 'http://www.3d-medicines.com', 2: 'https://www.89bio.com/', 3: 'https://www.acimmune.com/', 4: 'https://www.acastipharma.com', 5: 'https://acceleratediagnostics.com', 6: 'http://acceleronpharma.com/', 7: 'https://www.acell.com/', 8: 'https://www.acelrx.com', 9: 'https://achievelifesciences.com/'}, 'Combined': {0: 'A-1', 1: 'B-1', 2: 'C-1', 3: 'A-2', 4: 'A-2', 5: 'B-2', 6: 'C-3', 7: 'D-3', 8: 'A-3', 9: 'D-3'}}
[ "As far as I can tell, px.timeline produces a figure with one trace. This means that when you pass a boolean array to the visible argument for your buttons, clicking on these buttons these buttons won't correctly update the figure.\nAlthough it's not a very elegant solution, my suggestion would be that you recreate the px.timeline figure using multiple go.Bar traces – one trace for each product label. Then when you pass boolean array to the 'visible' argument as you did in your original code, the buttons should function correctly.\nIt's not perfect because the horizontal bars don't quite align with the labels (not sure why - any improvements would be greatly appreciated), but here is an example of what you can accomplish:\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\n\ndf = pd.DataFrame(\n {'ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10},\n 'Company': {0: 'Joes',\n 1: 'Mary',\n 2: 'Georgia',\n 3: 'France',\n 4: 'Butter',\n 5: 'Player',\n 6: 'Fish',\n 7: 'Cattle',\n 8: 'Swim',\n 9: 'Seabass'},\n 'Label': {0: 'Product_A-1',\n 1: 'Product_B-1',\n 2: 'Product_C-1',\n 3: 'Product_A-2',\n 4: 'Product_A-2',\n 5: 'Product_B-2',\n 6: 'Product_C-3',\n 7: 'Product_D-3',\n 8: 'Product_A-3',\n 9: 'Product_D-3'},\n 'Start': {0: '2021-10-31',\n 1: '2021-05-31',\n 2: '2021-10-01',\n 3: '2021-08-21',\n 4: '2021-10-01',\n 5: '2021-08-21',\n 6: '2021-04-18',\n 7: '2021-10-31',\n 8: '2021-08-30',\n 9: '2021-03-31'},\n 'End': {0: '2022-10-31',\n 1: '2022-05-31',\n 2: '2022-10-01',\n 3: '2022-08-21',\n 4: '2022-10-01',\n 5: '2022-08-21',\n 6: '2022-04-18',\n 7: '2022-10-31',\n 8: '2022-08-30',\n 9: '2022-03-31'},\n 'Group1': {0: 'A',\n 1: 'B',\n 2: 'C',\n 3: 'A',\n 4: 'A',\n 5: 'B',\n 6: 'C',\n 7: 'D',\n 8: 'A',\n 9: 'D'},\n 'Group2': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 3},\n 'Color': {0: 'Blue',\n 1: 'Red',\n 2: 'Green',\n 3: 'Yellow',\n 4: 'Green',\n 5: 'Yellow',\n 6: 'Red',\n 7: 'Green',\n 8: 'Green',\n 9: 'Yellow'},\n 'Review': {0: 'Excellent',\n 1: 'Good',\n 2: 'Bad',\n 3: 'Fair',\n 4: 'Good',\n 5: 'Bad',\n 6: 'Fair',\n 7: 'Excellent',\n 8: 'Good',\n 9: 'Bad'},\n 'url': {0: 'https://www.10xgenomics.com/',\n 1: 'http://www.3d-medicines.com',\n 2: 'https://www.89bio.com/',\n 3: 'https://www.acimmune.com/',\n 4: 'https://www.acastipharma.com',\n 5: 'https://acceleratediagnostics.com',\n 6: 'http://acceleronpharma.com/',\n 7: 'https://www.acell.com/',\n 8: 'https://www.acelrx.com',\n 9: 'https://achievelifesciences.com/'},\n 'Combined': {0: 'A-1',\n 1: 'B-1',\n 2: 'C-1',\n 3: 'A-2',\n 4: 'A-2',\n 5: 'B-2',\n 6: 'C-3',\n 7: 'D-3',\n 8: 'B-1',\n 9: 'D-3'}}\n)\n\n# fig2 = px.timeline(\n# df, x_start='Start', x_end='End', y='Label'\n# )\n\nfig2 = go.Figure()\n\ndf['Start'] = pd.to_datetime(df['Start'], format=\"%Y-%m-%d\")\ndf['End'] = pd.to_datetime(df['End'], format=\"%Y-%m-%d\")\n\nbutton_all = [\n dict(label=\"All\",\n method=\"update\",\n args = [{'visible': [True]*len(df)}])\n ]\n\nbutton_labels = []\nfor label in df['Combined'].unique():\n df_label = df.loc[df['Combined'] == label, ['Start','End','Label']]\n\n # extract milliseconds\n df_label['Diff'] = [d.total_seconds()*10**3 for d in (\n df_label['End'] - df_label['Start']\n )]\n\n fig2.add_trace(go.Bar(\n base=df_label['Start'].tolist(),\n x=df_label['Diff'].tolist(),\n y=df_label['Label'].tolist(),\n xcalendar='gregorian',\n orientation='h'\n ))\n\nall_trace_labels = [trace['y'][0] for trace in fig2.data]\nfor trace in fig2.data:\n label = trace['y'][0]\n visible_array = [t == label for t in all_trace_labels]\n button_labels.append(\n dict(label=label,\n method=\"update\",\n args = [{'visible': visible_array}])\n )\n\nfig2.update_layout(\n updatemenus=[\n dict(\n type=\"dropdown\",\n direction=\"down\",\n buttons=button_all + button_labels,\n )\n ],\n xaxis = {\n 'anchor': 'y',\n 'automargin': True,\n 'autorange': True,\n 'autotypenumbers': 'strict',\n 'calendar': 'gregorian',\n 'domain': [0, 1],\n 'dtick': 'M3',\n 'tick0': '2000-01-01',\n 'type': 'date'\n },\n yaxis = {\n 'anchor': 'x',\n 'automargin': True,\n 'autorange': True,\n 'autotypenumbers': 'strict',\n 'categoryorder': 'trace',\n 'domain': [0, 1],\n 'dtick': 1,\n 'side': 'left',\n 'tick0': 0,\n 'type': 'category'\n }\n)\n\nfig2.show()\n\n\n" ]
[ 0 ]
[]
[]
[ "drop_down_menu", "gantt_chart", "plotly", "timeline" ]
stackoverflow_0074607668_drop_down_menu_gantt_chart_plotly_timeline.txt
Q: FirebaseList in Flutter duplicates all values I think I'm misunderstanding how the FirebaseList widget in Flutter is working. I'm using Firebase Realtime Database for the chat feature in my app with this data: { "chatMessageOne": {...}, } Here is how I'm using the widget: List<ChatMessage> chatMessages = []; @override void initState() { // dbRef = dbInstance.ref("/events/${widget.event.event.eventId}"); dbRef = dbInstance.ref("/events/"); var query = dbRef!.child(widget.event.event.eventId); FirebaseList( query: query, onChildAdded: (index, snapshot) { Map<dynamic, dynamic> childMap = snapshot.value as dynamic; ChatMessage newChatMessage = ChatMessage( chatMessageId: snapshot.key.toString(), userId: childMap["userId"], displayName: childMap["displayName"], message: childMap["message"], datetime: childMap["datetime"], ); chatMessages.add(newChatMessage); print("onChildAdded:chatMessages: $chatMessages"); // prints [Instance of 'ChatMessage'] }, onValue: (snapshot) { for (var child in snapshot.children) { Map<dynamic, dynamic> childMap = child.value as dynamic; ChatMessage newChatMessage = ChatMessage( chatMessageId: child.key.toString(), userId: childMap["userId"], displayName: childMap["displayName"], message: childMap["message"], datetime: childMap["datetime"], ); chatMessages.add(newChatMessage); } print("onValue:chatMessages: $chatMessages"); // prints [Instance of 'ChatMessage', Instance of 'ChatMessage'] }, ); _messageFieldController = TextEditingController(); super.initState(); } I'm then using a ListView Builder in my build method to display all the messages. For some reason, nothing displays when the screen first opens but chatMessages list has data that you can see from the print statements. If I hot reload (not resetting state) the screen two messages (the same one duplicated twice) will be displayed despite there only being one message in the database. Additionally, if I send a message then it seems to retrieve all the messages in the database and display them all at once instead of just the new one... A: With the code you shared you'll indeed see all messages twice: onChildAdded gets called for each child node under query right away, and then whenever a new node is added. onValue gets called with existing child node under query right away, and then whenever there is any change to that data. If you implement this method, you'll also want to clear chatMessages each time onValue gets called - as it always gets a snapshot with all messages, not just the changes. So you should implement one or the other, not both.
FirebaseList in Flutter duplicates all values
I think I'm misunderstanding how the FirebaseList widget in Flutter is working. I'm using Firebase Realtime Database for the chat feature in my app with this data: { "chatMessageOne": {...}, } Here is how I'm using the widget: List<ChatMessage> chatMessages = []; @override void initState() { // dbRef = dbInstance.ref("/events/${widget.event.event.eventId}"); dbRef = dbInstance.ref("/events/"); var query = dbRef!.child(widget.event.event.eventId); FirebaseList( query: query, onChildAdded: (index, snapshot) { Map<dynamic, dynamic> childMap = snapshot.value as dynamic; ChatMessage newChatMessage = ChatMessage( chatMessageId: snapshot.key.toString(), userId: childMap["userId"], displayName: childMap["displayName"], message: childMap["message"], datetime: childMap["datetime"], ); chatMessages.add(newChatMessage); print("onChildAdded:chatMessages: $chatMessages"); // prints [Instance of 'ChatMessage'] }, onValue: (snapshot) { for (var child in snapshot.children) { Map<dynamic, dynamic> childMap = child.value as dynamic; ChatMessage newChatMessage = ChatMessage( chatMessageId: child.key.toString(), userId: childMap["userId"], displayName: childMap["displayName"], message: childMap["message"], datetime: childMap["datetime"], ); chatMessages.add(newChatMessage); } print("onValue:chatMessages: $chatMessages"); // prints [Instance of 'ChatMessage', Instance of 'ChatMessage'] }, ); _messageFieldController = TextEditingController(); super.initState(); } I'm then using a ListView Builder in my build method to display all the messages. For some reason, nothing displays when the screen first opens but chatMessages list has data that you can see from the print statements. If I hot reload (not resetting state) the screen two messages (the same one duplicated twice) will be displayed despite there only being one message in the database. Additionally, if I send a message then it seems to retrieve all the messages in the database and display them all at once instead of just the new one...
[ "With the code you shared you'll indeed see all messages twice:\n\nonChildAdded gets called for each child node under query right away, and then whenever a new node is added.\nonValue gets called with existing child node under query right away, and then whenever there is any change to that data. If you implement this method, you'll also want to clear chatMessages each time onValue gets called - as it always gets a snapshot with all messages, not just the changes.\n\nSo you should implement one or the other, not both.\n" ]
[ 1 ]
[]
[]
[ "dart", "firebase", "firebase_realtime_database", "flutter" ]
stackoverflow_0074672021_dart_firebase_firebase_realtime_database_flutter.txt
Q: I have problems with Java JMenuBar overlapping my JPanel I am creating a game and wanted to add a menu with some additional options for the user such as saving, loading or redirecting to a website, but after starting of the game and clicking on the JMenu I got a problem. the panel before clicking the menu: the panel after clicking the menu: The problem is that after opening the JMenu "Settings" - it overlaps my JPanel and I want to somehow fix it so it does not overlap. What am I doing wrong? This is my code: public class UpperFramePanel extends JMenuBar { public UpperFramePanel(JFrame frame) { JMenu menu1 = new JMenu("Settings"); menu1.add(new JMenuItem("Load")); menu1.add(new JMenuItem("Save")); menu1.add(new JSeparator()); menu1.add(new JMenuItem(new AbstractAction("Rules") { @Override public void actionPerformed(ActionEvent e) { URI uri = null; try { uri = new URI("https://www.worldothello.org/about/about-othello/othello-rules/official-rules/english"); java.awt.Desktop.getDesktop().browse(uri); } catch (URISyntaxException | IOException ignored) { } } })); this.add(menu1); frame.setJMenuBar(this); } }
I have problems with Java JMenuBar overlapping my JPanel
I am creating a game and wanted to add a menu with some additional options for the user such as saving, loading or redirecting to a website, but after starting of the game and clicking on the JMenu I got a problem. the panel before clicking the menu: the panel after clicking the menu: The problem is that after opening the JMenu "Settings" - it overlaps my JPanel and I want to somehow fix it so it does not overlap. What am I doing wrong? This is my code: public class UpperFramePanel extends JMenuBar { public UpperFramePanel(JFrame frame) { JMenu menu1 = new JMenu("Settings"); menu1.add(new JMenuItem("Load")); menu1.add(new JMenuItem("Save")); menu1.add(new JSeparator()); menu1.add(new JMenuItem(new AbstractAction("Rules") { @Override public void actionPerformed(ActionEvent e) { URI uri = null; try { uri = new URI("https://www.worldothello.org/about/about-othello/othello-rules/official-rules/english"); java.awt.Desktop.getDesktop().browse(uri); } catch (URISyntaxException | IOException ignored) { } } })); this.add(menu1); frame.setJMenuBar(this); } }
[]
[]
[ "To fix the issue where the JMenu overlaps the JPanel in your game, you can use the setBounds method of the JMenu class to specify the size and position of the menu on the screen. This will prevent the menu from overlapping the JPanel and allow it to be displayed in the desired location.\nHere is an example of how you can use the setBounds method to fix the overlap issue in your code:\npublic class UpperFramePanel extends JMenuBar {\n public UpperFramePanel(JFrame frame) {\n JMenu menu1 = new JMenu(\"Settings\");\n\n menu1.add(new JMenuItem(\"Load\"));\n menu1.add(new JMenuItem(\"Save\"));\n menu1.add(new JSeparator());\n menu1.add(new JMenuItem(new AbstractAction(\"Rules\") {\n @Override\n public void actionPerformed(ActionEvent e) {\n URI uri = null;\n try {\n uri = new URI(\"https://www.worldothello.org/about/about-othello/othello-rules/official-rules/english\");\n java.awt.Desktop.getDesktop().browse(uri);\n } catch (URISyntaxException | IOException ignored) {\n }\n }\n }));\n\n // set the bounds of the menu to prevent overlap\n menu1.setBounds(0, 0, 100, 20);\n\n this.add(menu1);\n frame.setJMenuBar(this);\n }\n}\n\nIn this updated code, the setBounds method is used to specify the size and position of the JMenu object.\n" ]
[ -3 ]
[ "java", "jmenubar", "jmenuitem", "jpanel", "swing" ]
stackoverflow_0074671945_java_jmenubar_jmenuitem_jpanel_swing.txt
Q: data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0 I have downloaded Portainer onto my server and created a PostgreSQL database in a container there. Today I could no longer get access to the database. The log shows a message that there is a version problem. I already read into some similar issues like Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one and Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one and the solutions brew postgresql-upgrade-database did not work. What can I do? LOG 2021-10-03 [1] FATAL: database files are incompatible with server 2021-10-03 [1] DETAIL: The data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0 (Debian 14.0-1.pgdg110+1). PostgreSQL Database directory appears to contain a database; Skipping initialization I also found this https://www.postgresql.org/docs/14/upgrading.html but the commands didn't work. Do I need to do this in the container somehow, or what commands will work to keep it running in the container? A: You need to update the data file to the new format with this command: $ brew postgresql-upgrade-database A: I resolved it by Removing the postgres image Remove the volume Pull the image again Assuming you know the docker commands for above step. A: On top of the answer suggesting removing all volumes/images/containers - if you have a shared volume for the DB in docker-compose.yml, like: db: image: postgres:14.1-alpine volumes: - ./tmp/db:/var/lib/postgresql/data You will also need to remove the postgres mapped volume data which lives in ./tmp/db. Otherwise those conflicting files would still be there. If you don't care about the data - you use the database for development purposes and you'll be able to re-create the db easily, just run rm -r ./tmp/db. Than you can just docker-compose up and re-create your database. In case you care about the data, use pg_dumpall to dump you data before removing the files and restore after you run docker-compose up and your postgres service is ready again. A: had a problem after running brew update brew upgrade Brew upgraded postgresql to 14 which gave me psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I have also seen the same error you have by inspecting tail /usr/local/var/postgres/server.log I have downgraded to version 13 running brew uninstall postgresql brew install postgresql@13 echo 'export PATH="/usr/local/opt/postgresql@13/bin:$PATH"' >> ~/.zshrc and the command I've used to start the DB again is pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start A: I think because of the difference postgresql13 with 14 in initialization. You can make a backup of your database before the new version, delete it and migrate database to the new version for example in django: dump: ./manage.py dumpdata -o mydata.json load: ./manage.py loaddata mydata.json django: Of course, if you have important information, do this separately for each model and pay attention to the dependencies when loading. A: I was also facing the same issue with postgres in keycloak. Downgrading the version to 13 resolved my issue. A: for me the database directory was in /tmp/db and since no important data was there I remove all and everything worked well ... but if your data is important then read these: https://www.postgresql.org/docs/13/upgrading.html https://www.postgresql.org/docs/13/pgupgrade.html https://www.kostolansky.sk/posts/upgrading-to-postgresql-14/ A: In docker-compose.yml you could change db-data:/var/lib/postgresql/data:rw to this db-data:/var/lib/postgresql@14/data:rw Delete image and run docker-compose up -d one more time A: I had the same issue after home brew update on my mac - Install @14 of postgresql This is what help to me: Install old binaries v13 brew install postgresql@13 Backup Your old DB folder Initdb with new name now use pg_upgrade like this: pg_upgrade --old-datadir [Your old DB folder] --new-datadir [Your new DB folder] --old-bindir [link to old bin (v13)] for example: pg_upgrade --old-datadir PSQ-data --new-datadir PSQ-data_new --old-bindir /usr/local/Cellar/postgresql@13/13.9/bin Source for old bin You will have after install @13, just look what you receive on terminal after install "Summary". After this operation just start sever with new DB A: I resolved it by Removing the postgres container docker rm "container name" Removing the postgres image docker rmi "image name" docker-compose stop docker-compose down list all volumes docker volume ls remove volume docker volume rm "volume name" Pull the image again Assuming you know the docker commands for above step.
data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0
I have downloaded Portainer onto my server and created a PostgreSQL database in a container there. Today I could no longer get access to the database. The log shows a message that there is a version problem. I already read into some similar issues like Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one and Postgres container crashes with `database files are incompatible with server` after container's image has been updated to the latest one and the solutions brew postgresql-upgrade-database did not work. What can I do? LOG 2021-10-03 [1] FATAL: database files are incompatible with server 2021-10-03 [1] DETAIL: The data directory was initialized by PostgreSQL version 13, which is not compatible with this version 14.0 (Debian 14.0-1.pgdg110+1). PostgreSQL Database directory appears to contain a database; Skipping initialization I also found this https://www.postgresql.org/docs/14/upgrading.html but the commands didn't work. Do I need to do this in the container somehow, or what commands will work to keep it running in the container?
[ "You need to update the data file to the new format with this command:\n$ brew postgresql-upgrade-database \n\n", "I resolved it by\n\nRemoving the postgres image\nRemove the volume\nPull the image again\n\nAssuming you know the docker commands for above step.\n", "On top of the answer suggesting removing all volumes/images/containers - if you have a shared volume for the DB in docker-compose.yml, like:\ndb:\n image: postgres:14.1-alpine\n volumes:\n - ./tmp/db:/var/lib/postgresql/data\n\nYou will also need to remove the postgres mapped volume data which lives in ./tmp/db. Otherwise those conflicting files would still be there.\nIf you don't care about the data - you use the database for development purposes and you'll be able to re-create the db easily, just run rm -r ./tmp/db. Than you can just docker-compose up and re-create your database.\nIn case you care about the data, use pg_dumpall to dump you data before removing the files and restore after you run docker-compose up and your postgres service is ready again.\n", "had a problem after running\nbrew update\nbrew upgrade\nBrew upgraded postgresql to 14 which gave me\npsql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket \"/var/run/postgresql/.s.PGSQL.5432\"?\nI have also seen the same error you have by inspecting\ntail /usr/local/var/postgres/server.log\nI have downgraded to version 13 running\nbrew uninstall postgresql\nbrew install postgresql@13\necho 'export PATH=\"/usr/local/opt/postgresql@13/bin:$PATH\"' >> ~/.zshrc\nand the command I've used to start the DB again is\npg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start\n", "I think because of the difference postgresql13 with 14 in initialization.\nYou can make a backup of your database before the new version, delete it and migrate database to the new version\nfor example in django:\ndump: ./manage.py dumpdata -o mydata.json\nload: ./manage.py loaddata mydata.json\n\n\ndjango: Of course, if you have important information, do this separately for each model and pay attention to the dependencies when loading.\n\n", "I was also facing the same issue with postgres in keycloak.\nDowngrading the version to 13 resolved my issue.\n", "for me the database directory was in /tmp/db and since no important data was there I remove all and everything worked well ...\nbut if your data is important then read these:\n\nhttps://www.postgresql.org/docs/13/upgrading.html\nhttps://www.postgresql.org/docs/13/pgupgrade.html\nhttps://www.kostolansky.sk/posts/upgrading-to-postgresql-14/\n\n", "In docker-compose.yml you could change\ndb-data:/var/lib/postgresql/data:rw\n\nto this\ndb-data:/var/lib/postgresql@14/data:rw\n\nDelete image and run\ndocker-compose up -d\n\none more time\n", "I had the same issue after home brew update on my mac - Install @14 of postgresql\nThis is what help to me:\nInstall old binaries v13\n\nbrew install postgresql@13\n\nBackup Your old DB folder\nInitdb with new name\nnow use pg_upgrade like this:\n\npg_upgrade --old-datadir [Your old DB folder] --new-datadir [Your new\nDB folder] --old-bindir [link to old bin (v13)]\n\nfor example:\n\npg_upgrade --old-datadir PSQ-data --new-datadir PSQ-data_new\n--old-bindir /usr/local/Cellar/postgresql@13/13.9/bin\n\nSource for old bin You will have after install @13, just look what you receive on terminal after install \"Summary\".\nAfter this operation just start sever with new DB\n", "I resolved it by\n\nRemoving the postgres container\ndocker rm \"container name\"\nRemoving the postgres image\ndocker rmi \"image name\"\ndocker-compose stop\ndocker-compose down\nlist all volumes\ndocker volume ls\nremove volume\ndocker volume rm \"volume name\"\n\nPull the image again\nAssuming you know the docker commands for above step.\n" ]
[ 26, 14, 4, 4, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "debian", "docker", "portainer", "postgresql" ]
stackoverflow_0069424563_debian_docker_portainer_postgresql.txt
Q: How to integrate remove.bg api into a react native app? I'm trying to integrate the remove.bg API into a react native app. However, I'm not sure how to call a node js file from a react native button. Please let me know if I can clarify anything. Thanks for responces! React Native JS Code containing remove.bg code: global.Buffer = global.Buffer || require('buffer').Buffer const axios = require('axios'); const FormData = require('form-data'); const fs = require('fs'); const path = require('path'); const { newinputPath } = require('../Wardrobe'); const inputPath = newinputPath; const formData = new FormData(); formData.append('size', 'auto'); formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath)); axios({ method: 'post', url: 'https://api.remove.bg/v1.0/removebg', data: formData, responseType: 'arraybuffer', headers: { ...formData.getHeaders(), 'X-Api-Key': 'kLJT2Gev5QbZe5epeexwrrKn', }, encoding: null }) .then((response) => { if(response.status != 200) return console.error('Error:', response.status, response.statusText); fs.writeFileSync("pics/no-bg.png", response.data); }) .catch((error) => { return console.error('Request failed:', error); }); Front-end code containing button: import React, { useState, useEffect } from 'react'; import { Button, Image, View, Platform } from 'react-native'; import * as ImagePicker from 'expo-image-picker'; let result; export let newinputPath; export default function ImagePickerExample() { const [image, setImage] = useState(null); const pickImage = async () => { // No permissions request is necessary for launching the image library result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result); if (!result.canceled) { setImage(result.assets[0].uri); } newinputPath = result.assets[0].uri; }; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Button title="Pick an image from camera roll" onPress={pickImage} /> {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />} </View> ); } A: To call a Node.js file from a React Native button, you would first need to import the require function from the react-native package, which is part of the React Native framework. Then, you can use the require function to import the Node.js file. Once the file is imported, you can call its functions from within the React Native button's onPress handler. Here's an example of how this might look: import { require } from 'react-native'; // Import the Node.js file const myNodeJsFile = require('./myNodeJsFile'); function MyReactNativeButton() { return ( <Button onPress={() => { // Call a function from the imported Node.js file myNodeJsFile.myFunction(); }} /> ); } Note that this example assumes that the Node.js file is in the same directory as the React Native component. You may need to adjust the path to the file depending on your project's directory structure.
How to integrate remove.bg api into a react native app?
I'm trying to integrate the remove.bg API into a react native app. However, I'm not sure how to call a node js file from a react native button. Please let me know if I can clarify anything. Thanks for responces! React Native JS Code containing remove.bg code: global.Buffer = global.Buffer || require('buffer').Buffer const axios = require('axios'); const FormData = require('form-data'); const fs = require('fs'); const path = require('path'); const { newinputPath } = require('../Wardrobe'); const inputPath = newinputPath; const formData = new FormData(); formData.append('size', 'auto'); formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath)); axios({ method: 'post', url: 'https://api.remove.bg/v1.0/removebg', data: formData, responseType: 'arraybuffer', headers: { ...formData.getHeaders(), 'X-Api-Key': 'kLJT2Gev5QbZe5epeexwrrKn', }, encoding: null }) .then((response) => { if(response.status != 200) return console.error('Error:', response.status, response.statusText); fs.writeFileSync("pics/no-bg.png", response.data); }) .catch((error) => { return console.error('Request failed:', error); }); Front-end code containing button: import React, { useState, useEffect } from 'react'; import { Button, Image, View, Platform } from 'react-native'; import * as ImagePicker from 'expo-image-picker'; let result; export let newinputPath; export default function ImagePickerExample() { const [image, setImage] = useState(null); const pickImage = async () => { // No permissions request is necessary for launching the image library result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result); if (!result.canceled) { setImage(result.assets[0].uri); } newinputPath = result.assets[0].uri; }; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Button title="Pick an image from camera roll" onPress={pickImage} /> {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />} </View> ); }
[ "To call a Node.js file from a React Native button, you would first need to import the require function from the react-native package, which is part of the React Native framework. Then, you can use the require function to import the Node.js file. Once the file is imported, you can call its functions from within the React Native button's onPress handler. Here's an example of how this might look:\nimport { require } from 'react-native';\n\n// Import the Node.js file\nconst myNodeJsFile = require('./myNodeJsFile');\n\nfunction MyReactNativeButton() {\n return (\n <Button\n onPress={() => {\n // Call a function from the imported Node.js file\n myNodeJsFile.myFunction();\n }}\n />\n );\n}\n\nNote that this example assumes that the Node.js file is in the same directory as the React Native component. You may need to adjust the path to the file depending on your project's directory structure.\n" ]
[ 0 ]
[]
[]
[ "javascript", "react_native", "reactjs" ]
stackoverflow_0074671759_javascript_react_native_reactjs.txt
Q: tensorflow MDA custom loss and ValueError: No gradients provided for any variable I would like to use the MDA (mean direction accuracy) as a custom loss function for a tensorflow neural network. I am trying to implement this as described in here: Custom Mean Directional Accuracy loss function in Keras def mda(y_true, y_pred): s = K.equal(K.sign(y_true[1:] - y_true[:-1]), K.sign(y_pred[1:] - y_pred[:-1])) return K.mean(K.cast(s, K.floatx())) The network works fine but when I try to fit my data I am getting this error: ValueError: No gradients provided for any variable I think that this is because I am loosing the gradient info from my pred tensor but I don't know how can implement this.... or if this makes any sense at all.... Finally I want to predict is if some numeric series is going up or down, that is why this function made sense to me. A: It looks like the error you're seeing is because the mda() function you've defined doesn't have any differentiable operations. Because of this, TensorFlow doesn't know how to compute the gradients of the function, and it's unable to optimize the weights of your neural network using backpropagation. To fix this, you'll need to make sure that your mda() function uses only differentiable operations. This will allow TensorFlow to compute the gradients of the function and use them to optimize the weights of your network. One way to do this would be to use the tf.math.sign() function instead of K.sign(), and the tf.math.reduce_mean() function instead of K.mean() in your mda() function. Both of these functions are differentiable, so TensorFlow will be able to compute the gradients of your mda() function and use them to optimize the weights of your network. Here's an example of how you could modify your mda() function to use differentiable operations: import tensorflow as tf def mda(y_true, y_pred): s = tf.equal(tf.math.sign(y_true[1:] - y_true[:-1]), tf.math.sign(y_pred[1:] - y_pred[:-1])) return tf.math.reduce_mean(tf.cast(s, tf.float32)) This should allow you to use the mda() function as a custom loss function for your TensorFlow neural network. A: The problem is that with K.equal and K.cast, you change numbers into bools. As a result, no gradient can be calculated. You could replace them with a calculation; using the fact that when two numbers are equal, their difference is zero, and that since sign returns only [-1, 0, 1], the absolute difference can only be 0, 1 or 2: def mda(y_true, y_pred): d = K.abs(K.sign(y_true[1:] - y_true[:-1]) - (K.sign(y_pred[1:] - y_pred[:-1]))) s = (1. - d) * (d - 1.) * (d - 2.) / 2. return K.mean(s) s is equal 1 when your K.equal is true, and 0 otherwise A: Thanks Reda and AndrzeO for your answers my question. As AndrzejO mention, equals transform the data to boolean so no gradient there. I implemented this other solution as an alternative to AndrzejO solution: def mda_custom_loss(y_true, y_pred): res = tf.math.sign(y_true[1:] - y_true[:-1]) - tf.math.sign(y_pred[1:] - y_pred[:-1]) s = tf.math.abs(tf.math.sign(res)) return 1 - tf.math.reduce_mean(tf.math.sign(s))
tensorflow MDA custom loss and ValueError: No gradients provided for any variable
I would like to use the MDA (mean direction accuracy) as a custom loss function for a tensorflow neural network. I am trying to implement this as described in here: Custom Mean Directional Accuracy loss function in Keras def mda(y_true, y_pred): s = K.equal(K.sign(y_true[1:] - y_true[:-1]), K.sign(y_pred[1:] - y_pred[:-1])) return K.mean(K.cast(s, K.floatx())) The network works fine but when I try to fit my data I am getting this error: ValueError: No gradients provided for any variable I think that this is because I am loosing the gradient info from my pred tensor but I don't know how can implement this.... or if this makes any sense at all.... Finally I want to predict is if some numeric series is going up or down, that is why this function made sense to me.
[ "It looks like the error you're seeing is because the mda() function you've defined doesn't have any differentiable operations. Because of this, TensorFlow doesn't know how to compute the gradients of the function, and it's unable to optimize the weights of your neural network using backpropagation.\nTo fix this, you'll need to make sure that your mda() function uses only differentiable operations. This will allow TensorFlow to compute the gradients of the function and use them to optimize the weights of your network.\nOne way to do this would be to use the tf.math.sign() function instead of K.sign(), and the tf.math.reduce_mean() function instead of K.mean() in your mda() function. Both of these functions are differentiable, so TensorFlow will be able to compute the gradients of your mda() function and use them to optimize the weights of your network.\nHere's an example of how you could modify your mda() function to use differentiable operations:\nimport tensorflow as tf\n\ndef mda(y_true, y_pred):\n s = tf.equal(tf.math.sign(y_true[1:] - y_true[:-1]),\n tf.math.sign(y_pred[1:] - y_pred[:-1]))\n return tf.math.reduce_mean(tf.cast(s, tf.float32))\n\n\nThis should allow you to use the mda() function as a custom loss function for your TensorFlow neural network.\n", "The problem is that with K.equal and K.cast, you change numbers into bools. As a result, no gradient can be calculated.\nYou could replace them with a calculation; using the fact that when two numbers are equal, their difference is zero, and that since sign returns only [-1, 0, 1], the absolute difference can only be 0, 1 or 2:\ndef mda(y_true, y_pred):\n d = K.abs(K.sign(y_true[1:] - y_true[:-1]) - (K.sign(y_pred[1:] - y_pred[:-1])))\n s = (1. - d) * (d - 1.) * (d - 2.) / 2.\nreturn K.mean(s)\n\ns is equal 1 when your K.equal is true, and 0 otherwise\n", "Thanks Reda and AndrzeO for your answers my question. As AndrzejO mention, equals transform the data to boolean so no gradient there.\nI implemented this other solution as an alternative to AndrzejO solution:\ndef mda_custom_loss(y_true, y_pred):\n res = tf.math.sign(y_true[1:] - y_true[:-1]) - tf.math.sign(y_pred[1:] - y_pred[:-1])\n s = tf.math.abs(tf.math.sign(res))\n return 1 - tf.math.reduce_mean(tf.math.sign(s))\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "keras", "loss_function", "python", "tensorflow" ]
stackoverflow_0074671602_keras_loss_function_python_tensorflow.txt
Q: iOS - Device language not recognized for localization I have an app with multiple embedded packages using their own localization files. The app doesn't seem to be picking the localized strings when I change the device language/region, but if I change the language for the app from iPhone Settings -> App -> Language, the language is recognized properly and the correct strings are shown. Does anyone know of a fix around this? Or if it's a known iOS issue somehow? A: It sounds like the device language/region is not being detected correctly by your app. In order for the localization to work properly, your app needs to be able to detect the language/region of the device and then use the appropriate localized strings accordingly. To do this, you should make sure that your app is using the proper APIs to detect the device language/region. The recommended way to do this is to use the NSLocale class. You can use the NSLocale instance's objectForKey: method to get the current language/region code and then use that to select the appropriate localized strings for your app. You can also use the Apple-provided localization tools to make the process easier. They provide a way to localize your app's strings quickly and easily, and the tools will automatically detect the device language/region. Hopefully this helps. Best of luck!
iOS - Device language not recognized for localization
I have an app with multiple embedded packages using their own localization files. The app doesn't seem to be picking the localized strings when I change the device language/region, but if I change the language for the app from iPhone Settings -> App -> Language, the language is recognized properly and the correct strings are shown. Does anyone know of a fix around this? Or if it's a known iOS issue somehow?
[ "It sounds like the device language/region is not being detected correctly by your app. In order for the localization to work properly, your app needs to be able to detect the language/region of the device and then use the appropriate localized strings accordingly.\nTo do this, you should make sure that your app is using the proper APIs to detect the device language/region. The recommended way to do this is to use the NSLocale class. You can use the NSLocale instance's objectForKey: method to get the current language/region code and then use that to select the appropriate localized strings for your app.\nYou can also use the Apple-provided localization tools to make the process easier. They provide a way to localize your app's strings quickly and easily, and the tools will automatically detect the device language/region.\nHopefully this helps. Best of luck!\n" ]
[ 0 ]
[]
[]
[ "ios", "localization", "swift" ]
stackoverflow_0074630853_ios_localization_swift.txt
Q: Arduino Snake Project I am having some problems explaining this code and would be very happy if someone who knows this area could help me. It would help me a lot if someone could add detailed descriptions to some of the commands. If someone could take the time to explain this code in some detail, I would be very happy. Especially the code from line 139 to 151 I don't understand how these commands work. If you know only something about one part, i would be happy too, if you share me this informations. Thank you I also informed myself about this code and i know what many parts are doing but i dont know how this commands work. If someone could help me how they work it would help me a lot. The Code is about a Snake game for arduino with a joystick and a 8x8 LED-Matrix. The Part of the codes, which i dont understand: lc.shutdown(0,false); lc.setIntensity(0,8); lc.clearDisplay(0); //Check If The Snake hits itself for(j=0;j<snake.len;j++){ if(snake.body[j][0] == neuerKopf [0] && snake.body[j][1] == neuerKopf[1]){ //Pause the game for 1 sec then Reset it delay(1000); snake = {{1,5},{{0,5}, {1,5}}, 2, {1,0}};//Reinitialize the snake object apple = {(int)random(0,8),(int)random(0,8)};//Reinitialize an apple object return; The complete Code (neuerKopf=newHead): #include <LedControl.h> typedef struct Snake Snake; struct Snake{ int kopf[2]; int body[40][2]; int len; int dir[2]; }; typedef struct Apple Apple; struct Apple{ int rPos; int cPos; }; const int DIN =12; const int CS =11; const int CLK = 10; LedControl lc = LedControl(DIN, CLK, CS,1); const int varXPin = A3; const int varYPin = A4; const short messageSpeed = 5; byte pic[8] = {0,0,0,0,0,0,0,0}; Snake snake = {{1,5},{{0,5}, {1,5}}, 2, {1,0}}; Apple apple = {(int)random(0,8),(int)random(0,8)}; float oldTime = 0; float timer = 0; float updateRate = 3; int i,j; void setup() { do a wakeup call */ lc.shutdown(0,false); lc.setIntensity(0,8); lc.clearDisplay(0); pinMode(varXPin, INPUT); pinMode(varYPin, INPUT); } void loop() { float deltaTime = calculateDeltaTime(); timer += deltaTime; int xVal = analogRead(varXPin); int yVal = analogRead(varYPin); if(xVal<100 && snake.dir[1]==0){ snake.dir[0] = 0; snake.dir[1] = -1; }else if(xVal >920 && snake.dir[1]==0){ snake.dir[0] = 0; snake.dir[1] = 1; }else if(yVal<100 && snake.dir[0]==0){ snake.dir[0] = -1; snake.dir[1] = 0; }else if(yVal >920 && snake.dir[0]==0){ snake.dir[0] = 1; snake.dir[1] = 0; } //Update if(timer > 1000/updateRate){ timer = 0; Update(); } //Render Render(); } float calculateDeltaTime(){ float currentTime = millis(); float dt = currentTime - oldTime; oldTime = currentTime; return dt; } void reset(){ for(int j=0;j<8;j++){ pic[j] = 0; } } void Update(){ reset();// int neuerKopf[2] = {snake.kopf[0]+snake.dir[0], snake.kopf[1]+snake.dir[1]}; if(neuerKopf[0]==8){ neuerKopf[0]=0; }else if(neuerKopf[0]==-1){ neuerKopf[0] = 7; }else if(neuerKopf[1]==8){ neuerKopf[1]=0; }else if(neuerKopf[1]==-1){ neuerKopf[1]=7; } for(j=0;j<snake.len;j++){ if(snake.body[j][0] == neuerKopf [0] && snake.body[j][1] == neuerKopf[1]){ delay(1000); snake = {{1,5},{{0,5}, {1,5}}, 2, {1,0}}; apple = {(int)random(0,8),(int)random(0,8)}; return; } } if(neuerKopf[0] == apple.rPos && neuerKopf[1] ==apple.cPos){ snake.len = snake.len+1; apple.rPos = (int)random(0,8); apple.cPos = (int)random(0,8); }else{ removeFirst(); } snake.body[snake.len-1][0]= neuerKopf[0]; snake.body[snake.len-1][1]= neuerKopf[1]; snake.kopf[0] = neuerKopf[0]; snake.kopf[1] = neuerKopf[1]; for(j=0;j<snake.len;j++){ pic[snake.body[j][0]] |= 128 >> snake.body[j][1]; } pic[apple.rPos] |= 128 >> apple.cPos; } void Render(){ for(i=0;i<8;i++){ lc.setRow(0,i,pic[i]); } } void removeFirst(){ for(j=1;j<snake.len;j++){ snake.body[j-1][0] = snake.body[j][0]; snake.body[j-1][1] = snake.body[j][1]; } } const PROGMEM bool gameOverMessage[8][74] = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,1,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0,0,1,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} }; void showGameOverMessage() { for (int d = 0; d < sizeof(gameOverMessage[0]) - 7; d++) { for (int col = 0; col < 8; col++) { delay(messageSpeed); for (int row = 0; row < 8; row++) { lc.setLed(0, row, col, pgm_read_byte(&(gameOverMessage[row][col + d]))); } } } } A: The code you provided is a Snake game for Arduino that uses a joystick and an 8x8 LED matrix to display the game. The part of the code you don't understand is the lc.shutdown(0,false); lc.setIntensity(0,8); and lc.clearDisplay(0); lines. These lines are using methods from the LedControl class to initialize the LED matrix. The LedControl class is a library for controlling LED matrices or seven-segment displays with a MAX7221 or MAX7219 driver. The lc object is an instance of the LedControl class that is used to access its methods. The lc.shutdown(0,false); line is using the shutdown method of the LedControl class to turn on the display. The 0 argument specifies the index of the device on the display, and the false argument specifies that the display should be turned on. The lc.setIntensity(0,8); line is using the setIntensity method of the LedControl class to set the brightness of the display. The 0 argument specifies the index of the device on the display, and the 8 argument specifies the brightness level (on a scale from 0 to 15). The lc.clearDisplay(0); line is using the clearDisplay method of the LedControl class to clear the display. The 0 argument specifies the index of the device on the display. These three lines of code are initializing the LED matrix and setting it up for use in the Snake game.
Arduino Snake Project
I am having some problems explaining this code and would be very happy if someone who knows this area could help me. It would help me a lot if someone could add detailed descriptions to some of the commands. If someone could take the time to explain this code in some detail, I would be very happy. Especially the code from line 139 to 151 I don't understand how these commands work. If you know only something about one part, i would be happy too, if you share me this informations. Thank you I also informed myself about this code and i know what many parts are doing but i dont know how this commands work. If someone could help me how they work it would help me a lot. The Code is about a Snake game for arduino with a joystick and a 8x8 LED-Matrix. The Part of the codes, which i dont understand: lc.shutdown(0,false); lc.setIntensity(0,8); lc.clearDisplay(0); //Check If The Snake hits itself for(j=0;j<snake.len;j++){ if(snake.body[j][0] == neuerKopf [0] && snake.body[j][1] == neuerKopf[1]){ //Pause the game for 1 sec then Reset it delay(1000); snake = {{1,5},{{0,5}, {1,5}}, 2, {1,0}};//Reinitialize the snake object apple = {(int)random(0,8),(int)random(0,8)};//Reinitialize an apple object return; The complete Code (neuerKopf=newHead): #include <LedControl.h> typedef struct Snake Snake; struct Snake{ int kopf[2]; int body[40][2]; int len; int dir[2]; }; typedef struct Apple Apple; struct Apple{ int rPos; int cPos; }; const int DIN =12; const int CS =11; const int CLK = 10; LedControl lc = LedControl(DIN, CLK, CS,1); const int varXPin = A3; const int varYPin = A4; const short messageSpeed = 5; byte pic[8] = {0,0,0,0,0,0,0,0}; Snake snake = {{1,5},{{0,5}, {1,5}}, 2, {1,0}}; Apple apple = {(int)random(0,8),(int)random(0,8)}; float oldTime = 0; float timer = 0; float updateRate = 3; int i,j; void setup() { do a wakeup call */ lc.shutdown(0,false); lc.setIntensity(0,8); lc.clearDisplay(0); pinMode(varXPin, INPUT); pinMode(varYPin, INPUT); } void loop() { float deltaTime = calculateDeltaTime(); timer += deltaTime; int xVal = analogRead(varXPin); int yVal = analogRead(varYPin); if(xVal<100 && snake.dir[1]==0){ snake.dir[0] = 0; snake.dir[1] = -1; }else if(xVal >920 && snake.dir[1]==0){ snake.dir[0] = 0; snake.dir[1] = 1; }else if(yVal<100 && snake.dir[0]==0){ snake.dir[0] = -1; snake.dir[1] = 0; }else if(yVal >920 && snake.dir[0]==0){ snake.dir[0] = 1; snake.dir[1] = 0; } //Update if(timer > 1000/updateRate){ timer = 0; Update(); } //Render Render(); } float calculateDeltaTime(){ float currentTime = millis(); float dt = currentTime - oldTime; oldTime = currentTime; return dt; } void reset(){ for(int j=0;j<8;j++){ pic[j] = 0; } } void Update(){ reset();// int neuerKopf[2] = {snake.kopf[0]+snake.dir[0], snake.kopf[1]+snake.dir[1]}; if(neuerKopf[0]==8){ neuerKopf[0]=0; }else if(neuerKopf[0]==-1){ neuerKopf[0] = 7; }else if(neuerKopf[1]==8){ neuerKopf[1]=0; }else if(neuerKopf[1]==-1){ neuerKopf[1]=7; } for(j=0;j<snake.len;j++){ if(snake.body[j][0] == neuerKopf [0] && snake.body[j][1] == neuerKopf[1]){ delay(1000); snake = {{1,5},{{0,5}, {1,5}}, 2, {1,0}}; apple = {(int)random(0,8),(int)random(0,8)}; return; } } if(neuerKopf[0] == apple.rPos && neuerKopf[1] ==apple.cPos){ snake.len = snake.len+1; apple.rPos = (int)random(0,8); apple.cPos = (int)random(0,8); }else{ removeFirst(); } snake.body[snake.len-1][0]= neuerKopf[0]; snake.body[snake.len-1][1]= neuerKopf[1]; snake.kopf[0] = neuerKopf[0]; snake.kopf[1] = neuerKopf[1]; for(j=0;j<snake.len;j++){ pic[snake.body[j][0]] |= 128 >> snake.body[j][1]; } pic[apple.rPos] |= 128 >> apple.cPos; } void Render(){ for(i=0;i<8;i++){ lc.setRow(0,i,pic[i]); } } void removeFirst(){ for(j=1;j<snake.len;j++){ snake.body[j-1][0] = snake.body[j][0]; snake.body[j-1][1] = snake.body[j][1]; } } const PROGMEM bool gameOverMessage[8][74] = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,1,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0,0,1,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} }; void showGameOverMessage() { for (int d = 0; d < sizeof(gameOverMessage[0]) - 7; d++) { for (int col = 0; col < 8; col++) { delay(messageSpeed); for (int row = 0; row < 8; row++) { lc.setLed(0, row, col, pgm_read_byte(&(gameOverMessage[row][col + d]))); } } } }
[ "The code you provided is a Snake game for Arduino that uses a joystick and an 8x8 LED matrix to display the game. The part of the code you don't understand is the lc.shutdown(0,false); lc.setIntensity(0,8); and lc.clearDisplay(0); lines.\nThese lines are using methods from the LedControl class to initialize the LED matrix. The LedControl class is a library for controlling LED matrices or seven-segment displays with a MAX7221 or MAX7219 driver. The lc object is an instance of the LedControl class that is used to access its methods.\nThe lc.shutdown(0,false); line is using the shutdown method of the LedControl class to turn on the display. The 0 argument specifies the index of the device on the display, and the false argument specifies that the display should be turned on.\nThe lc.setIntensity(0,8); line is using the setIntensity method of the LedControl class to set the brightness of the display. The 0 argument specifies the index of the device on the display, and the 8 argument specifies the brightness level (on a scale from 0 to 15).\nThe lc.clearDisplay(0); line is using the clearDisplay method of the LedControl class to clear the display. The 0 argument specifies the index of the device on the display.\nThese three lines of code are initializing the LED matrix and setting it up for use in the Snake game.\n" ]
[ 0 ]
[]
[]
[ "arduino", "arduino_uno", "java" ]
stackoverflow_0074671919_arduino_arduino_uno_java.txt
Q: how do i get a document based on whats in its subcollection firestore? I have a firestore database that looks like this : posts(collection)/post (document)/upvote (collection)/userID (document). now for example my user id is 1234 so it would look like this. posts/dogs are cool/upvote/1234(userid) id also like to add that the end document name is the userid and inside of it is just a property that says exists: true this is just so its not auto-deleted. the goal for me is to go in and check if my user has upvoted on this post and if they have id like to return the post Document and not the upvote document. it's pretty much functionality where id likes to show the posts that I've upvoted. im using next js and firestore which im a little new to ive tried onsnapshot with a query but it seems like it might be something big that im missing. A: Firestore queries can only filter on data that is in the documents that they return. So if you're looking to return documents from the posts collection, you can only filter on data in those documents - not from the documents in the upvote collection under it. The solution is usually to make sure you have some data about the votes in the posts documents. For example, if you store an upvoteCount in each document in posts, you can use that for the query - and implement more use-cases, such as get your most-upvoted posts. You'll have to update the document in posts whenever a relevant document is written (or deleted) under its upvotes collection.
how do i get a document based on whats in its subcollection firestore?
I have a firestore database that looks like this : posts(collection)/post (document)/upvote (collection)/userID (document). now for example my user id is 1234 so it would look like this. posts/dogs are cool/upvote/1234(userid) id also like to add that the end document name is the userid and inside of it is just a property that says exists: true this is just so its not auto-deleted. the goal for me is to go in and check if my user has upvoted on this post and if they have id like to return the post Document and not the upvote document. it's pretty much functionality where id likes to show the posts that I've upvoted. im using next js and firestore which im a little new to ive tried onsnapshot with a query but it seems like it might be something big that im missing.
[ "Firestore queries can only filter on data that is in the documents that they return. So if you're looking to return documents from the posts collection, you can only filter on data in those documents - not from the documents in the upvote collection under it.\nThe solution is usually to make sure you have some data about the votes in the posts documents. For example, if you store an upvoteCount in each document in posts, you can use that for the query - and implement more use-cases, such as get your most-upvoted posts. You'll have to update the document in posts whenever a relevant document is written (or deleted) under its upvotes collection.\n" ]
[ 1 ]
[]
[]
[ "firebase", "google_cloud_firestore", "javascript", "reactjs" ]
stackoverflow_0074671663_firebase_google_cloud_firestore_javascript_reactjs.txt
Q: Create React App - download CSV file in public folder If I have: -- public -- csv exampleCSV.csv i.e. /public/csv/exampleCSV.csv and then: fetch('csv/exampleCSV.csv') .then(response => { console.log(response); response.blob().then(blob => { let url = window.URL.createObjectURL(blob); let a = document.createElement('a'); a.href = url; a.download = 'exampleCSV.csv'; a.click(); }); }); Why do I not get the CSV file on click but instead the html page of the react app? A: Probably would be better to close this... But the way I resolved was generating the csv file in code. Then downloaded on click... A: If excel file is already in public folder then this usage would not be solution for your problem? <a href="/csv/exampleCSV.csv" download> Download </a>
Create React App - download CSV file in public folder
If I have: -- public -- csv exampleCSV.csv i.e. /public/csv/exampleCSV.csv and then: fetch('csv/exampleCSV.csv') .then(response => { console.log(response); response.blob().then(blob => { let url = window.URL.createObjectURL(blob); let a = document.createElement('a'); a.href = url; a.download = 'exampleCSV.csv'; a.click(); }); }); Why do I not get the CSV file on click but instead the html page of the react app?
[ "Probably would be better to close this...\nBut the way I resolved was generating the csv file in code. Then downloaded on click...\n", "If excel file is already in public folder then this usage would not be solution for your problem?\n<a href=\"/csv/exampleCSV.csv\" download>\n Download\n</a>\n\n" ]
[ 0, 0 ]
[]
[]
[ "create_react_app", "javascript", "reactjs" ]
stackoverflow_0074555592_create_react_app_javascript_reactjs.txt
Q: Cannot get data from request.get_json(force=True) import requests import numpy as np import json from flask import Flask, request, jsonify url = 'http://localhost:5000/api' dat = np.genfromtxt('/home/panos/Manti_Milk/BigData/50_0_50_3.5_3-3.dat') d1 = dat[:,0] data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3": d1[3], "w4": d1[4], "w5": d1[5], "w6": d1[6], "w7": d1[7], "w8": d1[8], "w9": d1[9], "w10": d1[10], "w11": d1[11], "w12": d1[12], "w13": d1[13], "w14": d1[14], "w15": d1[15]} jsondata = json.dumps(data, indent=4) r = request.post(url, json = jsondata) @app.route('/api',methods=['POST','GET']) def predict(): jsondata = request.get_json(force=True) dummy = json.loads(jsondata) arr = np.fromiter(dummy.values(), dtype=float).reshape(16,1) return {"data": arr} if __name__ == '__main__': app.run(port=5000, debug=True) It returns Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0) When setting force=False, returns "Null" Any Help? I have read several questoins/answers where it should work. But this is not the case! A: You do not need to decode json data after request.get_json(), it is already the Python dict. So the line dummy = json.loads(jsondata) is unnecessary. @app.route('/api',methods=['POST','GET']) def predict(): jsondata = request.get_json(force=True) arr = np.fromiter(jsondata.values(), dtype=float) EDIT: First file - server.py: import numpy as np from flask import Flask, request app = Flask(__name__) @app.route('/api', methods=['POST', 'GET']) def predict(): jsondata = request.get_json(force=True) arr = np.fromiter(jsondata.values(), dtype=float).reshape(16, 1) print(arr) # do whatever you want here return "1" app.run(debug=True) Second file - client.py: import requests import numpy as np dat = np.genfromtxt('data.dat') d1 = dat[:, 0] data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3": d1[3], "w4": d1[4], "w5": d1[5], "w6": d1[6], "w7": d1[7], "w8": d1[8], "w9": d1[9], "w10": d1[10], "w11": d1[11], "w12": d1[12], "w13": d1[13], "w14": d1[14], "w15": d1[15]} requests.post("http://127.0.0.1:5000/api", json=data) Then execute them separately (from different console tabs): At first, start the server in [1] tab: $ python server.py * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with stat * Debugger is active! And after that run request from client in another [2] tab: $ python client.py Then you will see desired output in server tab [1]: [[2297.] [1376.] [1967.] [2414.] [2012.] [2348.] [2293.] [1800.] [2011.] [2340.] [1949.] [2015.] [2338.] [1866.] [1461.] [2158.]]
Cannot get data from request.get_json(force=True)
import requests import numpy as np import json from flask import Flask, request, jsonify url = 'http://localhost:5000/api' dat = np.genfromtxt('/home/panos/Manti_Milk/BigData/50_0_50_3.5_3-3.dat') d1 = dat[:,0] data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3": d1[3], "w4": d1[4], "w5": d1[5], "w6": d1[6], "w7": d1[7], "w8": d1[8], "w9": d1[9], "w10": d1[10], "w11": d1[11], "w12": d1[12], "w13": d1[13], "w14": d1[14], "w15": d1[15]} jsondata = json.dumps(data, indent=4) r = request.post(url, json = jsondata) @app.route('/api',methods=['POST','GET']) def predict(): jsondata = request.get_json(force=True) dummy = json.loads(jsondata) arr = np.fromiter(dummy.values(), dtype=float).reshape(16,1) return {"data": arr} if __name__ == '__main__': app.run(port=5000, debug=True) It returns Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0) When setting force=False, returns "Null" Any Help? I have read several questoins/answers where it should work. But this is not the case!
[ "You do not need to decode json data after request.get_json(), it is already the Python dict. So the line dummy = json.loads(jsondata) is unnecessary.\[email protected]('/api',methods=['POST','GET'])\ndef predict():\n jsondata = request.get_json(force=True)\n arr = np.fromiter(jsondata.values(), dtype=float)\n\nEDIT:\nFirst file - server.py:\nimport numpy as np\nfrom flask import Flask, request\n\n\napp = Flask(__name__)\n\[email protected]('/api', methods=['POST', 'GET'])\ndef predict():\n jsondata = request.get_json(force=True)\n arr = np.fromiter(jsondata.values(), dtype=float).reshape(16, 1)\n print(arr) # do whatever you want here\n return \"1\"\n\n\napp.run(debug=True)\n\nSecond file - client.py:\nimport requests\nimport numpy as np\n\ndat = np.genfromtxt('data.dat')\nd1 = dat[:, 0]\n\ndata = {\"w0\": d1[0], \"w1\": d1[1], \"w2\": d1[2], \"w3\": d1[3], \"w4\": d1[4],\n \"w5\": d1[5], \"w6\": d1[6], \"w7\": d1[7], \"w8\": d1[8], \"w9\": d1[9], \"w10\": d1[10],\n \"w11\": d1[11], \"w12\": d1[12], \"w13\": d1[13], \"w14\": d1[14], \"w15\": d1[15]}\n\nrequests.post(\"http://127.0.0.1:5000/api\", json=data)\n\nThen execute them separately (from different console tabs):\nAt first, start the server in [1] tab:\n$ python server.py\n\n * Running on http://127.0.0.1:5000\nPress CTRL+C to quit\n * Restarting with stat\n * Debugger is active!\n\nAnd after that run request from client in another [2] tab:\n$ python client.py\n\nThen you will see desired output in server tab [1]:\n[[2297.]\n [1376.]\n [1967.]\n [2414.]\n [2012.]\n [2348.]\n [2293.]\n [1800.]\n [2011.]\n [2340.]\n [1949.]\n [2015.]\n [2338.]\n [1866.]\n [1461.]\n [2158.]]\n\n" ]
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074670424_flask_python.txt
Q: Request.body is empty object even after sending a fetch post request with body Fetch request through an HTML page. I want to post formData object to the server which is hosted locally. let formData={ name:document.getElementById('name').value, question:document.getElementById('question').value } let response=await fetch('http://localhost:5000/',{ method:'POST', mode:'no-cors', headers:{'Content-Type':'application/json'}, body:JSON.stringify(formData) }).then((res)=>console.log(res)).catch((err)=>console.log(err)) }) The req.body gives an empty object, I also tried using body-parser but it didn't work either. //--------app.js------------- const express = require('express'); const app=express(); const port=process.env.PORT || 5000; app.use(express.json()); app.get('/',(req,res)=>{ res.send('im alive') }) app.post('/',(req,res)=>{ console.log(req.body); res.json({status:"okay"}); }) app.listen(5000,()=> console.log('Listening at '+port)); A: The mode:'no-cors' is messing things up. This mode leads to only selected content type headers to be sent. Allowed list. allowed content types headers: [ ['Content-Type', 'application/x-www-form-urlencoded'], ['Content-Type', 'multipart/form-data'], ['Content-Type', 'text/plain'], ] So you have 2 options left. 1.Remove 'no-cors' mode. 2.Use content type:application/x-www-form-urlencoded. You would need additional code to convert the json, but it can get complicated.Json to url encoded A: Make sure you wait for the data before printing. fetch('http://127.0.0.1:3000/') .then(async data => { const res = await data.json() // data is a promise here console.log(res) })
Request.body is empty object even after sending a fetch post request with body
Fetch request through an HTML page. I want to post formData object to the server which is hosted locally. let formData={ name:document.getElementById('name').value, question:document.getElementById('question').value } let response=await fetch('http://localhost:5000/',{ method:'POST', mode:'no-cors', headers:{'Content-Type':'application/json'}, body:JSON.stringify(formData) }).then((res)=>console.log(res)).catch((err)=>console.log(err)) }) The req.body gives an empty object, I also tried using body-parser but it didn't work either. //--------app.js------------- const express = require('express'); const app=express(); const port=process.env.PORT || 5000; app.use(express.json()); app.get('/',(req,res)=>{ res.send('im alive') }) app.post('/',(req,res)=>{ console.log(req.body); res.json({status:"okay"}); }) app.listen(5000,()=> console.log('Listening at '+port));
[ "The mode:'no-cors' is messing things up. This mode leads to only selected content type headers to be sent.\nAllowed list. allowed content types\nheaders: [\n['Content-Type', 'application/x-www-form-urlencoded'],\n['Content-Type', 'multipart/form-data'],\n['Content-Type', 'text/plain'],\n]\nSo you have 2 options left.\n1.Remove 'no-cors' mode.\n2.Use content type:application/x-www-form-urlencoded. You would need additional code to convert the json, but it can get complicated.Json to url encoded\n", "Make sure you wait for the data before printing.\nfetch('http://127.0.0.1:3000/')\n .then(async data => {\n const res = await data.json() // data is a promise here\n console.log(res)\n})\n\n" ]
[ 1, 0 ]
[]
[]
[ "fetch_api", "node.js" ]
stackoverflow_0071612691_fetch_api_node.js.txt
Q: How to set state array by merging it with another array without having duplicates? How to properly add objects from another array to my state array without having the same element twice? The state array: const [arr, setArr] = useState([1,2,3]) The array I want to merge the state array with: const someArr = [2,3,4,5] The wanted outcome is arr = [1,2,3,4,5] Doing something like: const arr3 = [...new Set([...arr, ...someArr])] setArr(arr3) works, but I'm sure that's the wrong solution for this. Thanks! A: To properly add the objects from someArr to the state array without having the same element twice, you can use the Set data structure to store the elements of the state array, and then use the spread operator and the concat method to add the elements of someArr to the Set without duplicates. Finally, you can convert the Set back to an array and set it as the new state. Here's an example of how you can do this: const [arr, setArr] = useState([1,2,3]); const someArr = [2,3,4,5]; // Create a Set from the state array const set = new Set(arr); // Add the elements of someArr to the Set without duplicates set.add(...someArr); // Convert the Set back to an array and set it as the new state setArr([...set]); // arr is now [1,2,3,4,5] Alternatively, you can use the filter method to remove duplicates from the someArr array before adding it to the state array. Here's an example of how you can do this: const [arr, setArr] = useState([1,2,3]); const someArr = [2,3,4,5]; // Remove duplicates from someArr using the filter method const filteredArr = someArr.filter(x => !arr.includes(x)); // Add the elements of filteredArr to the state array setArr(arr.concat(filteredArr)); // arr is now [1,2,3,4,5] In both examples, the state array arr will be updated to contain the elements from someArr without duplicates. The Set data structure is more efficient for checking for duplicates, but using the filter method is more straightforward and may be easier to understand. You can choose the approach that works best for your use case.
How to set state array by merging it with another array without having duplicates?
How to properly add objects from another array to my state array without having the same element twice? The state array: const [arr, setArr] = useState([1,2,3]) The array I want to merge the state array with: const someArr = [2,3,4,5] The wanted outcome is arr = [1,2,3,4,5] Doing something like: const arr3 = [...new Set([...arr, ...someArr])] setArr(arr3) works, but I'm sure that's the wrong solution for this. Thanks!
[ "To properly add the objects from someArr to the state array without having the same element twice, you can use the Set data structure to store the elements of the state array, and then use the spread operator and the concat method to add the elements of someArr to the Set without duplicates. Finally, you can convert the Set back to an array and set it as the new state.\nHere's an example of how you can do this:\nconst [arr, setArr] = useState([1,2,3]);\nconst someArr = [2,3,4,5];\n\n// Create a Set from the state array\nconst set = new Set(arr);\n\n// Add the elements of someArr to the Set without duplicates\nset.add(...someArr);\n\n// Convert the Set back to an array and set it as the new state\nsetArr([...set]);\n\n// arr is now [1,2,3,4,5]\n\nAlternatively, you can use the filter method to remove duplicates from the someArr array before adding it to the state array.\nHere's an example of how you can do this:\nconst [arr, setArr] = useState([1,2,3]);\nconst someArr = [2,3,4,5];\n\n// Remove duplicates from someArr using the filter method\nconst filteredArr = someArr.filter(x => !arr.includes(x));\n\n// Add the elements of filteredArr to the state array\nsetArr(arr.concat(filteredArr));\n\n// arr is now [1,2,3,4,5]\n\nIn both examples, the state array arr will be updated to contain the elements from someArr without duplicates. The Set data structure is more efficient for checking for duplicates, but using the filter method is more straightforward and may be easier to understand. You can choose the approach that works best for your use case.\n" ]
[ 1 ]
[]
[]
[ "arrays", "reactjs", "state" ]
stackoverflow_0074672049_arrays_reactjs_state.txt
Q: Custom Route in an App for using in Cloud Shops Is it possible to add custom routes in an app which are also valid in a cloud shop? I couldnt find anything about it in the docs. A: You can implement custom endpoints using app scripts.
Custom Route in an App for using in Cloud Shops
Is it possible to add custom routes in an app which are also valid in a cloud shop? I couldnt find anything about it in the docs.
[ "You can implement custom endpoints using app scripts.\n" ]
[ 1 ]
[]
[]
[ "shopware", "shopware6", "shopware6_api", "shopware6_app" ]
stackoverflow_0074670389_shopware_shopware6_shopware6_api_shopware6_app.txt
Q: How can I get my python code to be more efficient? I've been struggling for the past couple days with getting my python code to be more efficient, while also getting the run time to be with in the given specifications of the problem below ( 3 seconds, for any given input). Was told that linear time may help, but was hoping I can get some help on how I'd approach it with my existing code here, would really appreciate the help. This is the given problem: *Dan has a list of problems suitable for Assignment 4. The difficulties of these problems are stored in a list of integers a. The i-th problem’s difficulty is represented by a[i] (the higher the integer, the more difficult the problem). Dan is too busy eating saltines to worry about Assignment 4 decisions, so he asks Michael the TA to select at least two problems from the list for the assignment. Since there are many possible subsets of the problems to consider and Michael has a life, he decides to consider only sublists (definition follows) of the list of problems. To make grading the assignment easier, Michael wants to pick problems that don’t vary too much in difficulty. What is the smallest difference between the difficulties of the most difficult selected problem and the least difficult selected problem he can achieve by selecting a sublist of length at least 2 of the original list of problems? Definition: A sublist of a list a is any list you can obtain by removing some (possibly 0) elements from the start of a and then removing some (possibly 0) elements from the end of it. (It’s like the definition of segment from lecture.) .* Input The input consists of a single line containing the integers in the list a, separated by single spaces. Output Print a single integer indicating the smallest difference in difficulties Michael can achieve. Constraints 2 <= len(a) <= 500000 1 <= a[i] <= 10**9 Time Limit: Your program must finish running on any valid input within 3 seconds Sample Input 1 10 6 9 1 Sample Output 1 3 My code: import time # import time module arr = list(map(int, input().split(" "))) st = time.time() diff = 10**9 for i in range(len(arr)-1): max_ele = min_ele = arr[i] for j in range(i+1, len(arr)): max_ele = max(max_ele, arr[j]) min_ele = min(min_ele, arr[j]) if max_ele - min_ele <= diff: diff = max_ele - min_ele print(diff) # end = time.time() - st #print(end) ``` ` A: It looks like your current approach is to iterate through all possible pairs of elements in the list and calculate the difference between the maximum and minimum element in each pair. This approach will take quadratic time, which might not efficient enough to solve this problem within the given time constraints. To make your code more efficient, you can sort the list and then iterate through the sorted list to find the smallest difference between the maximum and minimum element in any sublist of length at least 2. Since the list is sorted, you can simply keep track of the minimum and maximum element you have seen so far, and then update the minimum and maximum as you iterate through the list. This approach will take linear time, which should be fast enough to solve this problem within the time constraints. Here is an example of how you can implement this approach: import time # import time module arr = list(map(int, input().split(" "))) # sort the list in ascending order arr.sort() # initialize the minimum and maximum elements we have seen so far min_ele = arr[0] max_ele = arr[1] # initialize the smallest difference between the maximum and minimum element # in any sublist of length at least 2 diff = max_ele - min_ele # iterate through the list, starting from the second element for i in range(1, len(arr)): # update the minimum and maximum elements min_ele = min(min_ele, arr[i]) max_ele = max(max_ele, arr[i]) # update the smallest difference diff = min(diff, max_ele - min_ele) # print the smallest difference print(diff) I hope this helps! Let me know if you have any other questions. A: You can think of the sublists or segments as sliding windows over the array. Because the minimum length is two, the question is equivalent to asking for the minimum difference in a sublist of exactly two, ie consecutive elements. In python you can do this with a list, or better generator, comprehension diff=min((abs(a-b) for a,b in zip(arr[:-1],arr[1:]))) As a loop diff=10**9 for a,b in zip(arr[:-1],arr[1:]): diff=min(diff,abs(a-b)) return diff
How can I get my python code to be more efficient?
I've been struggling for the past couple days with getting my python code to be more efficient, while also getting the run time to be with in the given specifications of the problem below ( 3 seconds, for any given input). Was told that linear time may help, but was hoping I can get some help on how I'd approach it with my existing code here, would really appreciate the help. This is the given problem: *Dan has a list of problems suitable for Assignment 4. The difficulties of these problems are stored in a list of integers a. The i-th problem’s difficulty is represented by a[i] (the higher the integer, the more difficult the problem). Dan is too busy eating saltines to worry about Assignment 4 decisions, so he asks Michael the TA to select at least two problems from the list for the assignment. Since there are many possible subsets of the problems to consider and Michael has a life, he decides to consider only sublists (definition follows) of the list of problems. To make grading the assignment easier, Michael wants to pick problems that don’t vary too much in difficulty. What is the smallest difference between the difficulties of the most difficult selected problem and the least difficult selected problem he can achieve by selecting a sublist of length at least 2 of the original list of problems? Definition: A sublist of a list a is any list you can obtain by removing some (possibly 0) elements from the start of a and then removing some (possibly 0) elements from the end of it. (It’s like the definition of segment from lecture.) .* Input The input consists of a single line containing the integers in the list a, separated by single spaces. Output Print a single integer indicating the smallest difference in difficulties Michael can achieve. Constraints 2 <= len(a) <= 500000 1 <= a[i] <= 10**9 Time Limit: Your program must finish running on any valid input within 3 seconds Sample Input 1 10 6 9 1 Sample Output 1 3 My code: import time # import time module arr = list(map(int, input().split(" "))) st = time.time() diff = 10**9 for i in range(len(arr)-1): max_ele = min_ele = arr[i] for j in range(i+1, len(arr)): max_ele = max(max_ele, arr[j]) min_ele = min(min_ele, arr[j]) if max_ele - min_ele <= diff: diff = max_ele - min_ele print(diff) # end = time.time() - st #print(end) ``` `
[ "It looks like your current approach is to iterate through all possible pairs of elements in the list and calculate the difference between the maximum and minimum element in each pair. This approach will take quadratic time, which might not efficient enough to solve this problem within the given time constraints.\nTo make your code more efficient, you can sort the list and then iterate through the sorted list to find the smallest difference between the maximum and minimum element in any sublist of length at least 2. Since the list is sorted, you can simply keep track of the minimum and maximum element you have seen so far, and then update the minimum and maximum as you iterate through the list. This approach will take linear time, which should be fast enough to solve this problem within the time constraints.\nHere is an example of how you can implement this approach:\nimport time # import time module\narr = list(map(int, input().split(\" \")))\n\n# sort the list in ascending order\narr.sort()\n\n# initialize the minimum and maximum elements we have seen so far\nmin_ele = arr[0]\nmax_ele = arr[1]\n\n# initialize the smallest difference between the maximum and minimum element\n# in any sublist of length at least 2\ndiff = max_ele - min_ele\n\n# iterate through the list, starting from the second element\nfor i in range(1, len(arr)):\n # update the minimum and maximum elements\n min_ele = min(min_ele, arr[i])\n max_ele = max(max_ele, arr[i])\n\n # update the smallest difference\n diff = min(diff, max_ele - min_ele)\n\n# print the smallest difference\nprint(diff)\n\nI hope this helps! Let me know if you have any other questions.\n", "You can think of the sublists or segments as sliding windows over the array. Because the minimum length is two, the question is equivalent to asking for the minimum difference in a sublist of exactly two, ie consecutive elements. In python you can do this with a list, or better generator, comprehension\ndiff=min((abs(a-b) for a,b in zip(arr[:-1],arr[1:])))\n\nAs a loop\ndiff=10**9\nfor a,b in zip(arr[:-1],arr[1:]):\n diff=min(diff,abs(a-b))\nreturn diff\n\n" ]
[ 1, 0 ]
[]
[]
[ "processing_efficiency", "python" ]
stackoverflow_0074671865_processing_efficiency_python.txt
Q: Send email for sign request through API I'm trying to send an email with sign request with API XMLM/RPC in Python client For this, I implement 5 calls to the API: Upload file with Method sign.template and method upload_template, send the PDF file and got the Document ID. Update contract sign, update pdf file with the field or fields to fill with user data (name, company sign..). Create the email request with message data (receiver, pdf file, text message). Some method required to check the email before send: Model sign.send.request method: read, and Model sign.send.request.signer method read Send email with model sign.send.request and method send_request with args the email template created before, like this: request_sign = api.execute_kw(database, uid, api_key, "sign.send.request","send_request", [template_email_id]) template created before, like this: All steps executes well, but the last one gives me this: xmlrpc.client.Fault: ... line 534, in dump_nil\n raise TypeError("cannot marshal None unless allow_none is enabled")\nTypeError: cannot marshal None unless allow_none is enabled\n'> I declare the connection with allow_none = True: api = client.ServerProxy("%s/xmlrpc/2/object" % self.url, allow_none=True) I don't know what Am I doing wrong with the method call. A: It seems like the error is occurring because you are trying to marshal None as a parameter to the send_request method. Marshaling refers to the process of converting an object into a format that can be transmitted over a network. In this case, it appears that one or more of the parameters you are passing to the send_request method is None and the XML-RPC library you are using is not able to handle that. To fix this error, you will need to make sure that all the parameters you pass to the send_request method are not None. You can do this by checking the values of the parameters before calling the method and replacing any None values with an appropriate default value. For example, if one of the parameters is supposed to be a string, you could replace any None values with an empty string like this: # Replace any None values with an empty string param1 = "" if param1 is None else param1 param2 = "" if param2 is None else param2 # Call the send_request method with the updated parameters request_sign = api.execute_kw(database, uid, api_key, "sign.send.request","send_request", [param1, param2]) You will need to repeat this process for all the parameters you are passing to the send_request method. Once you have done that, the error should be resolved and the method should be able to execute successfully. In general, it's important to make sure that you are passing the correct types of parameters to API methods and that you are handling any potential None values properly. This can help prevent errors like the one you are experiencing and ensure that your code is more robust and reliable.
Send email for sign request through API
I'm trying to send an email with sign request with API XMLM/RPC in Python client For this, I implement 5 calls to the API: Upload file with Method sign.template and method upload_template, send the PDF file and got the Document ID. Update contract sign, update pdf file with the field or fields to fill with user data (name, company sign..). Create the email request with message data (receiver, pdf file, text message). Some method required to check the email before send: Model sign.send.request method: read, and Model sign.send.request.signer method read Send email with model sign.send.request and method send_request with args the email template created before, like this: request_sign = api.execute_kw(database, uid, api_key, "sign.send.request","send_request", [template_email_id]) template created before, like this: All steps executes well, but the last one gives me this: xmlrpc.client.Fault: ... line 534, in dump_nil\n raise TypeError("cannot marshal None unless allow_none is enabled")\nTypeError: cannot marshal None unless allow_none is enabled\n'> I declare the connection with allow_none = True: api = client.ServerProxy("%s/xmlrpc/2/object" % self.url, allow_none=True) I don't know what Am I doing wrong with the method call.
[ "It seems like the error is occurring because you are trying to marshal None as a parameter to the send_request method. Marshaling refers to the process of converting an object into a format that can be transmitted over a network. In this case, it appears that one or more of the parameters you are passing to the send_request method is None and the XML-RPC library you are using is not able to handle that.\nTo fix this error, you will need to make sure that all the parameters you pass to the send_request method are not None. You can do this by checking the values of the parameters before calling the method and replacing any None values with an appropriate default value.\nFor example, if one of the parameters is supposed to be a string, you could replace any None values with an empty string like this:\n# Replace any None values with an empty string\nparam1 = \"\" if param1 is None else param1\nparam2 = \"\" if param2 is None else param2\n\n# Call the send_request method with the updated parameters\nrequest_sign = api.execute_kw(database, uid, api_key, \"sign.send.request\",\"send_request\", [param1, param2])\n\nYou will need to repeat this process for all the parameters you are passing to the send_request method. Once you have done that, the error should be resolved and the method should be able to execute successfully.\nIn general, it's important to make sure that you are passing the correct types of parameters to API methods and that you are handling any potential None values properly. This can help prevent errors like the one you are experiencing and ensure that your code is more robust and reliable.\n" ]
[ 0 ]
[]
[]
[ "api", "odoo", "typeerror", "xml_rpc" ]
stackoverflow_0074650550_api_odoo_typeerror_xml_rpc.txt
Q: How to maximize and minimize a div (no jquery only javascript) hello I need to maximaze or minimize a div in my html page using only javascript no jquery i wanna be able to do like this http://jsfiddle.net/miqdad/Qy6Sj/1/ $("#button").click(function(){ if($(this).html() == "-"){ $(this).html("+"); } else{ $(this).html("-"); } $("#box").slideToggle(); }); this is exactly how i want it to be but no jquery but with no jquery only javascript, can someone please help me, I googled this everywhere and couldnt find the answer A: Here's an example of how you can achieve the same effect using only vanilla JavaScript: // get the button and box elements var button = document.getElementById("button"); var box = document.getElementById("box"); // add a click event listener to the button button.addEventListener("click", function() { // toggle the "open" class on the box box.classList.toggle("open"); // update the button text if (button.innerHTML === "-") { button.innerHTML = "+"; } else { button.innerHTML = "-"; } }); This code listens for a click event on the button, and then toggles the open class on the box element. The open class could be defined in your CSS as follows: .open { height: auto !important; /* or any other styles you want to apply to the expanded box */ } This way, you can use CSS transitions to smoothly animate the expansion and contraction of the box. You can also use the button.innerHTML property to update the button text when it is clicked. An inline example would look like this: <!DOCTYPE html> <html> <head> <style> #box { height: 0; overflow: hidden; transition: height 0.5s; } .open { height: auto !important; } </style> </head> <body> <button id="button">-</button> <div id="box"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in facilisis magna. Pellentesque hendrerit dolor in ipsum sagittis bibendum. </div> <script> // get the button and box elements var button = document.getElementById("button"); var box = document.getElementById("box"); // add a click event listener to the button button.addEventListener("click", function() { // toggle the "open" class on the box box.classList.toggle("open"); // update the button text if (button.innerHTML === "-") { button.innerHTML = "+"; } else { button.innerHTML = "-"; } }); </script> </body> </html> A: a simple google search came up with: https://www.itcodar.com/javascript/expand-div-on-click-with-smooth-animation.html#:~:text=How%20to%20display%20a%20div%20with%20a%20smooth,transition%20must%20include%20the%20change%20of%20height.%20Thus%3A function seeMore() { const text = document.getElementById('website-info-idea') const text2 = document.getElementById('website-info-technical') text.classList.toggle("show") text2.classList.toggle("show") } .col { opacity: 0; height: 0; overflow: hidden; transition: all 1s ease-in-out; } .col.show { opacity: 1; height: 23px; transition: all 1s ease-in-out; } #a1 { display:inline-block; border: solid 2px black; } <div id='a1'> <a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a> <div class="col" id="website-info-idea">Idea</div> <div class="col" id="website-info-technical">Technical</div> </div>
How to maximize and minimize a div (no jquery only javascript)
hello I need to maximaze or minimize a div in my html page using only javascript no jquery i wanna be able to do like this http://jsfiddle.net/miqdad/Qy6Sj/1/ $("#button").click(function(){ if($(this).html() == "-"){ $(this).html("+"); } else{ $(this).html("-"); } $("#box").slideToggle(); }); this is exactly how i want it to be but no jquery but with no jquery only javascript, can someone please help me, I googled this everywhere and couldnt find the answer
[ "Here's an example of how you can achieve the same effect using only vanilla JavaScript:\n// get the button and box elements\nvar button = document.getElementById(\"button\");\nvar box = document.getElementById(\"box\");\n\n// add a click event listener to the button\nbutton.addEventListener(\"click\", function() {\n // toggle the \"open\" class on the box\n box.classList.toggle(\"open\");\n \n // update the button text\n if (button.innerHTML === \"-\") {\n button.innerHTML = \"+\";\n } else {\n button.innerHTML = \"-\";\n }\n});\n\n\nThis code listens for a click event on the button, and then toggles the open class on the box element. The open class could be defined in your CSS as follows:\n.open {\n height: auto !important; /* or any other styles you want to apply to the expanded box */\n}\n\nThis way, you can use CSS transitions to smoothly animate the expansion and contraction of the box. You can also use the button.innerHTML property to update the button text when it is clicked.\nAn inline example would look like this:\n<!DOCTYPE html>\n<html>\n<head>\n <style>\n #box {\n height: 0;\n overflow: hidden;\n transition: height 0.5s;\n }\n \n .open {\n height: auto !important;\n }\n </style>\n</head>\n<body>\n <button id=\"button\">-</button>\n <div id=\"box\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in facilisis magna. Pellentesque hendrerit dolor in ipsum sagittis bibendum.\n </div>\n \n <script>\n // get the button and box elements\n var button = document.getElementById(\"button\");\n var box = document.getElementById(\"box\");\n\n // add a click event listener to the button\n button.addEventListener(\"click\", function() {\n // toggle the \"open\" class on the box\n box.classList.toggle(\"open\");\n\n // update the button text\n if (button.innerHTML === \"-\") {\n button.innerHTML = \"+\";\n } else {\n button.innerHTML = \"-\";\n }\n });\n </script>\n</body>\n</html>\n\n", "a simple google search came up with:\nhttps://www.itcodar.com/javascript/expand-div-on-click-with-smooth-animation.html#:~:text=How%20to%20display%20a%20div%20with%20a%20smooth,transition%20must%20include%20the%20change%20of%20height.%20Thus%3A\n\n\n\nfunction seeMore() {\n const text = document.getElementById('website-info-idea')\n const text2 = document.getElementById('website-info-technical')\n text.classList.toggle(\"show\")\n text2.classList.toggle(\"show\")\n}\n.col {\n opacity: 0;\n height: 0;\n overflow: hidden;\n transition: all 1s ease-in-out;\n}\n\n.col.show {\n opacity: 1;\n height: 23px;\n transition: all 1s ease-in-out;\n}\n\n#a1 {\n display:inline-block;\n border: solid 2px black;\n}\n<div id='a1'>\n <a onclick=\"seeMore()\" class=\"btn btn-secondary btn-md btn-custom\">About this Website</a>\n\n <div class=\"col\" id=\"website-info-idea\">Idea</div>\n <div class=\"col\" id=\"website-info-technical\">Technical</div>\n</div>\n\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "html", "javascript" ]
stackoverflow_0074671365_html_javascript.txt
Q: IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null") Hello everyone i need some help over this issue in Django *IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null") i got this when i tried to insert a new course * class Course(models.Model): category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE , related_name='teacher_courses') title = models.CharField(max_length=150) description = models.TextField() featured_img = models.ImageField(upload_to='course_imgs/',null=True) techs = models.TextField(null=True) class Meta: verbose_name_plural = "3. Courses" def related_content(self): related_content=Course.objects.filter(techs__icontains=self.techs) return serializers.serialize('json',related_content) def tech_list(self): tech_list = self.techs.split(',') return tech_list def __str__(self): return self.title class CourseList(generics.ListCreateAPIView): queryset = models.Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): qs = super().get_queryset() if 'result' in self.request.GET: limit = int(self.request.GET['result']) qs = models.Course.objects.all().order_by('-id')[:limit] if 'category' in self.request.GET: category = self.request.GET['category'] qs = models.Course.objects.filter(techs__icontains=category) if 'skill_name' in self.request.GET and 'teacher' in self.request.GET: skill_name = self.request.GET['skill_name'] teacher = self.request.GET['teacher'] teacher = models.Teacher.objects.filter(id=teacher).first() qs = models.Course.objects.filter(techs__icontains=skill_name,teacher=teacher) return qs class CourseSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields =['id','title','description','category_id','teacher','featured_img','techs','course_chapters','related_content','tech_list'] depth=1 I have been searching the solution for hours but i did not get any way to solve the issue and i expect you to help me thank you A: an integrity error is a database error, you're trying to enter a Course object without specifying (in your case) which CourseCategory object the Course Object is connected to. Here are the docs. You will have to choose an Existing CourseCategory to link the Course to. A: Problem resides in your category field in Course model. category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE) You have not assigned any CourseCategory object to your field. If that was a mistake you should assign a CourseCategory otherwise if you want to opt if CourseCategory can be accepted as null you should change that line to: category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE, blank=True, null=True) Furthermore, you need to change your category_id in your serializer to category. If your serializer fields are not custom, they should match their respective model's fields names.
IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null")
Hello everyone i need some help over this issue in Django *IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null") i got this when i tried to insert a new course * class Course(models.Model): category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE , related_name='teacher_courses') title = models.CharField(max_length=150) description = models.TextField() featured_img = models.ImageField(upload_to='course_imgs/',null=True) techs = models.TextField(null=True) class Meta: verbose_name_plural = "3. Courses" def related_content(self): related_content=Course.objects.filter(techs__icontains=self.techs) return serializers.serialize('json',related_content) def tech_list(self): tech_list = self.techs.split(',') return tech_list def __str__(self): return self.title class CourseList(generics.ListCreateAPIView): queryset = models.Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): qs = super().get_queryset() if 'result' in self.request.GET: limit = int(self.request.GET['result']) qs = models.Course.objects.all().order_by('-id')[:limit] if 'category' in self.request.GET: category = self.request.GET['category'] qs = models.Course.objects.filter(techs__icontains=category) if 'skill_name' in self.request.GET and 'teacher' in self.request.GET: skill_name = self.request.GET['skill_name'] teacher = self.request.GET['teacher'] teacher = models.Teacher.objects.filter(id=teacher).first() qs = models.Course.objects.filter(techs__icontains=skill_name,teacher=teacher) return qs class CourseSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields =['id','title','description','category_id','teacher','featured_img','techs','course_chapters','related_content','tech_list'] depth=1 I have been searching the solution for hours but i did not get any way to solve the issue and i expect you to help me thank you
[ "an integrity error is a database error, you're trying to enter a Course object without specifying (in your case) which CourseCategory object the Course Object is connected to. Here are the docs. You will have to choose an Existing CourseCategory to link the Course to.\n", "Problem resides in your category field in Course model.\n category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE)\n\nYou have not assigned any CourseCategory object to your field. If that was a mistake you should assign a CourseCategory otherwise if you want to opt if CourseCategory can be accepted as null you should change that line to:\n category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE, blank=True, null=True)\n\nFurthermore, you need to change your category_id in your serializer to category. If your serializer fields are not custom, they should match their respective model's fields names.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "django_rest_framework" ]
stackoverflow_0074672009_django_django_rest_framework.txt
Q: What is the most efficient way to implement table which stores sparse data in C# I have a DataTable which stores very sparse data, something like: P1 P2 P3 P4 P5 ... J1 1 1 J2 1 1 J3 1 . . . The number of rows and columns might reach over 10^8. How can I store this data in more efficient way? A: If your disk file system supports Sparse files you can create an empty file, mark it sparse, and then resize it to rows * colums * datasize. Then it's a matter of accessing the data by [row][column], where the offset can be calculated with: offset = ((columns.length * (row-1)) + column) * datasize There is some overhead with sparse files as well regarding allocation where it typically allocated pages of 16-64kb, but depending on how your data clusters it might very well work. A: First, get rid of the DataTable for those counts of data. Its memory usage is way to huge here. If your data are always 0/1, the most efficient way should be a bit-mask. If your data are not only 0/1, create a structure that abstracts all your columns. Here's a conceptional prototype of that data structure. class MyData { public MyData(int[] columns, object[] data) { _columns = columns; _data = data; } int[] _columns; object[] _data; public object this[int column] { get { int index = IndexOf(column); return index != -1 ? _data[index] : null; } } private int IndexOf(int column) { for (int i = 0; i < _columns.Length; i++) if (_columns[i] == column) return i; return -1; } } You could additionally save the memory for the _columns by applying the flyweight pattern. Hope this helps A: There is a lot of prior art in storing spare matrices efficiently. A common approach is known as 'List of Lists'. For example, Python has a memory efficient way of storing spare matrices as 'Row-based linked list sparse matrix'. A: The best solution depends on how you are going to use it, but if it does not need to be serialized you could consider using a nested dictionary like this: using System.Collections.Generic; public class SparseMatrix<T>: Dictionary<int, Dictionary<int, T>> { public void Add(int p, int j, T value) { Dictionary<int, T> jdic; if (!TryGetValue(p, out jdic)) { jdic = new Dictionary<int, T>(); Add(p, jdic); } jdic[j] = value; } public T query(int p, int j) { Dictionary<int, T> jdic; if (TryGetValue(p, out jdic)) { T val; if (jdic.TryGetValue(j, out val)) return val; } return default(T); } } You can use it, in your example with a boolean like so: using Xunit; public class TestSparseBoolMatrix { [Fact] public void TestSBM() { SparseMatrix<bool> matrix = new SparseMatrix<bool>(); matrix.Add(2, 4, true); matrix.Add(7, 3, true); bool NotSet = matrix.query(1, 1); bool isSet = matrix.query(2, 4); Assert.False(NotSet); Assert.True(isSet); } }
What is the most efficient way to implement table which stores sparse data in C#
I have a DataTable which stores very sparse data, something like: P1 P2 P3 P4 P5 ... J1 1 1 J2 1 1 J3 1 . . . The number of rows and columns might reach over 10^8. How can I store this data in more efficient way?
[ "If your disk file system supports Sparse files you can create an empty file, mark it sparse, and then resize it to rows * colums * datasize.\nThen it's a matter of accessing the data by [row][column], where the offset can be calculated with:\noffset = ((columns.length * (row-1)) + column) * datasize\n\nThere is some overhead with sparse files as well regarding allocation where it typically allocated pages of 16-64kb, but depending on how your data clusters it might very well work.\n", "First, get rid of the DataTable for those counts of data. Its memory usage is way to huge here.\nIf your data are always 0/1, the most efficient way should be a bit-mask.\nIf your data are not only 0/1, create a structure that abstracts all your columns.\nHere's a conceptional prototype of that data structure.\nclass MyData {\n public MyData(int[] columns, object[] data) {\n _columns = columns;\n _data = data;\n }\n\n int[] _columns;\n object[] _data;\n\n public object this[int column] {\n get {\n int index = IndexOf(column);\n return index != -1 ? _data[index] : null;\n }\n }\n\n private int IndexOf(int column) {\n for (int i = 0; i < _columns.Length; i++)\n if (_columns[i] == column)\n return i;\n return -1;\n }\n}\n\nYou could additionally save the memory for the _columns by applying the flyweight pattern.\nHope this helps\n", "There is a lot of prior art in storing spare matrices efficiently.\nA common approach is known as 'List of Lists'. For example, Python has a memory efficient way of storing spare matrices as 'Row-based linked list sparse matrix'. \n", "The best solution depends on how you are going to use it, but if it does not need to be serialized you could consider using a nested dictionary like this:\n using System.Collections.Generic;\n\n public class SparseMatrix<T>: Dictionary<int, Dictionary<int, T>>\n {\n public void Add(int p, int j, T value)\n {\n Dictionary<int, T> jdic;\n if (!TryGetValue(p, out jdic))\n {\n jdic = new Dictionary<int, T>();\n Add(p, jdic);\n }\n jdic[j] = value;\n }\n\n public T query(int p, int j)\n {\n Dictionary<int, T> jdic;\n if (TryGetValue(p, out jdic))\n {\n T val;\n if (jdic.TryGetValue(j, out val))\n return val;\n }\n\n return default(T);\n }\n }\n\nYou can use it, in your example with a boolean like so:\n using Xunit;\n\n public class TestSparseBoolMatrix\n {\n [Fact]\n public void TestSBM()\n {\n SparseMatrix<bool> matrix = new SparseMatrix<bool>();\n\n matrix.Add(2, 4, true);\n matrix.Add(7, 3, true);\n\n bool NotSet = matrix.query(1, 1);\n bool isSet = matrix.query(2, 4);\n\n Assert.False(NotSet);\n Assert.True(isSet);\n }\n }\n\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "c#", "sparse_matrix" ]
stackoverflow_0003306327_c#_sparse_matrix.txt
Q: npm install Fails With "Command not found" ... ONLY With One Package? This is a weird one. I recently setup a new (Linux) development machine, and normally npm works fine: $ npm i cheerio npm WARN ERESOLVE overriding peer dependency ... rest of installation output ... But when I try to install one specific package, local-ssl-proxy, I get an error: $ npm i local-ssl-proxy npm i local-ssl-proxy: command not found (NOTE: The package is actually designed to be installed globally, but I get the same error when I provide a -g argument.) I thought at first maybe it was the hyphens, but another hyphenated package works fine: $ npm i image-size npm WARN ERESOLVE overriding peer dependency ... rest of installation output ... Can anyone explain why some some packages would tell me npm doesn't exist, while some wouldn't? I figure it has to be a Bash issue or something (I do have the npm Bash completions installed, although I don't see how they could cause this). But I just don't see how failing to find the npm command could even be the fault of npm, and how my OS could fail to find npm just for one argument to the command. A: This problem wound up fixing itself, so the solution was as strange as the issue. I did however restart my terminal in-between, so that's the only thing I can attribute to the fix.
npm install Fails With "Command not found" ... ONLY With One Package?
This is a weird one. I recently setup a new (Linux) development machine, and normally npm works fine: $ npm i cheerio npm WARN ERESOLVE overriding peer dependency ... rest of installation output ... But when I try to install one specific package, local-ssl-proxy, I get an error: $ npm i local-ssl-proxy npm i local-ssl-proxy: command not found (NOTE: The package is actually designed to be installed globally, but I get the same error when I provide a -g argument.) I thought at first maybe it was the hyphens, but another hyphenated package works fine: $ npm i image-size npm WARN ERESOLVE overriding peer dependency ... rest of installation output ... Can anyone explain why some some packages would tell me npm doesn't exist, while some wouldn't? I figure it has to be a Bash issue or something (I do have the npm Bash completions installed, although I don't see how they could cause this). But I just don't see how failing to find the npm command could even be the fault of npm, and how my OS could fail to find npm just for one argument to the command.
[ "This problem wound up fixing itself, so the solution was as strange as the issue. I did however restart my terminal in-between, so that's the only thing I can attribute to the fix.\n" ]
[ 0 ]
[]
[]
[ "linux", "npm", "npm_install" ]
stackoverflow_0074669095_linux_npm_npm_install.txt
Q: Using partial_sum() with long long values I am solving a problem for which, I need to calculate the prefix and suffix sum values. When I do it this way: class Solution { public: int minimumAverageDifference(vector<int>& nums) { long n=size(nums); vector<long long> left(n,0ll), right(n,0ll); partial_sum(begin(nums), end(nums), begin(left)); partial_sum(rbegin(nums), rend(nums), rbegin(right)); return 0; } }; This works fine for smaller input values, but when the input is very large, I get an error: Line 258: Char 43: runtime error: signed integer overflow: 2147453785 + 36049 cannot be represented in type 'int' (stl_numeric.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_numeric.h:267:43 However, the traditional for-loop works just fine for all the inputs, including the very large ones: class Solution { public: int minimumAverageDifference(vector<int>& nums) { long n=size(nums); vector<long long> left(n,0ll), right(n,0ll); left[0]=nums[0]; for(int i=1; i<n; i++) { left[i]=left[i-1]+nums[i]; } right[n-1]=nums[n-1]; for(int i=n-2; i>=0; i--) { right[i]=right[i+1]+nums[i]; } return 0; } }; What am I missing about the usage of partial_sum()? A: std::partial_sum() is defined such that the accumulator type is that as the type of the input range element: typename std::iterator_traits<InputIt>::value_type sum = *first; ... This is also true for an overload that takes a custom binary operation. There is no simple way to override that type - you have to somehow modify the input range itself. If you really want to use std::partial_sum(), you could either copy the input range into std::vector<long long> or transform it on-fly using boost::transform_iterator: std::vector<int> in(5, INT_MAX); std::vector<long long> out(in.size()); auto cast_to_long_long = [](int v){ return static_cast<long long>(v); }; auto first = boost::make_transform_iterator(in.begin(), cast_to_long_long); auto last = boost::make_transform_iterator(in.end(), cast_to_long_long); std::partial_sum(first, last, out.begin()); Demo However, the simplest solution is to use std::inclusive_scan(), which accepts the initial value that determines the accumulator type: std::inclusive_scan(in.begin(), in.end(), out.begin(), std::plus(), 0LL); Demo
Using partial_sum() with long long values
I am solving a problem for which, I need to calculate the prefix and suffix sum values. When I do it this way: class Solution { public: int minimumAverageDifference(vector<int>& nums) { long n=size(nums); vector<long long> left(n,0ll), right(n,0ll); partial_sum(begin(nums), end(nums), begin(left)); partial_sum(rbegin(nums), rend(nums), rbegin(right)); return 0; } }; This works fine for smaller input values, but when the input is very large, I get an error: Line 258: Char 43: runtime error: signed integer overflow: 2147453785 + 36049 cannot be represented in type 'int' (stl_numeric.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_numeric.h:267:43 However, the traditional for-loop works just fine for all the inputs, including the very large ones: class Solution { public: int minimumAverageDifference(vector<int>& nums) { long n=size(nums); vector<long long> left(n,0ll), right(n,0ll); left[0]=nums[0]; for(int i=1; i<n; i++) { left[i]=left[i-1]+nums[i]; } right[n-1]=nums[n-1]; for(int i=n-2; i>=0; i--) { right[i]=right[i+1]+nums[i]; } return 0; } }; What am I missing about the usage of partial_sum()?
[ "std::partial_sum() is defined such that the accumulator type is that as the type of the input range element:\ntypename std::iterator_traits<InputIt>::value_type sum = *first;\n...\n\nThis is also true for an overload that takes a custom binary operation. There is no simple way to override that type - you have to somehow modify the input range itself.\nIf you really want to use std::partial_sum(), you could either copy the input range into std::vector<long long> or transform it on-fly using boost::transform_iterator:\nstd::vector<int> in(5, INT_MAX);\nstd::vector<long long> out(in.size());\n\nauto cast_to_long_long = [](int v){ return static_cast<long long>(v); };\nauto first = boost::make_transform_iterator(in.begin(), cast_to_long_long);\nauto last = boost::make_transform_iterator(in.end(), cast_to_long_long);\n\nstd::partial_sum(first, last, out.begin());\n\nDemo\nHowever, the simplest solution is to use std::inclusive_scan(), which accepts the initial value that determines the accumulator type:\nstd::inclusive_scan(in.begin(), in.end(), out.begin(), std::plus(), 0LL);\n\nDemo\n" ]
[ 0 ]
[]
[]
[ "algorithm", "c++", "prefix_sum", "stl" ]
stackoverflow_0074671972_algorithm_c++_prefix_sum_stl.txt
Q: JPA : How to handle mapping with a table that has relationship with two other tables? I have three tables, table A (product), table B (invoice) and table C (invoices_info) which contains two columns referencing invoice_id and product_id. How can i insert a new entry (a new invoice) while inserting the products to the appropriate table and inserting the invoice info to its table also ? Here are the entity classes : Product @Entity @Table(name = "product") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "family_id") private long familyId; @Column(name = "product_name") private String productName; @Column(name = "product_category") private String productCategory; @Column(name = "product_quantity") private int productQuantity; //getters and setters } Invoice @Entity @Table(name = "invoice") public class Invoice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "invoice_id") private Long id; @Column(name = "provider_id") private Long providerId; @Column(name = "total") private int invoiceTotal; @Column(name = "date") private Date invoiceDate; //getters and setters } InvoiceInfo @Entity @Table(name = "invoice_info") public class InvoiceInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "item_id") private long id; @Column(name = "product_id") private long productId; @Column(name = "invoice_id") private long invoiceId; //getters and setters } A: To insert a new entry in the invoice and invoice_info tables while inserting the products to the product table, you can use the Session#persist method from the Hibernate API. The Session#persist method allows you to save an entity to the database and automatically generates the required SQL INSERT statement for you. Here's an example of how you can use the Session#persist method to insert a new invoice and the associated products into the database: // create a new Product entity Product product = new Product(); product.setFamilyId(1); product.setProductName("Product 1"); product.setProductCategory("Category 1"); product.setProductQuantity(10); // create a new Invoice entity Invoice invoice = new Invoice(); invoice.setProviderId(1); invoice.setInvoiceTotal(100); invoice.setInvoiceDate(new Date()); // create a new InvoiceInfo entity InvoiceInfo invoiceInfo = new InvoiceInfo(); invoiceInfo.setProductId(product.getId()); invoiceInfo.setInvoiceId(invoice.getId()); // get the current Hibernate session Session session = sessionFactory.getCurrentSession(); // save the Product, Invoice, and InvoiceInfo entities to the database // using the persist method session.persist(product); session.persist(invoice); session.persist(invoiceInfo); In the code above, we create new Product, Invoice, and InvoiceInfo entities and then save them to the database using the Session#persist method. This will automatically generate the required SQL INSERT statements to insert the new entities into the appropriate tables. It's important to note that the Session#persist method does not commit the transaction automatically. This means that you will need to explicitly call the Session#commit method in order to save the changes to the database. You can do this by adding the following line of code after the Session#persist calls: session.commit(); A: InvoiceInfo should be join table, Define relationship on entities Product & Invoice using annotations @OneToMany, @ManyToOne based on your requirement. A: You have to create relationships between your entities by using a set of annotations like: @ManyToOne, @OneToMany, @ManyToMany or @OneToOne... and other annotations if needed. In your case I am not really sure you need an InvoiceInfo table, as the Invoice table can (or should) already contains the list of products. I would suggest you the following relationships: Product @Entity @Table(name = "product") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "family_id") private long familyId; @Column(name = "product_name") private String productName; @Column(name = "product_category") private String productCategory; @Column(name = "product_quantity") private int productQuantity; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "invoice_id", referencedColumnName = "id") private Invoice invoice; //getters and setters } Invoice @Entity @Table(name = "invoice") public class Invoice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "invoice_id") private Long id; @Column(name = "provider_id") private Long providerId; @Column(name = "total") private int invoiceTotal; @Column(name = "date") private Date invoiceDate; @OneToMany(mappedBy = "product") private List<Product> products; //getters and setters } As your table InvoiceInfo no longer exists, you just have to insert you data in two table like this: Invoice invoice = invoiceRepository.save(invoice); Product product = new Product(); // Set the other properties product.setInvoice(invoice); productRepository.save(product);
JPA : How to handle mapping with a table that has relationship with two other tables?
I have three tables, table A (product), table B (invoice) and table C (invoices_info) which contains two columns referencing invoice_id and product_id. How can i insert a new entry (a new invoice) while inserting the products to the appropriate table and inserting the invoice info to its table also ? Here are the entity classes : Product @Entity @Table(name = "product") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "family_id") private long familyId; @Column(name = "product_name") private String productName; @Column(name = "product_category") private String productCategory; @Column(name = "product_quantity") private int productQuantity; //getters and setters } Invoice @Entity @Table(name = "invoice") public class Invoice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "invoice_id") private Long id; @Column(name = "provider_id") private Long providerId; @Column(name = "total") private int invoiceTotal; @Column(name = "date") private Date invoiceDate; //getters and setters } InvoiceInfo @Entity @Table(name = "invoice_info") public class InvoiceInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "item_id") private long id; @Column(name = "product_id") private long productId; @Column(name = "invoice_id") private long invoiceId; //getters and setters }
[ "To insert a new entry in the invoice and invoice_info tables while inserting the products to the product table, you can use the Session#persist method from the Hibernate API. The Session#persist method allows you to save an entity to the database and automatically generates the required SQL INSERT statement for you.\nHere's an example of how you can use the Session#persist method to insert a new invoice and the associated products into the database:\n// create a new Product entity\nProduct product = new Product();\nproduct.setFamilyId(1);\nproduct.setProductName(\"Product 1\");\nproduct.setProductCategory(\"Category 1\");\nproduct.setProductQuantity(10);\n\n// create a new Invoice entity\nInvoice invoice = new Invoice();\ninvoice.setProviderId(1);\ninvoice.setInvoiceTotal(100);\ninvoice.setInvoiceDate(new Date());\n\n// create a new InvoiceInfo entity\nInvoiceInfo invoiceInfo = new InvoiceInfo();\ninvoiceInfo.setProductId(product.getId());\ninvoiceInfo.setInvoiceId(invoice.getId());\n\n// get the current Hibernate session\nSession session = sessionFactory.getCurrentSession();\n\n// save the Product, Invoice, and InvoiceInfo entities to the database\n// using the persist method\nsession.persist(product);\nsession.persist(invoice);\nsession.persist(invoiceInfo);\n\nIn the code above, we create new Product, Invoice, and InvoiceInfo entities and then save them to the database using the Session#persist method. This will automatically generate the required SQL INSERT statements to insert the new entities into the appropriate tables.\nIt's important to note that the Session#persist method does not commit the transaction automatically. This means that you will need to explicitly call the Session#commit method in order to save the changes to the database. You can do this by adding the following line of code after the Session#persist calls:\nsession.commit();\n\n", "InvoiceInfo should be join table, Define relationship on entities Product & Invoice using annotations @OneToMany, @ManyToOne based on your requirement.\n", "You have to create relationships between your entities by using a set of annotations like: @ManyToOne, @OneToMany, @ManyToMany or @OneToOne... and other annotations if needed.\nIn your case I am not really sure you need an InvoiceInfo table, as the Invoice table can (or should) already contains the list of products.\nI would suggest you the following relationships:\nProduct\n@Entity\n@Table(name = \"product\")\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\")\n private Long id;\n @Column(name = \"family_id\")\n private long familyId; \n @Column(name = \"product_name\")\n private String productName;\n @Column(name = \"product_category\")\n private String productCategory;\n @Column(name = \"product_quantity\") \n private int productQuantity;\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"invoice_id\", referencedColumnName = \"id\")\n private Invoice invoice;\n //getters and setters\n}\n\nInvoice\n@Entity\n@Table(name = \"invoice\")\npublic class Invoice {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"invoice_id\")\n private Long id;\n @Column(name = \"provider_id\")\n private Long providerId;\n @Column(name = \"total\")\n private int invoiceTotal;\n @Column(name = \"date\")\n private Date invoiceDate;\n @OneToMany(mappedBy = \"product\")\n private List<Product> products;\n //getters and setters\n}\n\nAs your table InvoiceInfo no longer exists, you just have to insert you data in two table like this:\nInvoice invoice = invoiceRepository.save(invoice);\nProduct product = new Product();\n// Set the other properties\nproduct.setInvoice(invoice);\nproductRepository.save(product);\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "hibernate", "java", "jpa" ]
stackoverflow_0074671623_hibernate_java_jpa.txt
Q: How to add multiple image upload functionality in Django form.Imagefield()? How to allow users to upload multiple images through Django Forms, which was fetched in Django template by using form.ImageField() it was providing the following output: <input type="file" name="image" accept"Image/*" id="id_image"> This is allowing to upload only one image, But need to provide multiple upload option. But I need the following output using Django Form with my custom class <input type="file" multiple accept"Image/*" id="id_image" class="myclass1 myclass2"> How can I achieve this? A: Django doesn't allow this, but I've done something similar by following along with this article upload multiple images in django. Another workaround is just to create a model for all of the image files and link in to your current model.
How to add multiple image upload functionality in Django form.Imagefield()?
How to allow users to upload multiple images through Django Forms, which was fetched in Django template by using form.ImageField() it was providing the following output: <input type="file" name="image" accept"Image/*" id="id_image"> This is allowing to upload only one image, But need to provide multiple upload option. But I need the following output using Django Form with my custom class <input type="file" multiple accept"Image/*" id="id_image" class="myclass1 myclass2"> How can I achieve this?
[ "Django doesn't allow this, but I've done something similar by following along with this article upload multiple images in django. Another workaround is just to create a model for all of the image files and link in to your current model.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates" ]
stackoverflow_0074664605_django_django_forms_django_templates.txt
Q: How to click on link and redirects me to a new page in react how to click on anchor tag in the card and redirects me to another page with more details of the current card example click on opens new tab with current (clicked) card details here is an api for item https://api.npoint.io/d275425a434e02acf2f7/News/0 snippets of code also a link that works https://codesandbox.io/s/sweet-spence-1tl4y5?file=/src/App.js my api https://api.npoint.io/d275425a434e02acf2f7 for rendering all items in cards filteredCat?.map((list) => { if (list.showOnHomepage === "yes") { const date = format( new Date(list.publishedDate), "EEE dd MMM yyyy" ); const showCat = news.map((getid) => { if (getid.id == list.categoryID) return getid.name; }); // const rec = list.publishedDate.sort((date1, date2) => date1 - date2); return ( <Card className=" extraCard col-lg-3" style={{ width: "" }} id={list.categoryID} > <Card.Img variant="top" src={list.urlToImage} alt="Image" /> <Card.Body> <Card.Title className="textTitle"> {list.title} </Card.Title> <Card.Text></Card.Text> <small className="text-muted d-flex"> <FaRegCalendarAlt className="m-1" style={{ color: "#0aceff" }} /> {date} </small> <div style={{ color: "#0aceff" }} className="d-flex justify-content-between" > <Button variant="" className={classes["btn-cat"]}> {showCat} </Button> <div> <FaRegHeart /> <FaLink /> </div> </div> </Card.Body> </Card> ); } }) } </div> } opens to a in new tab A: To make an anchor tag redirect to another page, you can use the onClick event to call a function that uses the window.location.href property to redirect the user to the desired page. Here is an example of how to do this: function handleClick(event) { event.preventDefault(); window.location.href = 'https://www.example.com'; } function App() { return ( <a href="#" onClick={handleClick}> Click me to redirect! </a> ); } In this example, when the user clicks on the anchor tag, the handleClick function is called. This function prevents the default behavior of the anchor tag (which is to navigate to the URL specified in the href attribute), and instead sets the window.location.href property to the desired URL, redirecting the user to that page. You can use this same approach to redirect the user to a page with more details about the current card, using the card's ID to specify the details page for that particular card.
How to click on link and redirects me to a new page in react
how to click on anchor tag in the card and redirects me to another page with more details of the current card example click on opens new tab with current (clicked) card details here is an api for item https://api.npoint.io/d275425a434e02acf2f7/News/0 snippets of code also a link that works https://codesandbox.io/s/sweet-spence-1tl4y5?file=/src/App.js my api https://api.npoint.io/d275425a434e02acf2f7 for rendering all items in cards filteredCat?.map((list) => { if (list.showOnHomepage === "yes") { const date = format( new Date(list.publishedDate), "EEE dd MMM yyyy" ); const showCat = news.map((getid) => { if (getid.id == list.categoryID) return getid.name; }); // const rec = list.publishedDate.sort((date1, date2) => date1 - date2); return ( <Card className=" extraCard col-lg-3" style={{ width: "" }} id={list.categoryID} > <Card.Img variant="top" src={list.urlToImage} alt="Image" /> <Card.Body> <Card.Title className="textTitle"> {list.title} </Card.Title> <Card.Text></Card.Text> <small className="text-muted d-flex"> <FaRegCalendarAlt className="m-1" style={{ color: "#0aceff" }} /> {date} </small> <div style={{ color: "#0aceff" }} className="d-flex justify-content-between" > <Button variant="" className={classes["btn-cat"]}> {showCat} </Button> <div> <FaRegHeart /> <FaLink /> </div> </div> </Card.Body> </Card> ); } }) } </div> } opens to a in new tab
[ "To make an anchor tag redirect to another page, you can use the onClick event to call a function that uses the window.location.href property to redirect the user to the desired page.\nHere is an example of how to do this:\nfunction handleClick(event) {\n event.preventDefault();\n window.location.href = 'https://www.example.com';\n}\n\nfunction App() {\n return (\n <a href=\"#\" onClick={handleClick}>\n Click me to redirect!\n </a>\n );\n}\n\nIn this example, when the user clicks on the anchor tag, the handleClick function is called. This function prevents the default behavior of the anchor tag (which is to navigate to the URL specified in the href attribute), and instead sets the window.location.href property to the desired URL, redirecting the user to that page.\nYou can use this same approach to redirect the user to a page with more details about the current card, using the card's ID to specify the details page for that particular card.\n" ]
[ 0 ]
[]
[]
[ "reactjs" ]
stackoverflow_0074671678_reactjs.txt