id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
55b6d7b495f46fd55e829e19f2b74021c8dce0a2
Stackoverflow Stackexchange Q: Where is or What is the serviceAccountKey.json is the node js sample of firebase realtime database I have downloaded the zip of Firebase real-time database node.js sample and navigate to the database section https://github.com/firebase/quickstart-nodejs/tree/master/database And I located to the line 35 which has the following code var serviceAccount = require('path/to/serviceAccountKey.json'); But I was wondering where is/what is the serviceAccountKey.json? A: Go to settings -> Service Account -> Generate New private key That will download the required Json
Q: Where is or What is the serviceAccountKey.json is the node js sample of firebase realtime database I have downloaded the zip of Firebase real-time database node.js sample and navigate to the database section https://github.com/firebase/quickstart-nodejs/tree/master/database And I located to the line 35 which has the following code var serviceAccount = require('path/to/serviceAccountKey.json'); But I was wondering where is/what is the serviceAccountKey.json? A: Go to settings -> Service Account -> Generate New private key That will download the required Json A: How to download your serviceAccountKey.json file * *Open Your firebase project *On the navigation drawer, select the project overview *Then select "Project settings" *On the new page, Select Service Accounts *Download file and store in a secured place. Note: Do not commit this file to git or share it with unauthorized users. A: It's a JSON file generated in the Firebase Console (see Add Firebase to your App) containing credentials about your corresponding Service Account. A: * *require('path/to/serviceAccountKey.json') means - call this file to be used in the file you are calling it *serviceAccountKey.json is a file that you have to generate *If you look at this page 'Add Firebase To Your App' https://firebase.google.com/docs/ios/setup under 'Add Firebase to your app' - it says Navigate to the Service Accounts and generate a new private key, doing this will generate what will be your 'serviceAccountKey.json' file after you rename it *place that file in the directory of your choosing local to your cloud code directory, have a look at this comment https://stackoverflow.com/a/42634321/2472466 for more insight into step 4
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:891985", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626919" }
6e48948f6eed894e204df33d05af544c844de1bf
Stackoverflow Stackexchange Q: Merge multiple columns into one column in pyspark dataframe using python I need to merge multiple columns of a dataframe into one single column with list(or tuple) as the value for the column using pyspark in python. Input dataframe: +-------+-------+-------+-------+-------+ | name |mark1 |mark2 |mark3 | Grade | +-------+-------+-------+-------+-------+ | Jim | 20 | 30 | 40 | "C" | +-------+-------+-------+-------+-------+ | Bill | 30 | 35 | 45 | "A" | +-------+-------+-------+-------+-------+ | Kim | 25 | 36 | 42 | "B" | +-------+-------+-------+-------+-------+ Output dataframe should be +-------+-----------------+ | name |marks | +-------+-----------------+ | Jim | [20,30,40,"C"] | +-------+-----------------+ | Bill | [30,35,45,"A"] | +-------+-----------------+ | Kim | [25,36,42,"B"] | +-------+-----------------+ A: look at this doc : https://spark.apache.org/docs/2.1.0/ml-features.html#vectorassembler from pyspark.ml.linalg import Vectors from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler( inputCols=["mark1", "mark2", "mark3"], outputCol="marks") output = assembler.transform(dataset) output.select("name", "marks").show(truncate=False)
Q: Merge multiple columns into one column in pyspark dataframe using python I need to merge multiple columns of a dataframe into one single column with list(or tuple) as the value for the column using pyspark in python. Input dataframe: +-------+-------+-------+-------+-------+ | name |mark1 |mark2 |mark3 | Grade | +-------+-------+-------+-------+-------+ | Jim | 20 | 30 | 40 | "C" | +-------+-------+-------+-------+-------+ | Bill | 30 | 35 | 45 | "A" | +-------+-------+-------+-------+-------+ | Kim | 25 | 36 | 42 | "B" | +-------+-------+-------+-------+-------+ Output dataframe should be +-------+-----------------+ | name |marks | +-------+-----------------+ | Jim | [20,30,40,"C"] | +-------+-----------------+ | Bill | [30,35,45,"A"] | +-------+-----------------+ | Kim | [25,36,42,"B"] | +-------+-----------------+ A: look at this doc : https://spark.apache.org/docs/2.1.0/ml-features.html#vectorassembler from pyspark.ml.linalg import Vectors from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler( inputCols=["mark1", "mark2", "mark3"], outputCol="marks") output = assembler.transform(dataset) output.select("name", "marks").show(truncate=False) A: Columns can be merged with sparks array function: import pyspark.sql.functions as f columns = [f.col("mark1"), ...] output = input.withColumn("marks", f.array(columns)).select("name", "marks") You might need to change the type of the entries in order for the merge to be successful A: You can do it in a select like following: from pyspark.sql.functions import * df.select( 'name' , concat( col("mark1"), lit(","), col("mark2"), lit(","), col("mark3"), lit(","), col("Grade") ).alias('marks') ) If [ ] necessary, it can be added lit function. from pyspark.sql.functions import * df.select( 'name' , concat(lit("["), col("mark1"), lit(","), col("mark2"), lit(","), col("mark3"), lit(","), col("Grade"), lit("]") ).alias('marks') ) A: If this is still relevant, you can use StringIndexer to encode your string values to float substitutes.
stackoverflow
{ "language": "en", "length": 254, "provenance": "stackexchange_0000F.jsonl.gz:892007", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626986" }
fd85feb38976c1558242ca474e5a496073613bfc
Stackoverflow Stackexchange Q: VBA dont find my Sheet name I have this part of code in vba in Excel to past value from cliboard: Dim WS as Worksheet Set WS = Sheets.Add SheetName= "New One" Sheets("New One").Range("A11").PasteSpecial xlValues And I have this problem: error '9' Subscript out of range. If I change the sheet name to a technical name like sheet19, work well, but I don't know the technical name of the sheet that is being created in the moment. How can I solve this? Thks in advance A: Change SheetName= "New One" Into WS.Name= "New One" Your statement is not changing the name of the sheet, but just assigning a variable. Also, since you have a reference on the sheet, that is WS, why invoke it again by the name, why not just WS.Range("A11").PasteSpecial xlPasteValues
Q: VBA dont find my Sheet name I have this part of code in vba in Excel to past value from cliboard: Dim WS as Worksheet Set WS = Sheets.Add SheetName= "New One" Sheets("New One").Range("A11").PasteSpecial xlValues And I have this problem: error '9' Subscript out of range. If I change the sheet name to a technical name like sheet19, work well, but I don't know the technical name of the sheet that is being created in the moment. How can I solve this? Thks in advance A: Change SheetName= "New One" Into WS.Name= "New One" Your statement is not changing the name of the sheet, but just assigning a variable. Also, since you have a reference on the sheet, that is WS, why invoke it again by the name, why not just WS.Range("A11").PasteSpecial xlPasteValues A: Something like this works: Public Sub TestMe() Dim WS As Worksheet Dim SheetName As String Set WS = Sheets.Add WS.Name = "New One" WS.Range("A11") = 45 'Alternative: Worksheets(WS.Name).Range("A15") = 46 End Sub Refer to WS later, or use Worksheets(WS.Name). Do not use Sheets, because it also refers to Charts, if you have some. A: use this ws.Name= "New One" ws.Range("A11").PasteSpecial xlValues A: It seems to me that your range is wrongly defined. It must be something like this Range(Cells(x1,y1),Cells(x2,y2)) Also if it a constructed worksheet at run time, you may need to use ThisWorkbook or ActiveSheet references. Try changing your range in above format and let me know.
stackoverflow
{ "language": "en", "length": 243, "provenance": "stackexchange_0000F.jsonl.gz:892022", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627027" }
98cde7830bd40eae1847e41a6ca8a11a499872db
Stackoverflow Stackexchange Q: asp.net Images not loading after publishing My images won't load after I publish my application. They do load when I'm debugging. Any idea what can cause this problem? <a class="navbar-brand" href="@Url.Action("SearchQuery", "Search")"><img id="logo" src="~/Images/Logo.png"/></a> A: Steps to add images to be published: 1) Right click the images folder and select "Include In Project" 2) Now you should see Build Action: Content on the properties for the images.
Q: asp.net Images not loading after publishing My images won't load after I publish my application. They do load when I'm debugging. Any idea what can cause this problem? <a class="navbar-brand" href="@Url.Action("SearchQuery", "Search")"><img id="logo" src="~/Images/Logo.png"/></a> A: Steps to add images to be published: 1) Right click the images folder and select "Include In Project" 2) Now you should see Build Action: Content on the properties for the images. A: Try Url.Content on your src attribute: src="@Url.Content("~/Images/Logo.png")" A: Are you sure you have set the Image folder to be deployed along with your other files (Folder --> Properties --> Build Action)? For further information please take a look at: https://msdn.microsoft.com/en-us/library/ee942158(v=vs.110).aspx#Anchor_1 A: Please check your publish code because of after your publish this image not appear in particular folder. may be issue of publish. A: Maybe you do add image to your development folder (via explorer etc) but not to your project. If an image file is not included in project, this will happen. If this is the case; please check if you can see logo.png under Images folder with an image icon in Visual Studio's solution explorer. If it's not there try checking "Show All Files" in solution explorer's toolbar. Then try right click -> Include In Project. After that, publish will copy the file to output folder. A: THIS may help. I had the same problem - image loading at debugging in VS/IIS, but not after deployment on another computer. Did all that was advised here and elsewhere. After hours of searching and not finding any answers, I came across the most fundamental solution. Turned out, it was my fault, being too hasty with the windows features setup. You need to turn on static content for WWW services, as it is described in the linked answer, and as was probably mentioned in every tutorial ever, which obviously I missed. Hope that helps someone. A: When a image wont load, always be sure to inspect the network tab within the dev tools. I had a problem where images with a specific folder wouldn't load after upload. Turned out that I had adblock installed on my pc and the folder was named Adverts. duh!
stackoverflow
{ "language": "en", "length": 362, "provenance": "stackexchange_0000F.jsonl.gz:892044", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627092" }
a128264e79f93fd5c63c2cac7da37a0c96148049
Stackoverflow Stackexchange Q: Angular 2 - Best way to get component's DOM Element in a unit test I've a sample Angular component template like below: <div style="border-bottom: 1px solid lightgray;"> <br> <div class="row"> <div class="col-md-2 text-center"> <a (click)="downloadFile()" class="download-file"><i class="fa fa-download fa-fw"></i>&nbsp;Download</a> </div> <div class="col-md-1 text-center"> <i [ngClass]="getFileIconClass"></i> </div> <div class="col-md-9"> <div class="row"> <div class="col-md-1"><strong>Name</strong></div> <div class="col-md-3"> <span>{{attachment.fileName}}</span> </div> </div> <div class="row"> <div class="col-md-1"><strong>Notes</strong></div> <div class="col-md-11"> <span>{{attachment.notes}}</span> </div> </div> </div> </div> <br> </div> I've to write a unit test to check if the Name and Notes contain correct value passed in the attachment object. For this purpose I've to get the HTMLElements from the DOM. I need to know what is the best practice to get HTMLElement in this case. Should I define a specific Id/Class attribute for each span like: ... <span class="fileName">{{attachment.fileName}}</span> ... <span class="notes">{{attachment.notes}}</span> ... and get HTMLElement like: fileNameEl = fixture.debugElement.query(By.css('.fileName')); // find span element for fileName notesEl = fixture.debugElement.query(By.css('.notes')); // find span element for notes element or should I just use JavaScript functions (like parentNode, childNodes, firstChild, nextSibling, querySelector etc) to navigate between nodes.
Q: Angular 2 - Best way to get component's DOM Element in a unit test I've a sample Angular component template like below: <div style="border-bottom: 1px solid lightgray;"> <br> <div class="row"> <div class="col-md-2 text-center"> <a (click)="downloadFile()" class="download-file"><i class="fa fa-download fa-fw"></i>&nbsp;Download</a> </div> <div class="col-md-1 text-center"> <i [ngClass]="getFileIconClass"></i> </div> <div class="col-md-9"> <div class="row"> <div class="col-md-1"><strong>Name</strong></div> <div class="col-md-3"> <span>{{attachment.fileName}}</span> </div> </div> <div class="row"> <div class="col-md-1"><strong>Notes</strong></div> <div class="col-md-11"> <span>{{attachment.notes}}</span> </div> </div> </div> </div> <br> </div> I've to write a unit test to check if the Name and Notes contain correct value passed in the attachment object. For this purpose I've to get the HTMLElements from the DOM. I need to know what is the best practice to get HTMLElement in this case. Should I define a specific Id/Class attribute for each span like: ... <span class="fileName">{{attachment.fileName}}</span> ... <span class="notes">{{attachment.notes}}</span> ... and get HTMLElement like: fileNameEl = fixture.debugElement.query(By.css('.fileName')); // find span element for fileName notesEl = fixture.debugElement.query(By.css('.notes')); // find span element for notes element or should I just use JavaScript functions (like parentNode, childNodes, firstChild, nextSibling, querySelector etc) to navigate between nodes.
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:892059", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627137" }
cd9fdb327c2ee9120062edfef374248a2b469cb6
Stackoverflow Stackexchange Q: How do I use Typescript definition (typings) files installed via NuGet in VS2017? I'm a little unsure on how I would go about using a typescript definition file that has been installed via NuGet in 2017. I'd like to use the 'modal' Bootstrap Jquery method on a JQuery Selector in order to show a modal popup box, but the TypeScript compiler does not recognise the '.modal' method, even though the Bootstrap definition file has been installed correctly. Even though the definitelytyped definition files have been installed via NuGet, the typescript compiler doesn't seem to be finding them. Are there any steps I need to take in order for the compiler to recognise the definition files as being installed? A: Seems like nuget isn't supported any longer for installing DefinitelyTyped definitions for Asp.Net Core. References : Visual Studio Forum DefinitelyTyped Github page
Q: How do I use Typescript definition (typings) files installed via NuGet in VS2017? I'm a little unsure on how I would go about using a typescript definition file that has been installed via NuGet in 2017. I'd like to use the 'modal' Bootstrap Jquery method on a JQuery Selector in order to show a modal popup box, but the TypeScript compiler does not recognise the '.modal' method, even though the Bootstrap definition file has been installed correctly. Even though the definitelytyped definition files have been installed via NuGet, the typescript compiler doesn't seem to be finding them. Are there any steps I need to take in order for the compiler to recognise the definition files as being installed? A: Seems like nuget isn't supported any longer for installing DefinitelyTyped definitions for Asp.Net Core. References : Visual Studio Forum DefinitelyTyped Github page
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:892086", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627215" }
008dda4a4bbc316fd3f19991f591c721b425a236
Stackoverflow Stackexchange Q: mongodb multiply aggregation operator Say I have the following aggregation : db.a.aggregate( [ { $project: { total: { $multiply: [ 4533, 0.0001 ] } } } ] ) The output of this aggregation is 0.45330000000000004 when it clearly should be 0.4533. Is this a bug in the aggregation framework? A: Okay then I was going to suggest multiplying and using $trunc, but you can basically get away with just chaining $multiply and $divide here: db.a.aggregate( [ { "$project": { "total": { "$divide": [ { "$multiply": [ { "$multiply": [ 4533, 0.0001 ] }, 10000 ]}, 10000 ] } }} ] ) or just $divide when that is what you mean: db.a.aggregate([ { "$project": { "total": { "$divide": [ 4533, 10000 ] } } } ]) Which both will give you: { "total" : 0.4533 } As noted, There is nothing new about floating point math and rounding, and as a general course you should avoid usage and simply apply the "non-floating point" version of what you actually mean. The long read if you have a while is at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Q: mongodb multiply aggregation operator Say I have the following aggregation : db.a.aggregate( [ { $project: { total: { $multiply: [ 4533, 0.0001 ] } } } ] ) The output of this aggregation is 0.45330000000000004 when it clearly should be 0.4533. Is this a bug in the aggregation framework? A: Okay then I was going to suggest multiplying and using $trunc, but you can basically get away with just chaining $multiply and $divide here: db.a.aggregate( [ { "$project": { "total": { "$divide": [ { "$multiply": [ { "$multiply": [ 4533, 0.0001 ] }, 10000 ]}, 10000 ] } }} ] ) or just $divide when that is what you mean: db.a.aggregate([ { "$project": { "total": { "$divide": [ 4533, 10000 ] } } } ]) Which both will give you: { "total" : 0.4533 } As noted, There is nothing new about floating point math and rounding, and as a general course you should avoid usage and simply apply the "non-floating point" version of what you actually mean. The long read if you have a while is at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:892093", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627233" }
58ac17bf2b891166976c309e98cddfe279580736
Stackoverflow Stackexchange Q: Log REST resource URL using Spring AspectJ I am using Spring Boot to develop a REST API and I would like to log the URL of the resources being retrieved by the clients using Spring Aspect. My class for the Aspect have this code: @Component @Aspect public class Logs { @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") public void allResources() {} @Before("allResources()") public void apiRequestLog(JoinPoint jp) { LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info("------------------------- o -------------------------"); String log = jp.getSignature().getName() + " >>>"; for (Object arg : jp.getArgs()) { log += "\n ARG: " + arg; } LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info(log); } } I dont know how to pass the RequestMapping object as parameter for the advice, and get the path of the URL. A: You can let Spring inject the client's request into your aspect: @Component @Aspect public class Logs { @Autowired(required = false) private HttpServletRequest request; ... The original URL called by the client can then be retrieved from that in the before-method via: request.getRequestURL();
Q: Log REST resource URL using Spring AspectJ I am using Spring Boot to develop a REST API and I would like to log the URL of the resources being retrieved by the clients using Spring Aspect. My class for the Aspect have this code: @Component @Aspect public class Logs { @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") public void allResources() {} @Before("allResources()") public void apiRequestLog(JoinPoint jp) { LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info("------------------------- o -------------------------"); String log = jp.getSignature().getName() + " >>>"; for (Object arg : jp.getArgs()) { log += "\n ARG: " + arg; } LogManager.getLogger(jp.getSignature().getDeclaringTypeName()).info(log); } } I dont know how to pass the RequestMapping object as parameter for the advice, and get the path of the URL. A: You can let Spring inject the client's request into your aspect: @Component @Aspect public class Logs { @Autowired(required = false) private HttpServletRequest request; ... The original URL called by the client can then be retrieved from that in the before-method via: request.getRequestURL(); A: An alternative without autowiring: @Around("isRestController()") public Object logApiCall(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); log.debug("{} {} from {}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr());
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:892102", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627269" }
dbc62003fba5656a1c8da0fad523f8f87ffe27c3
Stackoverflow Stackexchange Q: How to create & train a neural model to use for Core ML Apple introduced Core ML. There are many third parties providing trained models. But what if I want to create a model myself? How can I do that and what tools & technologies can I use? A: Core ML doesn't provide a way to train your own models. You only can convert existing ones to Apple 'mlmodel' format. To create your own neural networks, use Caffe or Keras frameworks and then convert those models to CoreML format. For traditional machine learning algorithms Core ML is also compatible with Scikit-learn* and XGBoost. You can also train and run neural networks on iOS without Core ML, just use Caffe 2 or TensorFlow. I support a long list of iOS-compatible machine learning libraries, if you're interested. All libraries mentioned above have a great documentation and a lot of tutorials for you to start creating your own models. *LibSVM is also compatible, but scikit-learn uses it under the hood anyway.
Q: How to create & train a neural model to use for Core ML Apple introduced Core ML. There are many third parties providing trained models. But what if I want to create a model myself? How can I do that and what tools & technologies can I use? A: Core ML doesn't provide a way to train your own models. You only can convert existing ones to Apple 'mlmodel' format. To create your own neural networks, use Caffe or Keras frameworks and then convert those models to CoreML format. For traditional machine learning algorithms Core ML is also compatible with Scikit-learn* and XGBoost. You can also train and run neural networks on iOS without Core ML, just use Caffe 2 or TensorFlow. I support a long list of iOS-compatible machine learning libraries, if you're interested. All libraries mentioned above have a great documentation and a lot of tutorials for you to start creating your own models. *LibSVM is also compatible, but scikit-learn uses it under the hood anyway.
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:892104", "question_score": "19", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627276" }
b777452269624e5ab8d891cc8fbe7f23d54dad9e
Stackoverflow Stackexchange Q: How to find count of Null and Nan values for each column in a PySpark dataframe efficiently? import numpy as np data = [ (1, 1, None), (1, 2, float(5)), (1, 3, np.nan), (1, 4, None), (1, 5, float(10)), (1, 6, float("nan")), (1, 6, float("nan")), ] df = spark.createDataFrame(data, ("session", "timestamp1", "id2")) Expected output dataframe with count of nan/null for each column Note: The previous questions I found in stack overflow only checks for null & not nan. That's why I have created a new question. I know I can use isnull() function in Spark to find number of Null values in Spark column but how to find Nan values in Spark dataframe? A: Here is my one liner. Here 'c' is the name of the column from pyspark.sql.functions import isnan, when, count, col, isNull df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()
Q: How to find count of Null and Nan values for each column in a PySpark dataframe efficiently? import numpy as np data = [ (1, 1, None), (1, 2, float(5)), (1, 3, np.nan), (1, 4, None), (1, 5, float(10)), (1, 6, float("nan")), (1, 6, float("nan")), ] df = spark.createDataFrame(data, ("session", "timestamp1", "id2")) Expected output dataframe with count of nan/null for each column Note: The previous questions I found in stack overflow only checks for null & not nan. That's why I have created a new question. I know I can use isnull() function in Spark to find number of Null values in Spark column but how to find Nan values in Spark dataframe? A: Here is my one liner. Here 'c' is the name of the column from pyspark.sql.functions import isnan, when, count, col, isNull df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count() A: An alternative to the already provided ways is to simply filter on the column like so import pyspark.sql.functions as F df = df.where(F.col('columnNameHere').isNull()) This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets. A: For null values in the dataframe of pyspark Dict_Null = {col:df.filter(df[col].isNull()).count() for col in df.columns} Dict_Null # The output in dict where key is column name and value is null values in that column {'#': 0, 'Name': 0, 'Type 1': 0, 'Type 2': 386, 'Total': 0, 'HP': 0, 'Attack': 0, 'Defense': 0, 'Sp_Atk': 0, 'Sp_Def': 0, 'Speed': 0, 'Generation': 0, 'Legendary': 0} A: You can use method shown here and replace isNull with isnan: from pyspark.sql.functions import isnan, when, count, col df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show() +-------+----------+---+ |session|timestamp1|id2| +-------+----------+---+ | 0| 0| 3| +-------+----------+---+ or df.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in df.columns]).show() +-------+----------+---+ |session|timestamp1|id2| +-------+----------+---+ | 0| 0| 5| +-------+----------+---+ A: To make sure it does not fail for string, date and timestamp columns: import pyspark.sql.functions as F def count_missings(spark_df,sort=True): """ Counts number of nulls and nans in each column """ df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas() if len(df) == 0: print("There are no any missing values!") return None if sort: return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False) return df If you want to see the columns sorted based on the number of nans and nulls in descending: count_missings(spark_df) # | Col_A | 10 | # | Col_C | 2 | # | Col_B | 1 | If you don't want ordering and see them as a single row: count_missings(spark_df, False) # | Col_A | Col_B | Col_C | # | 10 | 1 | 2 | A: I prefer this solution: df = spark.table(selected_table).filter(condition) counter = df.count() df = df.select([(counter - count(c)).alias(c) for c in df.columns]) A: Use the following code to identify the null values in every columns using pyspark. def check_nulls(dataframe): ''' Check null values and return the null values in pandas Dataframe INPUT: Spark Dataframe OUTPUT: Null values ''' # Create pandas dataframe nulls_check = pd.DataFrame(dataframe.select([count(when(isnull(c), c)).alias(c) for c in dataframe.columns]).collect(), columns = dataframe.columns).transpose() nulls_check.columns = ['Null Values'] return nulls_check #Check null values null_df = check_nulls(raw_df) null_df A: from pyspark.sql import DataFrame import pyspark.sql.functions as fn # compatiable with fn.isnan. Sourced from # https://github.com/apache/spark/blob/13fd272cd3/python/pyspark/sql/functions.py#L4818-L4836 NUMERIC_DTYPES = ( 'decimal', 'double', 'float', 'int', 'bigint', 'smallilnt', 'tinyint', ) def count_nulls(df: DataFrame) -> DataFrame: isnan_compat_cols = {c for (c, t) in df.dtypes if any(t.startswith(num_dtype) for num_dtype in NUMERIC_DTYPES)} return df.select( [fn.count(fn.when(fn.isnan(c) | fn.isnull(c), c)).alias(c) for c in isnan_compat_cols] + [fn.count(fn.when(fn.isnull(c), c)).alias(c) for c in set(df.columns) - isnan_compat_cols] ) Builds off of gench and user8183279's answers, but checks via only isnull for columns where isnan is not possible, rather than just ignoring them. The source code of pyspark.sql.functions seemed to have the only documentation I could really find enumerating these names — if others know of some public docs I'd be delighted. A: if you are writing spark sql, then the following will also work to find null value and count subsequently. spark.sql('select * from table where isNULL(column_value)') A: Yet another alternative (improved upon Vamsi Krishna's solutions above): def check_for_null_or_nan(df): null_or_nan = lambda x: isnan(x) | isnull(x) func = lambda x: df.filter(null_or_nan(x)).count() print(*[f'{i} has {func(i)} nans/nulls' for i in df.columns if func(i)!=0],sep='\n') check_for_null_or_nan(df) id2 has 5 nans/nulls A: Here is a readable solution because code is for people as much as computers ;-) df.selectExpr('sum(int(isnull(<col_name>) or isnan(<col_name>))) as null_or_nan_count'))
stackoverflow
{ "language": "en", "length": 724, "provenance": "stackexchange_0000F.jsonl.gz:892140", "question_score": "99", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627386" }
b5df1cadcd1333615238391879f29feba74aaff5
Stackoverflow Stackexchange Q: How can I access the dates from pandas dataframe? I would like to put the dates in a variable in order to pass them via django to charts.js. Now I have the problem, that I cannot access the dates, since they are apparently in the second row. print df['Open'] or print df['High'] works fpr example, but print df['Date'] doesn't work. Can you guys tell me how I can restructure the df in a way that I can print the dates as well? Thanks a lot for your help and kind regards. Dates are not accessable A: First column is called index, so for select need: print (df.index) dates = df.index Or add DataFrame.reset_index for new column from values of index: df = df.reset_index() dates = df['Date'] Sample: df = pd.DataFrame({'Open':[1,2,3], 'High':[8,9,2]}, index=pd.date_range('2015-01-01', periods=3)) df.index.name = 'Date' print (df) High Open Date 2015-01-01 8 1 2015-01-02 9 2 2015-01-03 2 3 print (df.index) DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03'], dtype='datetime64[ns]', name='Date', freq='D') df = df.reset_index() print (df['Date']) 0 2015-01-01 1 2015-01-02 2 2015-01-03 Name: Date, dtype: datetime64[ns] df.reset_index(inplace=True) print (df['Date']) 0 2015-01-01 1 2015-01-02 2 2015-01-03 Name: Date, dtype: datetime64[ns]
Q: How can I access the dates from pandas dataframe? I would like to put the dates in a variable in order to pass them via django to charts.js. Now I have the problem, that I cannot access the dates, since they are apparently in the second row. print df['Open'] or print df['High'] works fpr example, but print df['Date'] doesn't work. Can you guys tell me how I can restructure the df in a way that I can print the dates as well? Thanks a lot for your help and kind regards. Dates are not accessable A: First column is called index, so for select need: print (df.index) dates = df.index Or add DataFrame.reset_index for new column from values of index: df = df.reset_index() dates = df['Date'] Sample: df = pd.DataFrame({'Open':[1,2,3], 'High':[8,9,2]}, index=pd.date_range('2015-01-01', periods=3)) df.index.name = 'Date' print (df) High Open Date 2015-01-01 8 1 2015-01-02 9 2 2015-01-03 2 3 print (df.index) DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03'], dtype='datetime64[ns]', name='Date', freq='D') df = df.reset_index() print (df['Date']) 0 2015-01-01 1 2015-01-02 2 2015-01-03 Name: Date, dtype: datetime64[ns] df.reset_index(inplace=True) print (df['Date']) 0 2015-01-01 1 2015-01-02 2 2015-01-03 Name: Date, dtype: datetime64[ns]
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:892215", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627626" }
112b002a1581a2408bc758918ff2409a422535de
Stackoverflow Stackexchange Q: How to apply margins or css classes to Angular 2 component? Suppose I have a component that I want to apply some margins to, preferably via Bootstrap helper classes, e.g. mt-3 to apply top margin. When I specify them on the component like this: <my-custom-input required class="mt-3" name="usr" label="User" placeholder="Please enter username" [(ngModel)]="username"> </my-custom-input> the class="mt-3" does not do anything! Setting the margin manually via Chrome dev tools is not possible either... I'm guessing because my-custom-input is not a predefined HTML element (like div), it cannot have defined margins? This seems incredibly trivial thing to need in any application, but I'm surprised I was unable to find an answer thus far. How do we reposition such component? At the very least, specifying margins at the parent level (not inside components template) seems crucial thing to need?.. A: Give it a display: block; in your css : :host { display: block; }
Q: How to apply margins or css classes to Angular 2 component? Suppose I have a component that I want to apply some margins to, preferably via Bootstrap helper classes, e.g. mt-3 to apply top margin. When I specify them on the component like this: <my-custom-input required class="mt-3" name="usr" label="User" placeholder="Please enter username" [(ngModel)]="username"> </my-custom-input> the class="mt-3" does not do anything! Setting the margin manually via Chrome dev tools is not possible either... I'm guessing because my-custom-input is not a predefined HTML element (like div), it cannot have defined margins? This seems incredibly trivial thing to need in any application, but I'm surprised I was unable to find an answer thus far. How do we reposition such component? At the very least, specifying margins at the parent level (not inside components template) seems crucial thing to need?.. A: Give it a display: block; in your css : :host { display: block; }
stackoverflow
{ "language": "en", "length": 152, "provenance": "stackexchange_0000F.jsonl.gz:892218", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627640" }
681d81706c1a01702eb4f124721190d1cf9ed9cf
Stackoverflow Stackexchange Q: How to set splash timeout in scrapy-splash? I use scrapy-splash to crawl web page, and run splash service on docker. commond: docker run -p 8050:8050 scrapinghub/splash --max-timeout 3600 But I got a 504 error. "error": {"info": {"timeout": 30}, "description": "Timeout exceeded rendering page", "error": 504, "type": "GlobalTimeoutError"} Although I try to add splash.resource_timeout, request:set_timeout or SPLASH_URL = 'http://localhost:8050?timeout=1800.0', nothing changed. Thanks for help. A: I use scrapy-splash package and set the timeout in args parameter of SplashRequest like this: yield scrapy_splash.SplashRequest( url, self.parse, endpoint='execute', args={'lua_source': script, 'timeout': 3600}) It works for me.
Q: How to set splash timeout in scrapy-splash? I use scrapy-splash to crawl web page, and run splash service on docker. commond: docker run -p 8050:8050 scrapinghub/splash --max-timeout 3600 But I got a 504 error. "error": {"info": {"timeout": 30}, "description": "Timeout exceeded rendering page", "error": 504, "type": "GlobalTimeoutError"} Although I try to add splash.resource_timeout, request:set_timeout or SPLASH_URL = 'http://localhost:8050?timeout=1800.0', nothing changed. Thanks for help. A: I use scrapy-splash package and set the timeout in args parameter of SplashRequest like this: yield scrapy_splash.SplashRequest( url, self.parse, endpoint='execute', args={'lua_source': script, 'timeout': 3600}) It works for me.
stackoverflow
{ "language": "en", "length": 93, "provenance": "stackexchange_0000F.jsonl.gz:892235", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627694" }
233079a88437102a8ce2cc10b0c8e1802192cb19
Stackoverflow Stackexchange Q: Fine Grained Logging when using CocoaLumberJack in Swift I want to be able to open debug logging level for a specific file in my iOS application. We are using CocoaLumberJack in Swift as the logging framework. According to the documentation, this is possible in Objective C, but I could not find any documentation regarding Swift. Is it possible to do that? If so, how? Thanks, Omer A: Finally found out how to do that. I did that by creating another enum: public enum CustomLogFlags : UInt{ case test = 0b0100000 } And then set the log level: DDLog.logLevel = DDLogLevel(rawValue: DDLogLevel.error.rawValue | CustomLogFlags.test.rawValue) ?? DDLogLevel.error Now you can log messages using the new log level: let logLevel = DDLogFlag(rawValue: CustomLogFlags.test.rawValue) let logMsg = DDLogMessage(message: message(), level: logLevel, flag: flag, context: 0, file: file, function: function, line: line, tag: tag, options: DDLogMessageOptions(rawValue: 0), timestamp: nil) DDLog.log(logAsync, message: logMsg)
Q: Fine Grained Logging when using CocoaLumberJack in Swift I want to be able to open debug logging level for a specific file in my iOS application. We are using CocoaLumberJack in Swift as the logging framework. According to the documentation, this is possible in Objective C, but I could not find any documentation regarding Swift. Is it possible to do that? If so, how? Thanks, Omer A: Finally found out how to do that. I did that by creating another enum: public enum CustomLogFlags : UInt{ case test = 0b0100000 } And then set the log level: DDLog.logLevel = DDLogLevel(rawValue: DDLogLevel.error.rawValue | CustomLogFlags.test.rawValue) ?? DDLogLevel.error Now you can log messages using the new log level: let logLevel = DDLogFlag(rawValue: CustomLogFlags.test.rawValue) let logMsg = DDLogMessage(message: message(), level: logLevel, flag: flag, context: 0, file: file, function: function, line: line, tag: tag, options: DDLogMessageOptions(rawValue: 0), timestamp: nil) DDLog.log(logAsync, message: logMsg)
stackoverflow
{ "language": "en", "length": 148, "provenance": "stackexchange_0000F.jsonl.gz:892275", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627804" }
d670a84b17ece79cdbbb8d0d87f7669a9d3ac485
Stackoverflow Stackexchange Q: Setting conditional onClick behaviour in React Component I'm working on a component where a button (input field of type 'submit') will submitting data once clicked. However, I'd like to introduce a safeguard to show an alert on screen if the input field is blank. Thinking this would work the same way as it would for component attributes, I've tried variations on the following without much luck: onClick={props.inputText === '' ? alert("Text cannot be blank.") : (e => props.onSubmit(props.inputText))}/> I'd rather not run the check inside the onSubmit function in order to isolate updates to the store as far as possible (I'm following a React-Redux structure). Any idea if and how JSX handles a situation like this? A: You are assigning the value to onClick event, but onclick expect a function. To achieve that wrap all the logic inside a function body. Write it like this: onClick={ e => { props.inputText === '' ? alert("Text cannot be blank.") : props.onSubmit(props.inputText)} } /> Or onClick={this.onClick.bind(this)/> onClick(e){ if(props.inputText === ''){ alert("Text cannot be blank."); return; } props.onSubmit(props.inputText); }
Q: Setting conditional onClick behaviour in React Component I'm working on a component where a button (input field of type 'submit') will submitting data once clicked. However, I'd like to introduce a safeguard to show an alert on screen if the input field is blank. Thinking this would work the same way as it would for component attributes, I've tried variations on the following without much luck: onClick={props.inputText === '' ? alert("Text cannot be blank.") : (e => props.onSubmit(props.inputText))}/> I'd rather not run the check inside the onSubmit function in order to isolate updates to the store as far as possible (I'm following a React-Redux structure). Any idea if and how JSX handles a situation like this? A: You are assigning the value to onClick event, but onclick expect a function. To achieve that wrap all the logic inside a function body. Write it like this: onClick={ e => { props.inputText === '' ? alert("Text cannot be blank.") : props.onSubmit(props.inputText)} } /> Or onClick={this.onClick.bind(this)/> onClick(e){ if(props.inputText === ''){ alert("Text cannot be blank."); return; } props.onSubmit(props.inputText); } A: This should work: onClick={() => { props.inputText === '' ? alert("Text cannot be blank.") : props.onSubmit(props.inputText) }}
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:892286", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627838" }
1b2f716dbf749c4497cf9590ccfecdc47a274e87
Stackoverflow Stackexchange Q: Special annotations in RxJava When I use rxjava Android Studio automatically uses @io.reactivex.annotations.NonNull as annotation for methods. Is there any issue if I replace it with the @android.support.annotation.NonNull instead? I'm a bit afraid that I would lose some lint checks but I did not find anything about it A: There is no issue with replacing this annotation as it is just an hint for static analysis. In fact, by default Android Studio would not recognize RxJava2 @io.reactivex.annotations.NonNull as non null annotation and thus will not assert lint warnings. so if you keep using android default non null (@android.support.annotation.NonNull) you will be covered by lint. That also means that all RxJava2 library methods will not be considered with lint, unless you will change Android Studio settings. To sum it up, it doesn't really matter what non null annotation you're using as long as you add it to lint warnings (o.w. you miss the point with this annotations). to add RxJava2 annotation to Android Studio inspection, go to Inspection -> Constant conditions & Exception -> configure annotations, in Nullable/NotNull configuration add RxJava NonNull annotation:
Q: Special annotations in RxJava When I use rxjava Android Studio automatically uses @io.reactivex.annotations.NonNull as annotation for methods. Is there any issue if I replace it with the @android.support.annotation.NonNull instead? I'm a bit afraid that I would lose some lint checks but I did not find anything about it A: There is no issue with replacing this annotation as it is just an hint for static analysis. In fact, by default Android Studio would not recognize RxJava2 @io.reactivex.annotations.NonNull as non null annotation and thus will not assert lint warnings. so if you keep using android default non null (@android.support.annotation.NonNull) you will be covered by lint. That also means that all RxJava2 library methods will not be considered with lint, unless you will change Android Studio settings. To sum it up, it doesn't really matter what non null annotation you're using as long as you add it to lint warnings (o.w. you miss the point with this annotations). to add RxJava2 annotation to Android Studio inspection, go to Inspection -> Constant conditions & Exception -> configure annotations, in Nullable/NotNull configuration add RxJava NonNull annotation:
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:892295", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627862" }
78c5353109f3a2fe6fbb4dc296871aaa85f44a63
Stackoverflow Stackexchange Q: get List of reflect-metadata decorated fields of class I'm using reflect-metadata with typescript. I composed my own property decorator and it's called Field. How to get list of fields/properties, which are decorated by Field, of any type. For example: I want to get ProductID, ProductName field with their metadata from class Product/shown in below/. import 'reflect-metadata'; export const FIELD_METADATA_KEY = 'Field'; export interface FieldDecorator { field?: string; title?: string; type?: string; } export function Field(field: FieldDecorator) { return Reflect.metadata(FIELD_METADATA_KEY, field); } export class Product { @Field({ title: 'Product Id' }) ProductID: string; @Field({ title: 'Product Name', type: 'text' }) ProductName: string; UnitPrice: number; //not decorated } A: Unfortunately the reflect-metadata api does not expose this. As a workaround you can store the list of fields yourself: export const FIELD_METADATA_KEY = 'Field'; export const FIELD_LIST_METADATA_KEY = 'FieldList'; export function Field(field: FieldDecorator) { return (target: Object, propertyKey: string | symbol) => { // append propertyKey to field list metadata Reflect.defineMetadata(FIELD_LIST_METADATA_KEY, [...Reflect.getMetadata(FIELD_LIST_METADATA_KEY, target) ?? [], propertyKey], target); // your actual decorator Reflect.defineMetadata(FIELD_METADATA_KEY, field, target, propertyKey); }; } // list of keys Reflect.getMetadata(FIELD_LIST_METADATA_KEY, Product.prototype)
Q: get List of reflect-metadata decorated fields of class I'm using reflect-metadata with typescript. I composed my own property decorator and it's called Field. How to get list of fields/properties, which are decorated by Field, of any type. For example: I want to get ProductID, ProductName field with their metadata from class Product/shown in below/. import 'reflect-metadata'; export const FIELD_METADATA_KEY = 'Field'; export interface FieldDecorator { field?: string; title?: string; type?: string; } export function Field(field: FieldDecorator) { return Reflect.metadata(FIELD_METADATA_KEY, field); } export class Product { @Field({ title: 'Product Id' }) ProductID: string; @Field({ title: 'Product Name', type: 'text' }) ProductName: string; UnitPrice: number; //not decorated } A: Unfortunately the reflect-metadata api does not expose this. As a workaround you can store the list of fields yourself: export const FIELD_METADATA_KEY = 'Field'; export const FIELD_LIST_METADATA_KEY = 'FieldList'; export function Field(field: FieldDecorator) { return (target: Object, propertyKey: string | symbol) => { // append propertyKey to field list metadata Reflect.defineMetadata(FIELD_LIST_METADATA_KEY, [...Reflect.getMetadata(FIELD_LIST_METADATA_KEY, target) ?? [], propertyKey], target); // your actual decorator Reflect.defineMetadata(FIELD_METADATA_KEY, field, target, propertyKey); }; } // list of keys Reflect.getMetadata(FIELD_LIST_METADATA_KEY, Product.prototype)
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:892298", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627875" }
02fc16aa4e51dcae27b7010ffda500c69ba3734d
Stackoverflow Stackexchange Q: mac OS file system sandbox blocked open() I've run into dyld: could not load inserted library '/usr/local/lib/dgagent/libpreload.dylib' because no suitable image found. Did find: file system sandbox blocked open() of '/usr/local/lib/dgagent/libpreload.dylib' error with several applications - svnX (while trying to import directory, for example), SnailSVN (while trying to run Test during setup). Seems like this file system sandbox blocked open() therefore is not application specific but rather my Mac is missing some settings. Have anyone encountered the same issue and found the way around it? A: On 10.15 and later, folders like the Desktop, Documents etc. require "Files and Folders access" Two steps to setup the access: * *System Preferences > Security & Privacy > Privacy > Full Disk Access > "add your app such as svnX" *System Preferences > Security & Privacy > Privacy > Files and Folders > "add your app such as svnX"
Q: mac OS file system sandbox blocked open() I've run into dyld: could not load inserted library '/usr/local/lib/dgagent/libpreload.dylib' because no suitable image found. Did find: file system sandbox blocked open() of '/usr/local/lib/dgagent/libpreload.dylib' error with several applications - svnX (while trying to import directory, for example), SnailSVN (while trying to run Test during setup). Seems like this file system sandbox blocked open() therefore is not application specific but rather my Mac is missing some settings. Have anyone encountered the same issue and found the way around it? A: On 10.15 and later, folders like the Desktop, Documents etc. require "Files and Folders access" Two steps to setup the access: * *System Preferences > Security & Privacy > Privacy > Full Disk Access > "add your app such as svnX" *System Preferences > Security & Privacy > Privacy > Files and Folders > "add your app such as svnX" A: The comment from Richard Barber above saved my life. I also faced this issue (although with a different app and a different library) but essentially the same thing. Apple apps run is something called a Sandbox and hence cannot access a lot of locations. I tried adding the access to "Full Disk" and "Files and Folders" as specified in the above answer. I was able to add "Full Disk Access" but the "Files and Folder" thing was greyed out on my app in question (Microsoft Excel). So, that didn't work for me Finally what worked is taking the entire folder of the library in question (in my case a mysql odbc driver) and copying it over to /Applications/Microsoft Excel.app/Contents/Frameworks/ TL;DR : copy the library in question over to the Frameworks folder in the directory of that application and then the application should be able to access it A: This is a restriction commonly seen with Apple Gatekeeper on Hardened runtime. This has increased with MacOS catalina pushing for notarized applications.
stackoverflow
{ "language": "en", "length": 318, "provenance": "stackexchange_0000F.jsonl.gz:892328", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627957" }
eb747374d37e3c0796f1b1af1a964e0afce4ddcf
Stackoverflow Stackexchange Q: drop multiindex level but keep names of columns - pandas I have a df that looks like this a b c c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 I'd like to drop the c level but keep all the other column names a b c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 df.columns = df.columns.droplevel(0) works but the names of a and b disappear c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 A: I think you can use set_index + droplevel + reset_index: df = df.set_index(['a','b']) df.columns = df.columns.droplevel(0) df = df.reset_index() print (df) a b c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 Another solution with select columns by ['c']: df = df.set_index(['a','b'])['c'].reset_index() print (df) a b c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 But if get it from pivot_table solution is remove [] or add parameter values='c' if missing.
Q: drop multiindex level but keep names of columns - pandas I have a df that looks like this a b c c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 I'd like to drop the c level but keep all the other column names a b c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 df.columns = df.columns.droplevel(0) works but the names of a and b disappear c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 A: I think you can use set_index + droplevel + reset_index: df = df.set_index(['a','b']) df.columns = df.columns.droplevel(0) df = df.reset_index() print (df) a b c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 Another solution with select columns by ['c']: df = df.set_index(['a','b'])['c'].reset_index() print (df) a b c1 c2 0 87 33 32 34 1 32 10 45 62 2 78 83 99 71 But if get it from pivot_table solution is remove [] or add parameter values='c' if missing.
stackoverflow
{ "language": "en", "length": 189, "provenance": "stackexchange_0000F.jsonl.gz:892333", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44627970" }
e32de1d4dc82abb9526ab69b8320387078c82cf7
Stackoverflow Stackexchange Q: Duplicate identifier 'export=' I know this question was asked here before, but none of the solutions is working for me. I have the following tsconfig: { "compilerOptions": { "module": "commonjs", "target": "es6", "declaration": true, "outDir": "./dist" }, "typeRoots": ["./node_modules/@types/*"], "include": [ "./src/**/*" ] } but when I run tsc I get: ../node_modules/@types/passport/index.d.ts(100,5): error TS2300: Duplicate identifier 'export='. node_modules/@types/passport/index.d.ts(100,5): error TS2300: Duplicate identifier 'export='. How is it possible that I still get ../node_modules/@types/ (etc) when I specifically said only include the ./src folder and only types from ./node_modules/@types? I'm using typescript Version 2.4.0 (but have the same problem with version 2.3.4) A: What happens if you try the following tsconfig.json: { "compilerOptions": { "module": "commonjs", "target": "es6", "declaration": true, "rootDir": "src", "outDir": "dist", "skipLibCheck": true, "skipDefaultLibCheck": true } }
Q: Duplicate identifier 'export=' I know this question was asked here before, but none of the solutions is working for me. I have the following tsconfig: { "compilerOptions": { "module": "commonjs", "target": "es6", "declaration": true, "outDir": "./dist" }, "typeRoots": ["./node_modules/@types/*"], "include": [ "./src/**/*" ] } but when I run tsc I get: ../node_modules/@types/passport/index.d.ts(100,5): error TS2300: Duplicate identifier 'export='. node_modules/@types/passport/index.d.ts(100,5): error TS2300: Duplicate identifier 'export='. How is it possible that I still get ../node_modules/@types/ (etc) when I specifically said only include the ./src folder and only types from ./node_modules/@types? I'm using typescript Version 2.4.0 (but have the same problem with version 2.3.4) A: What happens if you try the following tsconfig.json: { "compilerOptions": { "module": "commonjs", "target": "es6", "declaration": true, "rootDir": "src", "outDir": "dist", "skipLibCheck": true, "skipDefaultLibCheck": true } }
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:892355", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628035" }
1c1a0d427ac6a192b9b94f08fd5b2204e0fa2f20
Stackoverflow Stackexchange Q: convert Python list to ordered unique values I encounter many tasks in which I need to filter python (2.7) list to keep only ordered unique values. My usual approach is by using odereddict from collections: from collections import OrderedDict ls = [1,2,3,4,1,23,4,12,3,41] ls = OrderedDict(zip(ls,['']*len(ls))).keys() print ls the output is: [1, 2, 3, 4, 23, 12, 41] is there any other state of the art method to do it in Python? * *Note - the input and the output should be given as list edit - a comparison of the methods can be found here: https://www.peterbe.com/plog/uniqifiers-benchmark the best solution meanwhile is: def get_unique(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] A: You could use a set like this: newls = [] seen = set() for elem in ls: if not elem in seen: newls.append(elem) seen.add(elem)
Q: convert Python list to ordered unique values I encounter many tasks in which I need to filter python (2.7) list to keep only ordered unique values. My usual approach is by using odereddict from collections: from collections import OrderedDict ls = [1,2,3,4,1,23,4,12,3,41] ls = OrderedDict(zip(ls,['']*len(ls))).keys() print ls the output is: [1, 2, 3, 4, 23, 12, 41] is there any other state of the art method to do it in Python? * *Note - the input and the output should be given as list edit - a comparison of the methods can be found here: https://www.peterbe.com/plog/uniqifiers-benchmark the best solution meanwhile is: def get_unique(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] A: You could use a set like this: newls = [] seen = set() for elem in ls: if not elem in seen: newls.append(elem) seen.add(elem) A: If you need to preserve the order and get rid of the duplicates, you can do it like: ls = [1, 2, 3, 4, 1, 23, 4, 12, 3, 41] lookup = set() # a temporary lookup set ls = [x for x in ls if x not in lookup and lookup.add(x) is None] # [1, 2, 3, 4, 23, 12, 41] This should be considerably faster than your approach. A: Define a function to do so: def uniques(l): retl = [] for x in l: if x not in retl: retl.append(x) return retl ls = [1,2,3,4,1,23,4,12,3,41] uniques(ls) [1, 2, 3, 4, 23, 12, 41] A: Another solution would be using list comprehension like this: [x for i, x in enumerate(ls) if x not in ls[:i]] Output: [1, 2, 3, 4, 23, 12, 41]
stackoverflow
{ "language": "en", "length": 283, "provenance": "stackexchange_0000F.jsonl.gz:892407", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628186" }
da56f3997ee076a86ec7441be290356b75e5f9a2
Stackoverflow Stackexchange Q: How to load and export variables from an .env file in Makefile? What is the best way to use a .env in a Makefile, i.e. loading that file and exporting all variables for subshells in make? It would be great if the proposed solution would work with make only, e.g. not using any third party tools. Also .env files support multiline variables like: FOO="this\nis\na\nmultiline\nvar" this is why this solution is probably not adequate. A: You can load specific .env file for each target by creating a function and target to use it with other targets when necessary. Here as an sample: define setup_env $(eval ENV_FILE := $(1).env) @echo " - setup env $(ENV_FILE)" $(eval include $(1).env) $(eval export) endef devEnv: $(call setup_env, dev) prodEnv: $(call setup_env, prod) clean: rm -rf bin/ build: clean GOOS=linux GOARCH=amd64 go build -o bin/ ./cmd/... dev: build devEnv cd cmd/api && ./../../bin/api migrate-dev-db: devEnv sh +x database/migration/migrate.sh dev migrate-prod-db: prodEnv sh +x database/migration/migrate.sh deploy: prodEnv sh +x script/deployment/production/ec2-deploy.sh
Q: How to load and export variables from an .env file in Makefile? What is the best way to use a .env in a Makefile, i.e. loading that file and exporting all variables for subshells in make? It would be great if the proposed solution would work with make only, e.g. not using any third party tools. Also .env files support multiline variables like: FOO="this\nis\na\nmultiline\nvar" this is why this solution is probably not adequate. A: You can load specific .env file for each target by creating a function and target to use it with other targets when necessary. Here as an sample: define setup_env $(eval ENV_FILE := $(1).env) @echo " - setup env $(ENV_FILE)" $(eval include $(1).env) $(eval export) endef devEnv: $(call setup_env, dev) prodEnv: $(call setup_env, prod) clean: rm -rf bin/ build: clean GOOS=linux GOARCH=amd64 go build -o bin/ ./cmd/... dev: build devEnv cd cmd/api && ./../../bin/api migrate-dev-db: devEnv sh +x database/migration/migrate.sh dev migrate-prod-db: prodEnv sh +x database/migration/migrate.sh deploy: prodEnv sh +x script/deployment/production/ec2-deploy.sh A: Make does not offer any way to read a content of the file to some variable. So, I consider it impossible to achieve the result without using external tools. However, if I am wrong, I'd be glad to learn some new trick. So, let's assume there are two files, .env, being a technically correct shell file: FOO=bar BAR="notfoo" # comment #comment MULTILINE="This\nis\nSparta!" # comment and script.sh: #!/bin/bash echo FOO=${FOO} echo BAR=${BAR} echo -e ${MULTILINE} One solution is to include the .env file, then make sure variables are exported: include .env $(eval export $(shell sed -ne 's/ *#.*$$//; /./ s/=.*$$// p' .env)) all: ./script.sh Because of different treatment of quotes by shell and make, you will see the quotes in output. You can avoid that by reprocessing the variables by make: include .env VARS:=$(shell sed -ne 's/ *\#.*$$//; /./ s/=.*$$// p' .env ) $(foreach v,$(VARS),$(eval $(shell echo export $(v)="$($(v))"))) all: ./script.sh but then the multiline variable will become a one-liner. Finally, you can generate a temporary file to be processed by bash and source it before any command is run: SHELL=bash all: .env-export . .env-export && ./script.sh .env-export: .env sed -ne '/^export / {p;d}; /.*=/ s/^/export / p' .env > .env-export Oh, new lines got messed in this case in multiline variable. You need to additionally quote them. Finally, you can add export to .env using above sed command, and do: SHELL=bash %: .env-export . .env-export && make -f secondary "$@" A: Found this and it worked great: at top of makefile ifneq (,$(wildcard ./.env)) include .env export endif Then you have make variables for all your env, for example MY_VAR use as $(MY_VAR)
stackoverflow
{ "language": "en", "length": 438, "provenance": "stackexchange_0000F.jsonl.gz:892411", "question_score": "26", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628206" }
ed2f37012fc54191a1f2923be864d486840ec100
Stackoverflow Stackexchange Q: Android Virtual Device/ Android Emulator - Decryption Unsuccessful I just installed Android Studio, and I am very new with this program. So when I run the Android Emulator it says: "To Start Android, enter your password", although I have never set a password. When I just enter a word with 4 letters it says "The Password you entered is correct, but unfortunately your data is corrupt". After that, I have to Reset the Phone, but when I do that the same menu with "To Start Android, enter your password" appears. Maybe it is just an easy mistake, but as I said I am new with this. I also did some research on the internet but I did not find anything useful. this is the 2 images that it showe me: 1) 2) and after i clicked on reset phone, nothing happened. I would be very glad if someone has an answer for this. A: open AVD and right click on the emulator choose ->Wipe data option.
Q: Android Virtual Device/ Android Emulator - Decryption Unsuccessful I just installed Android Studio, and I am very new with this program. So when I run the Android Emulator it says: "To Start Android, enter your password", although I have never set a password. When I just enter a word with 4 letters it says "The Password you entered is correct, but unfortunately your data is corrupt". After that, I have to Reset the Phone, but when I do that the same menu with "To Start Android, enter your password" appears. Maybe it is just an easy mistake, but as I said I am new with this. I also did some research on the internet but I did not find anything useful. this is the 2 images that it showe me: 1) 2) and after i clicked on reset phone, nothing happened. I would be very glad if someone has an answer for this. A: open AVD and right click on the emulator choose ->Wipe data option. A: Check that your avd folder path doesn't include national symbols (in my case it looked like C:\Users\Пользователь\.android). After I changed this path everything is working. See this post of how to change path: Possible to change where Android Virtual Devices are saved? A: This is a late response, but thought this simple fix might help anyone else who comes across this problem in the future. What worked for me is the following: In VS2017 ==> Tools ==> Android ==> Select: Android Device Manager In the Android Device Manager window, you'll see your Android Emulator. * *Make sure the far right column contains the button "Start" (if "Stop" appears, click "Stop") *Right Click the device, and select the "Factory Reset" option in the menu. Your emulator should now be working. Good luck. A: Check out "Viewing and managing your Avds" part. Try wiping data of your emulator or create a new emulator for yourself. https://developer.android.com/studio/run/managing-avds.html A: enable GoogleAPIs and Google Play Store A: Change the Android version. I was creating an emulator with Oreo 8.1 and got stuck in with the same issue. I created another with Marshmallows 6.0 and no more asking for password. Then if you are using Oreo 8.1 try with antoher. A: I created a virtual device, and after, I had to reinstall the emulator. When I booted the virtual device, I got this issue. I deleted it and made a new one, and it worked fine. A: Just go the AVD Manager and Wipe Data. The problem will be solved. A: Here are the steps I followed after my device corrupted. * *Close your emulator *Open AVD manager, right click on your device and click "Cold Boot Now" button. A: Sorry for a very Late Answer. But you can't create a x64 Virtual Device on x64 System. Your device needs to be x86. A: Just a warning to anyone getting this error on an emulator instance that was working and you cold booted or something. I got this error and just stopped and cold booted again and it was gone! So try that first before wiping your emulator instance unnecessarily. A: Deleted the device in the Device Manager and created a new one with a higher OS version (Oreo -> Pie). The error disappeared. Did not find the real reason yet.
stackoverflow
{ "language": "en", "length": 553, "provenance": "stackexchange_0000F.jsonl.gz:892458", "question_score": "34", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628366" }
bd2a4dc7706af563fe403929b1ceb52a0b4c3ff5
Stackoverflow Stackexchange Q: Shortcut for function parameter tooltip In Swift, when I start using some function, I get a tooltip with description of parameters. But when I start typing, it disappears and I have no idea how to call it after that. What is the shortcut to call this function parameter tool tip again? A few image on what I want. When I, for example, create UIAlertController and press (, XCode will show this Now, if you select and ENTER function, it will autocomplete parameters names and let you input values. But if you start typing the 1st parameter name and value, then add comma, XCode will not show this tooltip to help you know the name of the next parameter And in this case I would like to know the shortcut to call the tooltip with the name of the next parameter. If I hit escape, it does not help as well. I even navigated to the exact param name, but XCode did not recognize it. PS. This is the same command as CTRL + P in Android Studio.
Q: Shortcut for function parameter tooltip In Swift, when I start using some function, I get a tooltip with description of parameters. But when I start typing, it disappears and I have no idea how to call it after that. What is the shortcut to call this function parameter tool tip again? A few image on what I want. When I, for example, create UIAlertController and press (, XCode will show this Now, if you select and ENTER function, it will autocomplete parameters names and let you input values. But if you start typing the 1st parameter name and value, then add comma, XCode will not show this tooltip to help you know the name of the next parameter And in this case I would like to know the shortcut to call the tooltip with the name of the next parameter. If I hit escape, it does not help as well. I even navigated to the exact param name, but XCode did not recognize it. PS. This is the same command as CTRL + P in Android Studio.
stackoverflow
{ "language": "en", "length": 178, "provenance": "stackexchange_0000F.jsonl.gz:892468", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628395" }
beeff286130a7123b16a24a0c0b8df0b6172bcf1
Stackoverflow Stackexchange Q: How to return to previous page with parameters? I want to return to previous page with some parameters. Any suggestion how can i do that? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } So what i want is something like this : this._location.back(id:123); And when i back on page to have something like this : www.test.com?d=123 A: Here if you are using the this._location.back() to go back you can pass only the index to this function. How much index you want to go back from browser history. For Example to go 2 index back this._location.back(2); Example to go back with queryParams this.router.navigate(['/test2', { id: 12321313}]); Check for angular 2 declaration function location.back() inside @angular\common.js class Location { /* Navigates back in the platform's history.*/ /* @return {?} */ back() { this._platformStrategy.back(); } } InShort the thing what you are trying this._location.back(2) work same as window.history.back(); and accept only the index value you want to go back from browser history
Q: How to return to previous page with parameters? I want to return to previous page with some parameters. Any suggestion how can i do that? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } So what i want is something like this : this._location.back(id:123); And when i back on page to have something like this : www.test.com?d=123 A: Here if you are using the this._location.back() to go back you can pass only the index to this function. How much index you want to go back from browser history. For Example to go 2 index back this._location.back(2); Example to go back with queryParams this.router.navigate(['/test2', { id: 12321313}]); Check for angular 2 declaration function location.back() inside @angular\common.js class Location { /* Navigates back in the platform's history.*/ /* @return {?} */ back() { this._platformStrategy.back(); } } InShort the thing what you are trying this._location.back(2) work same as window.history.back(); and accept only the index value you want to go back from browser history
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:892480", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628417" }
df45c902d2d2d3f608c506191b403885a82915ab
Stackoverflow Stackexchange Q: How Kotlin objects & companion objects & lazy works with memory I couldn't find anywhere about how objects, companion objects and lazy works with memory. Can anyone here explain me how they work with memory? Thanks A: It's a quite vague question and can be answered by looking into bytecode. Object declaration Object declaration is a singleton. It has a static field called INSTANCE which gets initialized in static block (<clinit>). Companion object Companion is a kind of inner class, but is a singleton and behaves like object declaration. Lazy delegate Lazy delegate (every delegate) is a separate object. Each time you create a lazy field, a delegate object gets instantiated.
Q: How Kotlin objects & companion objects & lazy works with memory I couldn't find anywhere about how objects, companion objects and lazy works with memory. Can anyone here explain me how they work with memory? Thanks A: It's a quite vague question and can be answered by looking into bytecode. Object declaration Object declaration is a singleton. It has a static field called INSTANCE which gets initialized in static block (<clinit>). Companion object Companion is a kind of inner class, but is a singleton and behaves like object declaration. Lazy delegate Lazy delegate (every delegate) is a separate object. Each time you create a lazy field, a delegate object gets instantiated.
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:892497", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628461" }
f4dc5874e6662ff510fd6404a30288205e393d3d
Stackoverflow Stackexchange Q: Assume vs assert in JUnit tests I have read that assume will not run the test if assumption failed, but I am not sure regarding the logic of when to place assert vs assume. For example: any resource loading check should be done with assume? When should I use assume over assert? (Note: i am looking for correct design of when to use one over the other) A: The most easiest difference between Assert and Assume is : Assume will only run when the assumption is true. Will be skipped if it false. assumeTrue(boolean assumption, String message) Assert will run normally if true. In case of false assert, it gives predefined error message. assertTrue(boolean condition, String message)
Q: Assume vs assert in JUnit tests I have read that assume will not run the test if assumption failed, but I am not sure regarding the logic of when to place assert vs assume. For example: any resource loading check should be done with assume? When should I use assume over assert? (Note: i am looking for correct design of when to use one over the other) A: The most easiest difference between Assert and Assume is : Assume will only run when the assumption is true. Will be skipped if it false. assumeTrue(boolean assumption, String message) Assert will run normally if true. In case of false assert, it gives predefined error message. assertTrue(boolean condition, String message) A: You would use assume if you have circumstances under which some tests should not run at all. "Not run" means that it cannot fail, because, well, it did not run. You would use assert to fail a test if something goes wrong. So, in a hypothetical scenario where: * *you have different builds for different customers, and *you have some resource which is only applicable to a particular client, and *there is something testable about that resource, then you would write a test which: * *assumes that the resource is present, (so the test will not run on customers that do not have that resource,) and then *asserts that everything about the resource is okay (so on the customer that does actually have the resource, the test makes sure that the resource is as it should be.) A: Simply check out the javadoc for Assume: A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information. In other words: when an assert fires, you know that your testcase failed. Your production code isn't doing what you expect it to do. Assume means ... you don't know exactly what happened. A: The Assert class is the workhorse of JUnit and is the class JUnit testers are most familiar with. Most JUnit assert signatures are similar in nature. They consist of an optional message, an expected instance or variable and the actual instance or variable to be compared. Or, in the case of a boolean test like True, False, or Null, there is simply the actual instance to be tested. The signature with a message simply has an initial parameter with a message string that will be displayed in the event the assert fails: assert<something>(“Failure Message String”, <condition to be tested>); Assumptions: You’ve probably heard that it’s best not to work on assumptions so here is a testing tool JUnit gives you to ensure your tests don’t. Both Asserts and Assumes stop when a test fails and move on to the next test. The difference is that a failed Assert registers the failure as a failed test while an Assume just moves to the next test. This permits a tester to ensure that conditions, some of which may be external and out of control of the tester, are present as required before a test is run. There are four varieties of Assumes: one to check a boolean condition, one to check that an exception has not occurred, one to check for null objects, and one that can take a Hamcrest matcher. As seen in the Assert section above, the ability to take a Hamcrest matcher is a gateway to testing flexibility. You can read more here https://objectcomputing.com/resources/publications/sett/march-2014-junit-not-just-another-pretty-assert/ In short Assume used to disable tests, for example the following disables a test on Linux: Assume.assumeFalse(System.getProperty("os.name").contains("Linux")); Assert is used to test the functionality.
stackoverflow
{ "language": "en", "length": 612, "provenance": "stackexchange_0000F.jsonl.gz:892505", "question_score": "32", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628483" }
73b1f9c57a424da8d8a99c33c7646010d876034f
Stackoverflow Stackexchange Q: Is there a way to debug Tomcat Java application from Visual Studio Code I am relatively new to Java but need to do some changes to Java code. I prefer using Visual Studio Code for this. The Java code builds to .WAR file using Maven and is deployed to Tomcat. Is there any way to debug this app directly from Visual Studio Code? A: Visual Studio Code has a lot of tools to do this in marketplace. For Tomcat you can use this: https://marketplace.visualstudio.com/items?itemName=adashen.vscode-tomcat You can do all this things: * *Add Tomcat Server from Tomcat Install Path *Start/Restart Tomcat Server from VSCode *Run war package on Tomcat Server *Debug war package on Tomcat Server *Run exploded war on Tomcat Server *Debug exploded war on Tomcat Server *Open server homepage in browser to check all deployed war packages *View all deployed war packages in Tomcat Explorer *Open war package homepage in browser *Stop Tomcat Server *Rename Tomcat Server *Customize JVM Options when starting Tomcat Server *Reveal deployed war packages in file explorer *Delete deployed war package You need the debugger posted by Mert Mertce tho.
Q: Is there a way to debug Tomcat Java application from Visual Studio Code I am relatively new to Java but need to do some changes to Java code. I prefer using Visual Studio Code for this. The Java code builds to .WAR file using Maven and is deployed to Tomcat. Is there any way to debug this app directly from Visual Studio Code? A: Visual Studio Code has a lot of tools to do this in marketplace. For Tomcat you can use this: https://marketplace.visualstudio.com/items?itemName=adashen.vscode-tomcat You can do all this things: * *Add Tomcat Server from Tomcat Install Path *Start/Restart Tomcat Server from VSCode *Run war package on Tomcat Server *Debug war package on Tomcat Server *Run exploded war on Tomcat Server *Debug exploded war on Tomcat Server *Open server homepage in browser to check all deployed war packages *View all deployed war packages in Tomcat Explorer *Open war package homepage in browser *Stop Tomcat Server *Rename Tomcat Server *Customize JVM Options when starting Tomcat Server *Reveal deployed war packages in file explorer *Delete deployed war package You need the debugger posted by Mert Mertce tho.
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:892529", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628572" }
192e2a6a9364f8b4ceed2e7aec9a0d7c98ff6943
Stackoverflow Stackexchange Q: How to download a file from a URL which redirects? I need to download a file using url-->https://readthedocs.org/projects/django/downloads/pdf/latest/ This url redirects to a url with a .pdf file. How can I download that file with this url using python ? I've tried :- import urllib def download_file(download_url): web_file = urllib.urlopen(download_url) local_file = open('some_file.pdf', 'w') local_file.write(web_file.read()) web_file.close() local_file.close() if __name__ == 'main': download_file('https://readthedocs.org/projects/django/downloads/pdf/latest/') but this is not working A: import requests url = 'https://readthedocs.org/projects/django/downloads/pdf/latest/' r = requests.get(url, allow_redirects=True) # to get content after redirection pdf_url = r.url # 'https://media.readthedocs.org/pdf/django/latest/django.pdf' with open('file_name.pdf', 'wb') as f: f.write(r.content) If you want to download the file from other method or you want to get only final redirected URL you can use requests.head() as shown below: r = requests.head(url, allow_redirects=True) # to get only final redirect url
Q: How to download a file from a URL which redirects? I need to download a file using url-->https://readthedocs.org/projects/django/downloads/pdf/latest/ This url redirects to a url with a .pdf file. How can I download that file with this url using python ? I've tried :- import urllib def download_file(download_url): web_file = urllib.urlopen(download_url) local_file = open('some_file.pdf', 'w') local_file.write(web_file.read()) web_file.close() local_file.close() if __name__ == 'main': download_file('https://readthedocs.org/projects/django/downloads/pdf/latest/') but this is not working A: import requests url = 'https://readthedocs.org/projects/django/downloads/pdf/latest/' r = requests.get(url, allow_redirects=True) # to get content after redirection pdf_url = r.url # 'https://media.readthedocs.org/pdf/django/latest/django.pdf' with open('file_name.pdf', 'wb') as f: f.write(r.content) If you want to download the file from other method or you want to get only final redirected URL you can use requests.head() as shown below: r = requests.head(url, allow_redirects=True) # to get only final redirect url
stackoverflow
{ "language": "en", "length": 132, "provenance": "stackexchange_0000F.jsonl.gz:892560", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628699" }
93106fa44d164f2eb832a3fee8cace0a8c63bb55
Stackoverflow Stackexchange Q: Two columns ListView with items of varying heights I want to create a two columns listView with items of varying heights like that: image I have try this custom class found on GitHub and it was perfect but I have different problems because maybe the class is old (last update: 2014): * *Child Item's images with onClickListener block the custom listView's scrolling *SwipeRefreshLayout appear always when scroll up (I want only when I am at the top of the list) [Edit] Solution: Proposed by Piyush: StaggeredGridLayoutManager with RecyclerView A: you can use StaggeredGridLayoutManager you can use StaggeredGridLayoutManager private StaggeredGridLayoutManager gaggeredGridLayoutManager; gaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1); recyclerView.setLayoutManager(gaggeredGridLayoutManager); for more information follow this link StaggeredGridLayoutManager
Q: Two columns ListView with items of varying heights I want to create a two columns listView with items of varying heights like that: image I have try this custom class found on GitHub and it was perfect but I have different problems because maybe the class is old (last update: 2014): * *Child Item's images with onClickListener block the custom listView's scrolling *SwipeRefreshLayout appear always when scroll up (I want only when I am at the top of the list) [Edit] Solution: Proposed by Piyush: StaggeredGridLayoutManager with RecyclerView A: you can use StaggeredGridLayoutManager you can use StaggeredGridLayoutManager private StaggeredGridLayoutManager gaggeredGridLayoutManager; gaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1); recyclerView.setLayoutManager(gaggeredGridLayoutManager); for more information follow this link StaggeredGridLayoutManager A: Why don't you use a ScrollView instead? So you'll have a parent ScrollView containing just one RelativeLayout. Then you'll place two vertical LinearLayout inside the Relative one in which you are going to place your varying heights cells. Pseudo-code follows: <ScrollView> <RelativeLayout> <LinearLayout orientation="vertical"> //insert you items here via GroupView.addView inside your activity </LinearLayout> <LinearLayout orientation="vertical"> </LinearLayout> </RelativeLayout> <ScrollView>
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:892592", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628783" }
78eda021981cb704da4cc6ce2dd3c1251bd2c504
Stackoverflow Stackexchange Q: C# Split Regex: Capture a group when follow by characters I have a string: LRS00969 I want to split on 0s, but only if the group is preceded by non-number. I also want to preserve 0s in the returned array. So far I've got to this: [A-Z](0{1,}) However, when I split using Regex in ASP.NET, it returns string[] { "LRS969" }. I would like it to return string[] { "LRS", "00", "969" }. If I use (0{1,}) instead, it splits correctly, but of course it will match strings where 0s follow other numbers as well ( such as LRS100969 ) Any ideas? A: You may use (?<=[^0-9])(0+) See the regex demo Details: * *(?<=[^0-9]) - a positive lookbehind that requires a character other than a digit immediately to the left of the current location *(0+) - matches and captures into Group 1 (so that Regex.Split could paste this value into the resulting array) one or more 0 characters.
Q: C# Split Regex: Capture a group when follow by characters I have a string: LRS00969 I want to split on 0s, but only if the group is preceded by non-number. I also want to preserve 0s in the returned array. So far I've got to this: [A-Z](0{1,}) However, when I split using Regex in ASP.NET, it returns string[] { "LRS969" }. I would like it to return string[] { "LRS", "00", "969" }. If I use (0{1,}) instead, it splits correctly, but of course it will match strings where 0s follow other numbers as well ( such as LRS100969 ) Any ideas? A: You may use (?<=[^0-9])(0+) See the regex demo Details: * *(?<=[^0-9]) - a positive lookbehind that requires a character other than a digit immediately to the left of the current location *(0+) - matches and captures into Group 1 (so that Regex.Split could paste this value into the resulting array) one or more 0 characters. A: An alternative that works in other environments as well would be (?<!\d)(?=0)|(?<=0)(?!0) matching the boundary between a "non-number" and a 0, or, the boundary after last 0 in a sequence (that could be only one long). Since it's only look-arounds, no actual characters are matched, and thus it works without the "re-insert-delimiter" feature ;) See it here at REGEXSTORM.net and here at regex101.
stackoverflow
{ "language": "en", "length": 223, "provenance": "stackexchange_0000F.jsonl.gz:892625", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628898" }
8d6fe5198fe64fdfa88aa573a77cee45a6068b27
Stackoverflow Stackexchange Q: What is default css display value for react web application? I was passing upwork test for react.js and I have got this question, I realy don't know, and google/react documentation don't help me. Can anyone know? it is very interesting to me) A: A React application is not an element. It doesn't have a default value for any CSS property.
Q: What is default css display value for react web application? I was passing upwork test for react.js and I have got this question, I realy don't know, and google/react documentation don't help me. Can anyone know? it is very interesting to me) A: A React application is not an element. It doesn't have a default value for any CSS property. A: React usually renders into a DOM element you specify, and css defaults will be taken from that dom node. E.g. in this example, element's css will follow the css of the dom node with id root. const element = <h1>Hello, world</h1>; ReactDOM.render( element, document.getElementById('root') ) A: I think the right answer is browser dependent. It can't be inherit. See my jsbin example. I set display: inline-block on #root. And after rendering h1 only has browser default value display: block.
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:892635", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628928" }
6c1189699fadebd0cc85d69b72766f2516ad0d8a
Stackoverflow Stackexchange Q: Filtering numbers out from an array I have an array like below and need to filter out the numbers from it ex: [1,2] var str = [ "https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg" ] I have the below code : var filtered = str.filter(function(item) { return (typeof item === "number") }); but it is not filtering as it is a string. How to do it? A: Use isNaN(). var str=["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2","/static.jpg"]; var filtered = str.filter(function(item) { return (!isNaN(item)); }); console.log(filtered);
Q: Filtering numbers out from an array I have an array like below and need to filter out the numbers from it ex: [1,2] var str = [ "https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg" ] I have the below code : var filtered = str.filter(function(item) { return (typeof item === "number") }); but it is not filtering as it is a string. How to do it? A: Use isNaN(). var str=["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2","/static.jpg"]; var filtered = str.filter(function(item) { return (!isNaN(item)); }); console.log(filtered); A: var str = ["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2", "/static.jpg" ] str.filter(item=>!isNaN(parseInt(item))) parseInt convert number to integer and other values converted to "NaN", isNaN function validate value is either "NaN" or not https://www.w3schools.com/jsref/jsref_isnan.asp https://www.w3schools.com/jsref/jsref_parseint.asp A: I think this is the most precise way to filter out numbers from an array. str.filter(Number); If the array contains a number in the form of string, then the resulting array will have the number in the form of string. In your case, the resulting array will be ["1", "2"]. If the original array contains 0 or "0", then they will not be present in the resulting array. If resulting array should include only integer numbers, str.filter(Number.isInteger) This will exclude the number in the form of string like "1", "2", etc. For both integer and float numbers, str.filter(Number.isFinite) A: Making a small change to your code to make it work, this might possibly work. var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"]; var filtered = str.filter(function (item) { return !(parseInt(item) == item); }); console.log(filtered); Or if you want the numbers: var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"]; var filtered = str.filter(function (item) { return (parseInt(item) == item); }); console.log(filtered); A: You could use a regular expression which test a string, if it contains only digits. var array = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"]; array = array.filter(function (a) { return !/^\d+$/.test(a); }); console.log(array); A: If you want to check if a string only contains numeric digits, you can use regular expressions. var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"]; var filtered = str.filter(function (item) { return item.match(/^-?\d+$/); }); console.log(filtered); A: const intArray = []; const strArray = []; const rest_test_parameters = (...args) => { args.filter((item) => { if (parseInt(item)) { return intArray.push(parseInt(item)); } strArray.push(item); }); }; const objects = { a: "a", b: "c" }; rest_test_parameters(1, 2, "99","hello", objects); console.log("intArray", intArray); console.log("strArray",strArray); A: You usage func helper in filter function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n);} A: str = str.filter(function(item) { return (item !== 0) && ((!item) || (isNaN(item))); }); The right side of the operation calls filter and passes a function which returns true if an item is not 0 and it is either falsey or not a number; otherwise it returns false. For instance "" or null should be kept in the array as far as the specification goes. With this approach we get the desired array and we assign it to the str variable. A: const filterNumbers = [123456789, 'limit', 'elite', 987654321, 'destruction', 'present']; const result = filterNumbers.filter(number => parseInt(number) == number); console.log(result); Here's similar code that returns the number instead of the string. The => is just alternative syntax for function and return (see arrow function expressions), but will yield the same result. A: Most of the above answers are good, but missing one thing; filtering out array of numbers(neither integer, nor string form of numbers). I haved added the snippet to address those little issues. var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2.4", "/static.jpg","4"]; var filteredNumbers = str.filter(item=> parseFloat(item) == item).map(item=>parseFloat(item)); console.log(filteredNumbers); A: Here's a one liner: arr.filter(n => (parseInt(n)===0 || +n)).map(Number) This is assuming it is a flat array and not a nested one.
stackoverflow
{ "language": "en", "length": 605, "provenance": "stackexchange_0000F.jsonl.gz:892647", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44628965" }
d04dc99915b917d8ce6739f430cd71f5bef1a36e
Stackoverflow Stackexchange Q: Convert reference to item to slice of length 1 I have a &X. How can I convert this to a &[X] of length 1? std::slice::from_raw_parts should work, but it is unsafe. Is there a safe function that I can use to do this conversion?
Q: Convert reference to item to slice of length 1 I have a &X. How can I convert this to a &[X] of length 1? std::slice::from_raw_parts should work, but it is unsafe. Is there a safe function that I can use to do this conversion?
stackoverflow
{ "language": "en", "length": 45, "provenance": "stackexchange_0000F.jsonl.gz:892665", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629021" }
219c7c035f11a319f7ba227a12a181cf80d88b51
Stackoverflow Stackexchange Q: error.CannotStartupOSGIPlatform issue when running birt I'm in the midst of implementing Birt 4.6.0 into my gwt application. Unfortunately whenever I run a specific section of the program, I get the following error: org.eclipse.birt.core.exception.BirtException: error.CannotStartupOSGIPlatform at org.eclipse.birt.core.framework.Platform.startup(Platform.java:81) I've done some searching and one thread mentioned a permissions error but I am not sure what that entails. What does this mean? EDIT Just read another article that suggests that it may be an issue with my classpath but I already added all the jar files from ReportEngine/lib to my buildpath. Anyone know what jar files I am supposed to include? the offending code: public static synchronized IReportEngine getBirtEngine(ServletContext sc) { if (birtEngine == null) { EngineConfig config = new EngineConfig(); java.util.HashMap map = config.getAppContext();; map.put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, SegnalazioniDbManager.class.getClassLoader()); config.setAppContext(map); IPlatformContext context = new PlatformServletContext(sc); config.setPlatformContext(context); try { Platform.startup(config); //problem begins here ..... } [1]: http://developer.actuate.com/community/forum/index.php?/topic/20933-errorcannotstartuposgiplatform/ A: Yes it is indeed a permission error. The relevant file is: WEB-INF/platform/configuration/org.eclipse.osgi/.manager/.fileTableLock You need to give access to the Birt user.
Q: error.CannotStartupOSGIPlatform issue when running birt I'm in the midst of implementing Birt 4.6.0 into my gwt application. Unfortunately whenever I run a specific section of the program, I get the following error: org.eclipse.birt.core.exception.BirtException: error.CannotStartupOSGIPlatform at org.eclipse.birt.core.framework.Platform.startup(Platform.java:81) I've done some searching and one thread mentioned a permissions error but I am not sure what that entails. What does this mean? EDIT Just read another article that suggests that it may be an issue with my classpath but I already added all the jar files from ReportEngine/lib to my buildpath. Anyone know what jar files I am supposed to include? the offending code: public static synchronized IReportEngine getBirtEngine(ServletContext sc) { if (birtEngine == null) { EngineConfig config = new EngineConfig(); java.util.HashMap map = config.getAppContext();; map.put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, SegnalazioniDbManager.class.getClassLoader()); config.setAppContext(map); IPlatformContext context = new PlatformServletContext(sc); config.setPlatformContext(context); try { Platform.startup(config); //problem begins here ..... } [1]: http://developer.actuate.com/community/forum/index.php?/topic/20933-errorcannotstartuposgiplatform/ A: Yes it is indeed a permission error. The relevant file is: WEB-INF/platform/configuration/org.eclipse.osgi/.manager/.fileTableLock You need to give access to the Birt user.
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:892675", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629066" }
978c5326d16f265e0d70711a12e191c0ae84d91a
Stackoverflow Stackexchange Q: iOS GeoFencing: when user leaves the region in a subway What happens when user has no connection whatsoever and leaves the area I'm monitoring? I am trying to implement something like "Significant location change" monitoring for devices without SIM card. So I'm basically, monitoring a region around a user. When he leaves the area, I'm getting his new location and starting monitoring new area around his new location. And it seems to work fine, until I'm leaving that region without GPS or wi-fi connection (in a subway). Also, I want my app to keep track while it is suspended, so I can't check for region after some time has passed. I'm using AppDelegate's didFinishLaunching with options callback to begin new region tracking. Edit: My best idea for now is to couple CLVisit with CLRegion monitoring to check if user has already left the old region when he stops.
Q: iOS GeoFencing: when user leaves the region in a subway What happens when user has no connection whatsoever and leaves the area I'm monitoring? I am trying to implement something like "Significant location change" monitoring for devices without SIM card. So I'm basically, monitoring a region around a user. When he leaves the area, I'm getting his new location and starting monitoring new area around his new location. And it seems to work fine, until I'm leaving that region without GPS or wi-fi connection (in a subway). Also, I want my app to keep track while it is suspended, so I can't check for region after some time has passed. I'm using AppDelegate's didFinishLaunching with options callback to begin new region tracking. Edit: My best idea for now is to couple CLVisit with CLRegion monitoring to check if user has already left the old region when he stops.
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:892693", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629137" }
2cab5dd1ea4aaed279699e42675a2ee0fb39b59f
Stackoverflow Stackexchange Q: JAXB: How to always include xsi:type for elements of type that has subtypes? Let's assume following schema: <xsd:complexType name="User"> <xsd:sequence> <xsd:element name="name" type="xs:string"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="SpecialUser"> <xsd:complexContent> <xsd:extension base="User"> <xsd:sequence> <xsd:element name="speciality" type="xs:string"/> </xsd:sequence> </xsd:extension> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="UserContainer"> <xsd:sequence> <xsd:element name="user" type="User"/> </xsd:sequence> </xsd:complexType> Now when I serialize: new UserContainer() .withUser( new SpecialUser() .withName("name") .withSpeciality("speciality") ) I got: ... <user xsi:type="SpecialUser"> <name>name</name> <speciality></speciality> </user> ... However when I serialize: new UserContainer() .withUser( new User() .withName("name") ) I got: ... <user> <name>name</name> </user> ... Is there a way to configure JAXB to include xsi:type in second example (despite being redundant)?
Q: JAXB: How to always include xsi:type for elements of type that has subtypes? Let's assume following schema: <xsd:complexType name="User"> <xsd:sequence> <xsd:element name="name" type="xs:string"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="SpecialUser"> <xsd:complexContent> <xsd:extension base="User"> <xsd:sequence> <xsd:element name="speciality" type="xs:string"/> </xsd:sequence> </xsd:extension> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="UserContainer"> <xsd:sequence> <xsd:element name="user" type="User"/> </xsd:sequence> </xsd:complexType> Now when I serialize: new UserContainer() .withUser( new SpecialUser() .withName("name") .withSpeciality("speciality") ) I got: ... <user xsi:type="SpecialUser"> <name>name</name> <speciality></speciality> </user> ... However when I serialize: new UserContainer() .withUser( new User() .withName("name") ) I got: ... <user> <name>name</name> </user> ... Is there a way to configure JAXB to include xsi:type in second example (despite being redundant)?
stackoverflow
{ "language": "en", "length": 102, "provenance": "stackexchange_0000F.jsonl.gz:892756", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629299" }
3798ef0a4f06b79bc93330bc195bf34b96700f22
Stackoverflow Stackexchange Q: react-native: Command `run-android` unrecognized. Maybe caused by npm install Recently I started getting this issue, when I install a react-native package (eg: react-navigation) into my project, a whole bunch of packages are been removed (including react, react-native i think). And then when i try to run command "run-android", it says it doesn't recognize. I recently updated to the latest npm and react-native-cli. Is it something wrong with "npm install"? or react-native? node version: 8.1.2 <br/> react-native-cli: 2.0.1 <br/> react-native: 0.45.1 <br/> react-navigation: 1.0.0-beta.11 Below are the steps to re-create: * *Step 1 - Create project. *Step 2 - Run the "run-android" command (This works). *Step 3 - Install "react-native-navigation" into project. Notice in the image above. Seems like all the other packages are removed from the project.<br/><br/> * *Step 4 - Try running "run-android" command again. (will fail, but used to work before) Any idea on what the issue is and any way to solve it? A: Found the solution here. At first running npm install didn't work, but then, deleting the package-lock.json file and running npm install did the job. After that I installed react-navigation package seperately and it worked fine.
Q: react-native: Command `run-android` unrecognized. Maybe caused by npm install Recently I started getting this issue, when I install a react-native package (eg: react-navigation) into my project, a whole bunch of packages are been removed (including react, react-native i think). And then when i try to run command "run-android", it says it doesn't recognize. I recently updated to the latest npm and react-native-cli. Is it something wrong with "npm install"? or react-native? node version: 8.1.2 <br/> react-native-cli: 2.0.1 <br/> react-native: 0.45.1 <br/> react-navigation: 1.0.0-beta.11 Below are the steps to re-create: * *Step 1 - Create project. *Step 2 - Run the "run-android" command (This works). *Step 3 - Install "react-native-navigation" into project. Notice in the image above. Seems like all the other packages are removed from the project.<br/><br/> * *Step 4 - Try running "run-android" command again. (will fail, but used to work before) Any idea on what the issue is and any way to solve it? A: Found the solution here. At first running npm install didn't work, but then, deleting the package-lock.json file and running npm install did the job. After that I installed react-navigation package seperately and it worked fine. A: Here's what worked for me from start to finish. * *react-native init NavTest (The cli is locally installed with this command) *deleted package-lock.json *npm install --save react-navigation *deleted the generated package-lock.json *npm install *react-native run android A little ugly, I don't know entirely what happened, but this worked. https://reactnavigation.org/ for sample code to run. Or Copy this to index.android.js import React, { Component } from 'react'; import { AppRegistry, Button, } from 'react-native'; import { StackNavigator, } from 'react-navigation'; class HomeScreen extends Component { static navigationOptions = { title: 'Welcome', }; render() { const { navigate } = this.props.navigation; return ( <Button title="Go to Jane's profile" onPress={() => navigate('Profile', { name: 'Jane' }) } /> ); } } class ProfileScreen extends Component{ static navigationOptions = { title: 'Jane', }; render() { return (null); } } const NavTest= StackNavigator({ Home: { screen: HomeScreen }, Profile: { screen: ProfileScreen }, }); AppRegistry.registerComponent('NavTest', () => NavTest);
stackoverflow
{ "language": "en", "length": 347, "provenance": "stackexchange_0000F.jsonl.gz:892759", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629309" }
5cc9527ee9d8808af94eabcf1291c6983101166b
Stackoverflow Stackexchange Q: Unable to use pip inside jenkins I am trying to create a virtualenv inside jenkins job and then install requirements.txt. But I am unable to create virtualenv. This is what my Jenkins file look like. sh 'sudo easy_install pip; pip install virtualenv' But I am getting + sudo easy_install pip Searching for pip Best match: pip 9.0.1 Processing pip-9.0.1-py2.7.egg pip 9.0.1 is already the active version in easy-install.pth Installing pip script to /usr/local/bin Installing pip2.7 script to /usr/local/bin Installing pip2 script to /usr/local/bin Using /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg Processing dependencies for pip Finished processing dependencies for pip + pip install virtualenv /Users/Shared/Jenkins/Home/workspace/test-jenkinsfile@tmp/durable-e0a93859/script.sh: line 3: pip: command not found A: The pip command cannot be found within the user's path. the solution is either call it directly from /usr/local/bin/pip or add /usr/local/bin to the user's path for bash: PATH=${PATH}:/usr/local/bin for (t)csh: setenv PATH "${PATH}:/usr/local/bin"
Q: Unable to use pip inside jenkins I am trying to create a virtualenv inside jenkins job and then install requirements.txt. But I am unable to create virtualenv. This is what my Jenkins file look like. sh 'sudo easy_install pip; pip install virtualenv' But I am getting + sudo easy_install pip Searching for pip Best match: pip 9.0.1 Processing pip-9.0.1-py2.7.egg pip 9.0.1 is already the active version in easy-install.pth Installing pip script to /usr/local/bin Installing pip2.7 script to /usr/local/bin Installing pip2 script to /usr/local/bin Using /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg Processing dependencies for pip Finished processing dependencies for pip + pip install virtualenv /Users/Shared/Jenkins/Home/workspace/test-jenkinsfile@tmp/durable-e0a93859/script.sh: line 3: pip: command not found A: The pip command cannot be found within the user's path. the solution is either call it directly from /usr/local/bin/pip or add /usr/local/bin to the user's path for bash: PATH=${PATH}:/usr/local/bin for (t)csh: setenv PATH "${PATH}:/usr/local/bin"
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:892794", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629443" }
e43363ccb6e3a113a4e0a06b6005e37e5acf8ba2
Stackoverflow Stackexchange Q: blob to base64 converstion javascript I am trying to parse blob object into base64 string in javascript. Please help. my code is var reader = new FileReader(); reader.addEventListener("loadend", function () { // reader.result contains the contents of blob as a typed array var buffer = reader.result; var view = new Uint8Array(buffer); var binary = String.fromCharCode.apply(window, view); var base64 = btoa(binary); cb(base64); console.log(base64); }); reader.readAsArrayBuffer(data.blob); A: You may try this- var blob = //your blob data; var reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { var base64data = reader.result; console.log(base64data); return; } Refer- Convert blob to base64
Q: blob to base64 converstion javascript I am trying to parse blob object into base64 string in javascript. Please help. my code is var reader = new FileReader(); reader.addEventListener("loadend", function () { // reader.result contains the contents of blob as a typed array var buffer = reader.result; var view = new Uint8Array(buffer); var binary = String.fromCharCode.apply(window, view); var base64 = btoa(binary); cb(base64); console.log(base64); }); reader.readAsArrayBuffer(data.blob); A: You may try this- var blob = //your blob data; var reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { var base64data = reader.result; console.log(base64data); return; } Refer- Convert blob to base64
stackoverflow
{ "language": "en", "length": 98, "provenance": "stackexchange_0000F.jsonl.gz:892799", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629459" }
b7e2db166977b619aa1ef47bf39994bc073abd2a
Stackoverflow Stackexchange Q: Deploying Azure Resource Group project as a part of MsBuild script I'm trying to migrate our solution from classic to Resource Manager deployment and I've stuck with running the RM deployment as a step of MsBuild build script. For the classic project there is <MSBuild Projects="SomeAzureProject\SomeAzureProject.ccproj" Targets="Publish" Properties=" VisualStudioVersion=$(VisualStudioVersion); Configuration=$(CloudConfiguration); Platform=$(Platform); TargetProfile=$(CloudTargetProfile); PublishProfile=$(CloudPublishProfile); PublishDir=$(CloudPublishDir);"></MSBuild> build step. Is there something like this for the .deployproj ? If yes - what parameters should be passed to it? (we need to be able to pass at least resource group name, params file name and the template file name).
Q: Deploying Azure Resource Group project as a part of MsBuild script I'm trying to migrate our solution from classic to Resource Manager deployment and I've stuck with running the RM deployment as a step of MsBuild build script. For the classic project there is <MSBuild Projects="SomeAzureProject\SomeAzureProject.ccproj" Targets="Publish" Properties=" VisualStudioVersion=$(VisualStudioVersion); Configuration=$(CloudConfiguration); Platform=$(Platform); TargetProfile=$(CloudTargetProfile); PublishProfile=$(CloudPublishProfile); PublishDir=$(CloudPublishDir);"></MSBuild> build step. Is there something like this for the .deployproj ? If yes - what parameters should be passed to it? (we need to be able to pass at least resource group name, params file name and the template file name).
stackoverflow
{ "language": "en", "length": 96, "provenance": "stackexchange_0000F.jsonl.gz:892810", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629485" }
f667f94d7db80e21af49c90cd5ad5f308abd2cb5
Stackoverflow Stackexchange Q: What is the difference between Routes and Jobs in Talend ESB? They seem to be doing more or less the same thing - taking data, processing it and sending it out. Internet search results show that Talend Routes are almost the same as Camel Routes, but that does not say anything about what they are and how are they different from Jobs. What are the Routes and Jobs in Talend ESB? What is the difference between them? When to prefer one over the other? A: The main difference between Talend routes and jobs is that when you start a route, it listens indefinitely for input (file, message..etc), and whenever it is available it is processed and sent to destination ,until the route is stopped. On the other hand, a job is a batch process that is launched on demand to handle some input (files, database..etc) and ends when all input is processed.
Q: What is the difference between Routes and Jobs in Talend ESB? They seem to be doing more or less the same thing - taking data, processing it and sending it out. Internet search results show that Talend Routes are almost the same as Camel Routes, but that does not say anything about what they are and how are they different from Jobs. What are the Routes and Jobs in Talend ESB? What is the difference between them? When to prefer one over the other? A: The main difference between Talend routes and jobs is that when you start a route, it listens indefinitely for input (file, message..etc), and whenever it is available it is processed and sent to destination ,until the route is stopped. On the other hand, a job is a batch process that is launched on demand to handle some input (files, database..etc) and ends when all input is processed. A: Talend ESB jobs are exactly the same as the jobs you can make in other versions of Talend Studio (Data Integration Studio for example). Talend jobs are best suited to the creation of ETL (Extract-Transform-Load) data processes in which data needs to be Extracted, Transformed and Loaded between various types of object or system (i.e. databases, flatfiles etc.). Typically, you'd be talking about anything from small to large sets of data being processed over intervals greater than a few minutes or so. Talend ESB Studio takes the process you build in the Studio user interface and generates Java code in the background which allows your job to be executed when you click the run button. In enterprise versions of Talend, you can deploy these jobs to run on schedules, but it's also possible to export them by hand using the Studio itself. Talend ESB Routes are quite similar to jobs in that they generate Java code in the background just as jobs do, but their use is more suited to web services and messaging systems, where you have smaller sets of data and want to transport it in near real-time. Most (if not all) of the generated code for Talend ESB Routes use a Java framework called Apache Camel. Camel is used for creating Integration Patterns (the scope of which is pretty huge), but you can think of it loosely as a set of tools for creating messaging systems. Routes aren't designed to be periodically run - rather they get deployed in some form of OSGi container (Apache Karaf for example, which is bundled with Talend ESB) and are more service-oriented. An important point to note is that you can actually call Talend Jobs from a Talend Route if you want.
stackoverflow
{ "language": "en", "length": 445, "provenance": "stackexchange_0000F.jsonl.gz:892825", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629515" }
15e43731f7c737583929b0e3ecaec6e3c7c778c3
Stackoverflow Stackexchange Q: FormControl boolean without default value in angular 2 I'm using reactive forms in angular 2 (4.1.2) I have a boolean property which I don't want to have a default value but it should be required. This is how I create my form: constructor(private fb: FormBuilder) { this.form = this.fb.group({ payedOvertime: [false, Validators.required], }); } And my html: <div class="form-group"> <label>Payed overtime</label> <label> <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="true" />Yes </label> <label> <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="false" />No </label> </div> The problem is that while this works the radiobutton is preselected but I do not want that, rather it should have to be selected by clicking at one of the radio-buttons. If neither of the radiobuttons are clicked I want the form to be invalid. A: Only change Validators.required to Validators.requiredTrue, Something like: payedOvertime: [false, Validators.requiredTrue]
Q: FormControl boolean without default value in angular 2 I'm using reactive forms in angular 2 (4.1.2) I have a boolean property which I don't want to have a default value but it should be required. This is how I create my form: constructor(private fb: FormBuilder) { this.form = this.fb.group({ payedOvertime: [false, Validators.required], }); } And my html: <div class="form-group"> <label>Payed overtime</label> <label> <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="true" />Yes </label> <label> <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="false" />No </label> </div> The problem is that while this works the radiobutton is preselected but I do not want that, rather it should have to be selected by clicking at one of the radio-buttons. If neither of the radiobuttons are clicked I want the form to be invalid. A: Only change Validators.required to Validators.requiredTrue, Something like: payedOvertime: [false, Validators.requiredTrue] A: Change payedOvertime: [false, Validators.required] to payedOvertime: [null, Validators.required]. Given that you set it to false, it matches the value of No radio button in the template and it selects it by default (rightly so). Setting it to null will prevent Angular from matching the value with any of those declared in the template and thus non of those radio buttons will be selected.
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:892844", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629621" }
3f96acc5a521f5ede0eda7c5ad2cf1465affc3ac
Stackoverflow Stackexchange Q: How to "correctly" copy a types.SimpleNamespace object? I was expecting to be able to do something like: a = SimpleNamespace(x='test') b = a.copy() or maybe: b = SimpleNamespace(a) My current solution, which seems to work fine is b = SimpleNamespace(**a.__dict__) But it looks somewhat hacky. Is there a more "correct" way? I don't need a deep copy. A: I wanted to use do a deepcopy of a SimpleNamespace. A simple and easy to read way is to use the copy module. new_namespace = copy.copy(namespace) or new_namespace = copy.deepcopy(namespace) depending on what you need.
Q: How to "correctly" copy a types.SimpleNamespace object? I was expecting to be able to do something like: a = SimpleNamespace(x='test') b = a.copy() or maybe: b = SimpleNamespace(a) My current solution, which seems to work fine is b = SimpleNamespace(**a.__dict__) But it looks somewhat hacky. Is there a more "correct" way? I don't need a deep copy. A: I wanted to use do a deepcopy of a SimpleNamespace. A simple and easy to read way is to use the copy module. new_namespace = copy.copy(namespace) or new_namespace = copy.deepcopy(namespace) depending on what you need.
stackoverflow
{ "language": "en", "length": 94, "provenance": "stackexchange_0000F.jsonl.gz:892847", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629627" }
fb42f5f0717232a4fb7331c1f46f05160fc1bb0b
Stackoverflow Stackexchange Q: Improving performance of hive jdbc Does aynyone know how to increase performance for HIVE JDBC connection. Detailed problem: When I query hive from Hive CLI, I get a response within 7 sec but from HIVE JDBC connection I get a response after 14 sec. I was wondering if there is any way (configuration changes) with which I can improve performance for query through JDBC connection. Thanks in advance. A: Using Connection pooling helped me increase hive JDBC performance. As in hive there are many transformations happening while we query so using existing connection objects from connection pool instead of opening a new connection and closing for each request was quite helpful. Please let me know if any one else if facing same issue will post a detailed answer.
Q: Improving performance of hive jdbc Does aynyone know how to increase performance for HIVE JDBC connection. Detailed problem: When I query hive from Hive CLI, I get a response within 7 sec but from HIVE JDBC connection I get a response after 14 sec. I was wondering if there is any way (configuration changes) with which I can improve performance for query through JDBC connection. Thanks in advance. A: Using Connection pooling helped me increase hive JDBC performance. As in hive there are many transformations happening while we query so using existing connection objects from connection pool instead of opening a new connection and closing for each request was quite helpful. Please let me know if any one else if facing same issue will post a detailed answer. A: Can you please try the below options. * *If your query has joins then try setting the hive.auto.convert.join to true. *Try changing the configuration of Java Heap Size and Garbage Collection reference Link *Change the execution engine to Tez using set hive.execution.engine=tez To check currently set engine use hive.execution.engine. Other Hive performance configuration tips can be found in the Link Please let me know the results. A: To improve the performance of jdbc connection Use the standard jdbc performance improvement features -,connection pooling , prepared statement pooling (starting with jdbc 3.0) performance improvement of hive cli can be done by changing these configuration parameters -- enable cost based optimizer set hive.cbo.enable=true; set hive.compute.query.using.stats=true; set hive.stats.fetch.column.stats=true; set hive.stats.fetch.partition.stats=true; --collects statistics analyze table <TABLENAME> compute statistics for columns; --enable vectorization of queries. set hive.vectorized.execution.enabled = true; set hive.vectorized.execution.reduce.enabled = true; Hope thos helps A: If your database is Oracle you can try the Oracle Table Access for Hadoop and Spark (OTA4H) which can also be used from Hive QL. OTA4H will optimize the JDBC queries to retrieve the data from Oracle using splitters in order to get the best performance. You can join Hive tables with external tables inside Oracle directly in your hive queries.
stackoverflow
{ "language": "en", "length": 333, "provenance": "stackexchange_0000F.jsonl.gz:892859", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629663" }
d3b9509db7322f47e8bebe9d5aca00de64478ba8
Stackoverflow Stackexchange Q: How to apply timeout on method in Erlang? Is there a way to apply timeout on simple module method call, As example, my_method(Name)-> timer:sleep(2000), io:format("hello world ~p!~n",[Name]). I want to add timeout option to above method, is there a way to do it? A: You could spawn your function and wait for a a message back. You can set a timeout while you wait on the receive. my_method(Name)-> YourTimeOut = 10, Self = self(), _Pid = spawn(fun()-> timer:sleep(2000), io:format("hello world ~p!~n",[Name]), Self ! {self(), ok} end), receive {_PidSpawned, ok} -> ok after YourTimeOut -> timout end.
Q: How to apply timeout on method in Erlang? Is there a way to apply timeout on simple module method call, As example, my_method(Name)-> timer:sleep(2000), io:format("hello world ~p!~n",[Name]). I want to add timeout option to above method, is there a way to do it? A: You could spawn your function and wait for a a message back. You can set a timeout while you wait on the receive. my_method(Name)-> YourTimeOut = 10, Self = self(), _Pid = spawn(fun()-> timer:sleep(2000), io:format("hello world ~p!~n",[Name]), Self ! {self(), ok} end), receive {_PidSpawned, ok} -> ok after YourTimeOut -> timout end. A: See gen:call/3,4 implementation. It is done by do_call(Process, Label, Request, Timeout) -> try erlang:monitor(process, Process) of Mref -> %% If the monitor/2 call failed to set up a connection to a %% remote node, we don't want the '!' operator to attempt %% to set up the connection again. (If the monitor/2 call %% failed due to an expired timeout, '!' too would probably %% have to wait for the timeout to expire.) Therefore, %% use erlang:send/3 with the 'noconnect' option so that it %% will fail immediately if there is no connection to the %% remote node. catch erlang:send(Process, {Label, {self(), Mref}, Request}, [noconnect]), receive {Mref, Reply} -> erlang:demonitor(Mref, [flush]), {ok, Reply}; {'DOWN', Mref, _, _, noconnection} -> Node = get_node(Process), exit({nodedown, Node}); {'DOWN', Mref, _, _, Reason} -> exit(Reason) after Timeout -> %% <-- HERE erlang:demonitor(Mref, [flush]), exit(timeout) end catch error:_ -> %% Node (C/Java?) is not supporting the monitor. %% The other possible case -- this node is not distributed %% -- should have been handled earlier. %% Do the best possible with monitor_node/2. %% This code may hang indefinitely if the Process %% does not exist. It is only used for featureweak remote nodes. Node = get_node(Process), monitor_node(Node, true), receive {nodedown, Node} -> monitor_node(Node, false), exit({nodedown, Node}) after 0 -> Tag = make_ref(), Process ! {Label, {self(), Tag}, Request}, wait_resp(Node, Tag, Timeout) %% <-- HERE for C/Java nodes end end.
stackoverflow
{ "language": "en", "length": 332, "provenance": "stackexchange_0000F.jsonl.gz:892910", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629823" }
8f618a32c1a9459053233def40022979d1c407d0
Stackoverflow Stackexchange Q: How can I tell whether my Spring boot application is in debug mode? I'd like to modify how my application works depending on whether the --debug switch is present or not. I tried this in my @Configuration file: @Value("\${debug}") lateinit var debug: String but Spring says Could not resolve placeholder 'debug' in value "${debug}" How can I query the state of the --debug option? A: The most robust way to check for debug mode is to query the Environment. This will allow you to detect that the mode has been enabled whether that's been done via a command line argument (--debug), system property (-Ddebug), environment variable (DEBUG=true), etc. You can inject an instance of the Environment as you would any other dependency or you can implement EnvironmentAware. The getProperty(String) method can then be used to retrieve the value of the debug property. Spring Boot treats debug as being enabled if the debug property has a non-null value other than false: private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); return (value != null && !value.equals("false")); }
Q: How can I tell whether my Spring boot application is in debug mode? I'd like to modify how my application works depending on whether the --debug switch is present or not. I tried this in my @Configuration file: @Value("\${debug}") lateinit var debug: String but Spring says Could not resolve placeholder 'debug' in value "${debug}" How can I query the state of the --debug option? A: The most robust way to check for debug mode is to query the Environment. This will allow you to detect that the mode has been enabled whether that's been done via a command line argument (--debug), system property (-Ddebug), environment variable (DEBUG=true), etc. You can inject an instance of the Environment as you would any other dependency or you can implement EnvironmentAware. The getProperty(String) method can then be used to retrieve the value of the debug property. Spring Boot treats debug as being enabled if the debug property has a non-null value other than false: private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); return (value != null && !value.equals("false")); } A: I am afraid it is not possible to get debug mode this way. Spring looks for any property values here but --debug is not part of property. The debug detecting could be vendor specific. (see Determine if a java application is in debug mode in Eclipse for more info about debug detecting). A: the simplest way is makes debug option to a system property, for example: java -Ddebug Application then you can annotated the property as below: @Value("#{systemProperties.debug != null}") var debug: Boolean = false; // ^--- using a default value to avoiding NPException A: As already mentioned before in the reply by Andy, it is possible to evaluate the property debug, however you need to do this from the Environment. I ran into the same problem, when I wanted to activate a component, only in "debug mode". You can achieve this by using @ConditionalOnProperty("debug"), which does fetch the information from Environment and thus works with --debug, -Ddebug, …
stackoverflow
{ "language": "en", "length": 339, "provenance": "stackexchange_0000F.jsonl.gz:892934", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629885" }
9c85c50a79b13303906ef22cd1a1360eab704225
Stackoverflow Stackexchange Q: Error "name 'by' is not defined" using Python Selenium WebDriver I keep getting an error as below: NameError: name 'By' is not defined for the code chrome_driver_path = r"C:\chromedriver.exe" from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait browser = webdriver.Chrome(chrome_driver_path) browser.delete_all_cookies() browser.get("https://www.google.com/") wait = WebDriverWait(browser, 10) element = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="tsf"]/div[2]/div[3]/center/input[1]'))) Is my import correct? A: You have to import it: from selenium.webdriver.common.by import By
Q: Error "name 'by' is not defined" using Python Selenium WebDriver I keep getting an error as below: NameError: name 'By' is not defined for the code chrome_driver_path = r"C:\chromedriver.exe" from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait browser = webdriver.Chrome(chrome_driver_path) browser.delete_all_cookies() browser.get("https://www.google.com/") wait = WebDriverWait(browser, 10) element = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="tsf"]/div[2]/div[3]/center/input[1]'))) Is my import correct? A: You have to import it: from selenium.webdriver.common.by import By A: You can import By by using: from selenium.webdriver.common.by import By A: Adding this line at the top of the code resolved my problem: from selenium.webdriver.common.by import By
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:892958", "question_score": "36", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44629970" }
5fe61ee49bdea335bdc63993ace9ddcb86c962cf
Stackoverflow Stackexchange Q: Angular2 Change Detection I was learning about the how angular2 change detection works. I got the point that by default angular2 changeDetection works from the root node. After reading more about this I got the point that angular generate VM friendly code and perform more than thousand of checks within seconds for applying the change detection on the component. Can anyone please let me know more details about how angular generate VM friendly code practically using one code example?
Q: Angular2 Change Detection I was learning about the how angular2 change detection works. I got the point that by default angular2 changeDetection works from the root node. After reading more about this I got the point that angular generate VM friendly code and perform more than thousand of checks within seconds for applying the change detection on the component. Can anyone please let me know more details about how angular generate VM friendly code practically using one code example?
stackoverflow
{ "language": "en", "length": 80, "provenance": "stackexchange_0000F.jsonl.gz:893016", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630169" }
9d206f574cae3ca2f9738cfeccc2839b2c0199e6
Stackoverflow Stackexchange Q: RxSwift: How to add gesture to UILabel? I have a label with isUserInteractionEnabled set to true. Now, I need to add UITapGestureRecognizer for the label. Is there a way to add in Rx way. I have looked at the RxSwift library here. Which they didn't provide any extension for adding gesture. The UILabel+Rx file has only text and attributedText. Is there any workaround to add gesture to label? A: A UILabel is not configured with a tap gesture recognizer out of the box, that's why RxCocoa does not provide the means to listen to a gesture directly on the label. You will have to add the gesture recognizer yourself. Then you can use Rx to observe events from the recognizer, like so: let disposeBag = DisposeBag() let label = UILabel() label.text = "Hello World!" let tapGesture = UITapGestureRecognizer() label.addGestureRecognizer(tapGesture) tapGesture.rx.event.bind(onNext: { recognizer in print("touches: \(recognizer.numberOfTouches)") //or whatever you like }).disposed(by: disposeBag)
Q: RxSwift: How to add gesture to UILabel? I have a label with isUserInteractionEnabled set to true. Now, I need to add UITapGestureRecognizer for the label. Is there a way to add in Rx way. I have looked at the RxSwift library here. Which they didn't provide any extension for adding gesture. The UILabel+Rx file has only text and attributedText. Is there any workaround to add gesture to label? A: A UILabel is not configured with a tap gesture recognizer out of the box, that's why RxCocoa does not provide the means to listen to a gesture directly on the label. You will have to add the gesture recognizer yourself. Then you can use Rx to observe events from the recognizer, like so: let disposeBag = DisposeBag() let label = UILabel() label.text = "Hello World!" let tapGesture = UITapGestureRecognizer() label.addGestureRecognizer(tapGesture) tapGesture.rx.event.bind(onNext: { recognizer in print("touches: \(recognizer.numberOfTouches)") //or whatever you like }).disposed(by: disposeBag) A: Swift 5 (using RxGesture library). Best and simplest option imho. label .rx .tapGesture() .when(.recognized) // This is important! .subscribe(onNext: { [weak self] _ in guard let self = self else { return } self.doWhatYouNeedToDo() }) .disposed(by: disposeBag) Take care! If you don't use .when(.recognized) the tap gesture will fire as soon as your label is initialised! A: Swift 4 with RxCocoa + RxSwift + RxGesture let disposeBag = DisposeBag() let myView = UIView() myView.rx .longPressGesture(numberOfTouchesRequired: 1, numberOfTapsRequired: 0, minimumPressDuration: 0.01, allowableMovement: 1.0) .when(.began, .changed, .ended) .subscribe(onNext: { pan in let view = pan.view let location = pan.location(in: view) switch pan.state { case .began: print("began") case .changed: print("changed \(location)") case .ended: print("ended") default: break } }).disposed(by bag) or myView.rx .gesture(.tap(), .pan(), .swipe([.up, .down])) .subscribe({ onNext: gesture in switch gesture { case .tap: // Do something case .pan: // Do something case .swipeUp: // Do something default: break } }).disposed(by: bag) or event clever, to return an event. i.e string var buttons: Observable<[UIButton]>! let stringEvents = buttons .flatMapLatest({ Observable.merge($0.map({ button in return button.rx.tapGesture().when(.recognized) .map({ _ in return "tap" }) }) ) }) A: Those extensions are technically part of the RxCocoa libary which is currently packaged with RxSwift. You should be able to add the UITapGestureRecognizer to the view then just use the rx.event (rx_event if older) on that gesture object. If you have to do this in the context of the UILabel, then you might need to wrap it inside the UILabel+Rx too, but if you have simpler requirements just using the rx.event on the gesture should be a good workaround. A: You can subscribe label to the tap gesture label .rx .tapGesture() .subscribe(onNext: { _ in print("tap") }).disposed(by: disposeBag) A: As Write George Quentin. All work. view.rx .longPressGesture(configuration: { gestureRecognizer, delegate in gestureRecognizer.numberOfTouchesRequired = 1 gestureRecognizer.numberOfTapsRequired = 0 gestureRecognizer.minimumPressDuration = 0.01 gestureRecognizer.allowableMovement = 1.0 }) .when(.began, .changed, .ended) .subscribe(onNext: { pan in let view = pan.view let location = pan.location(in: view) switch pan.state { case .began: print(":DEBUG:began") case .changed: print(":DEBUG:changed \(location)") case .ended: print(":DEBUG:end \(location)") nextStep() default: break } }) .disposed(by: stepBag) A: I simple use this extension to get the tap as Driver in UI layer. public extension Reactive where Base: RxGestureView { func justTap() -> Driver<Void> { return tapGesture() .when(.recognized) .map{ _ in } .asDriver { _ in return Driver.empty() } } } When I need the tap event I call this view.rx.justTap()
stackoverflow
{ "language": "en", "length": 548, "provenance": "stackexchange_0000F.jsonl.gz:893018", "question_score": "33", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630176" }
411155d03a6afb55099af2171411b1f55eb5f9ac
Stackoverflow Stackexchange Q: What is the default value of the apns-expiration field? The apns-expiration field governs how long Apple will hold on to an apns message before giving up on delivering it (for example, if the device is turned off). According to their docs, a value of zero means "no retention": meaning that if the message can't be delivered immediately, its discarded. But what happens if the header isn't specified? In other words, what is the default behavior? A: My information isn't based on documentation but rather on stats gathered from a multi-million users system. The policy at this time is to retain push messages for a long time (exactly how long I dont know - we've seen 1M seconds retention in some cases). Of course, as this isn't documented it could change in the future. Note that this default value is similar to Google's policy (where the default is 2419200 seconds), with the exception that Google's policy is documented.
Q: What is the default value of the apns-expiration field? The apns-expiration field governs how long Apple will hold on to an apns message before giving up on delivering it (for example, if the device is turned off). According to their docs, a value of zero means "no retention": meaning that if the message can't be delivered immediately, its discarded. But what happens if the header isn't specified? In other words, what is the default behavior? A: My information isn't based on documentation but rather on stats gathered from a multi-million users system. The policy at this time is to retain push messages for a long time (exactly how long I dont know - we've seen 1M seconds retention in some cases). Of course, as this isn't documented it could change in the future. Note that this default value is similar to Google's policy (where the default is 2419200 seconds), with the exception that Google's policy is documented. A: https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW1 "If this value is nonzero, APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed if it is unable to deliver the notification the first time." Literally this means that the absence of the value equals to 0.
stackoverflow
{ "language": "en", "length": 205, "provenance": "stackexchange_0000F.jsonl.gz:893027", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630196" }
fa029b8a5a422ced8e1b6436e693e8d15c391473
Stackoverflow Stackexchange Q: regsvr32, should i unregister before register again? Scenario: * *I installed the COM dll on client machine in c:\program.dll and invoked the following command to register: regsvr32 "c:\program.dll" *I updated the dll with a new version, in the same directory as the installation "c:\program.dll". Doubt: Before registering the new version of the dll, do I need to unregister the previous version first? regsvr32 "c:\program.dll" /u If yes, why? A: You should unregister the old version, using the DllUnregisterServer function of the existing DLL. It won't make a difference if the new version being installed sets up the same registry keys, but keep in mind that the user may be downgrading to an earlier version that doesn't implement a particular class -- in which case that class would remain registered.
Q: regsvr32, should i unregister before register again? Scenario: * *I installed the COM dll on client machine in c:\program.dll and invoked the following command to register: regsvr32 "c:\program.dll" *I updated the dll with a new version, in the same directory as the installation "c:\program.dll". Doubt: Before registering the new version of the dll, do I need to unregister the previous version first? regsvr32 "c:\program.dll" /u If yes, why? A: You should unregister the old version, using the DllUnregisterServer function of the existing DLL. It won't make a difference if the new version being installed sets up the same registry keys, but keep in mind that the user may be downgrading to an earlier version that doesn't implement a particular class -- in which case that class would remain registered.
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:893031", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630203" }
cd11043ebe46dc68eda6554341e209eb8505b3ea
Stackoverflow Stackexchange Q: PyTorch Pretrained VGG19 KeyError I'm working on fine tuning the first 10 layers of VGG19 net to extract features from images. But I'm getting the below error which I couldn't find a get around: Traceback (most recent call last): File "TODO-train_from_scratch.py", line 390, in <module> main() File "TODO-train_from_scratch.py", line 199, in main model.load_state_dict(weights_load) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 339, in load_state_dict raise KeyError('missing keys in state_dict: "{}"'.format(missing)) Corresponding snippet from training code is: # create model vgg19 = models.vgg19(pretrained = True) vgg19_state_dict = vgg19.state_dict() vgg19_keys = vgg19_state_dict.keys() model = get_model() weights_load = {} for i in range(20): weights_load[model.state_dict().keys()[i]] = vgg19_state_dict[vgg19_keys[i]] model.load_state_dict(weights_load) model = torch.nn.DataParallel(model).cuda()
Q: PyTorch Pretrained VGG19 KeyError I'm working on fine tuning the first 10 layers of VGG19 net to extract features from images. But I'm getting the below error which I couldn't find a get around: Traceback (most recent call last): File "TODO-train_from_scratch.py", line 390, in <module> main() File "TODO-train_from_scratch.py", line 199, in main model.load_state_dict(weights_load) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 339, in load_state_dict raise KeyError('missing keys in state_dict: "{}"'.format(missing)) Corresponding snippet from training code is: # create model vgg19 = models.vgg19(pretrained = True) vgg19_state_dict = vgg19.state_dict() vgg19_keys = vgg19_state_dict.keys() model = get_model() weights_load = {} for i in range(20): weights_load[model.state_dict().keys()[i]] = vgg19_state_dict[vgg19_keys[i]] model.load_state_dict(weights_load) model = torch.nn.DataParallel(model).cuda()
stackoverflow
{ "language": "en", "length": 103, "provenance": "stackexchange_0000F.jsonl.gz:893097", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630395" }
5da42077db18c2ab7b77b7c2101d0e9c43c86547
Stackoverflow Stackexchange Q: Laravel/Homestead - can't connect to the DB I have installed homestead on my machine and cloned a project from a remote repository, now I am trying to create a DB for my project. This is how my .env file looks like: APP_ENV=local APP_DEBUG=true APP_KEY=base64:e7K7SUDgogNqTtP9TO1CfpbXFAC6FmLLSJ1l6K8pbWs= DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=localhost REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null I have tried to connect to DB using sequel pro standard option: Host: localhost Password: secret But I get: Unable to connect to host 127.0.0.1, or the request timed out. Be sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently 10 seconds). MySQL said: Can't connect to MySQL server on '127.0.0.1' (61) What am I doing wrong? A: Some options: * *Check the service of mysql is running; *Check the user and passowrd are correct; *Check the privilege of the user, try root user
Q: Laravel/Homestead - can't connect to the DB I have installed homestead on my machine and cloned a project from a remote repository, now I am trying to create a DB for my project. This is how my .env file looks like: APP_ENV=local APP_DEBUG=true APP_KEY=base64:e7K7SUDgogNqTtP9TO1CfpbXFAC6FmLLSJ1l6K8pbWs= DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=localhost REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null I have tried to connect to DB using sequel pro standard option: Host: localhost Password: secret But I get: Unable to connect to host 127.0.0.1, or the request timed out. Be sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently 10 seconds). MySQL said: Can't connect to MySQL server on '127.0.0.1' (61) What am I doing wrong? A: Some options: * *Check the service of mysql is running; *Check the user and passowrd are correct; *Check the privilege of the user, try root user A: For Mysql Connection you should have check username and password. and .env file DB_HOST=localhost DB_DATABASE=Your Database name DB_USERNAME=username DB_PASSWORD=password Along With that, you can update database.php file for database configurations. A: I had to add the port 33060 to be able to connect. Hope that will help others who got stuck like me. A: I have some problem with Laravel 7 Homestead. I solve the error with this step: * *Use mysql port 33060 *Clear laraver config. php artisan config:clear *Reload vagrant vagrant reload --provision And make sure your database name and password is correct. Happy coding.
stackoverflow
{ "language": "en", "length": 254, "provenance": "stackexchange_0000F.jsonl.gz:893111", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630430" }
7bee9e1ed8493e610bf620768e03e3647e635fba
Stackoverflow Stackexchange Q: yoyo migrations apply selected migrations to postgreSQL I'm using yoyo migrations to modify DB schema. I want to apply/rollback to Postgre DB not all "migrations" in migrations folder, but only those "migrations", that I selected. For example, if I have 001.test.py and 002.test.py and I want to apply/rollback only 002.test.py, how can I do it? In particular how to do this stuff in python code, not in shell? Yoyo's manual gives example only for execution of ALL migrations at once: from yoyo import read_migrations, get_backend backend = get_backend('postgres://postgres:postgres@localhost/db_test') migrations = read_migrations('/home/dfialkovskiy/dev/migrations') backend.apply_migrations(backend.to_apply(migrations)) backend.rollback_migrations(migrations) I think I need something like this, to choose migration script which to apply: backend.apply_migrations(backend.to_apply(migrations[1])) backend.rollback_migrations(migrations[0]) (this example doesn't work obviously) A: That is actually a real problem with yoyo migrations I faced the same problem but I overcome this with the code given below, this solves rolling back or applying specific migration. This example does it for applying migration only but it can be applied to roll back in a similar way. backend = get_backend('postgres://postgres:postgres@localhost/db_test') migrations = read_migrations('/home/dfialkovskiy/dev/migrations') migrations_to_apply = backend.to_apply(migrations) for pending_migration in migrations_to_apply: if pending_migration.id == os.path.splitext(sys.argv[1])[0].split('/')[-1]: backend.apply_one(pending_migration)
Q: yoyo migrations apply selected migrations to postgreSQL I'm using yoyo migrations to modify DB schema. I want to apply/rollback to Postgre DB not all "migrations" in migrations folder, but only those "migrations", that I selected. For example, if I have 001.test.py and 002.test.py and I want to apply/rollback only 002.test.py, how can I do it? In particular how to do this stuff in python code, not in shell? Yoyo's manual gives example only for execution of ALL migrations at once: from yoyo import read_migrations, get_backend backend = get_backend('postgres://postgres:postgres@localhost/db_test') migrations = read_migrations('/home/dfialkovskiy/dev/migrations') backend.apply_migrations(backend.to_apply(migrations)) backend.rollback_migrations(migrations) I think I need something like this, to choose migration script which to apply: backend.apply_migrations(backend.to_apply(migrations[1])) backend.rollback_migrations(migrations[0]) (this example doesn't work obviously) A: That is actually a real problem with yoyo migrations I faced the same problem but I overcome this with the code given below, this solves rolling back or applying specific migration. This example does it for applying migration only but it can be applied to roll back in a similar way. backend = get_backend('postgres://postgres:postgres@localhost/db_test') migrations = read_migrations('/home/dfialkovskiy/dev/migrations') migrations_to_apply = backend.to_apply(migrations) for pending_migration in migrations_to_apply: if pending_migration.id == os.path.splitext(sys.argv[1])[0].split('/')[-1]: backend.apply_one(pending_migration) A: I've faced similar problem with yoyo when I wrote my first DB migrations. I solved the problem with another module - SQLalchemy migrate. Check the docs here. It's very understandable and user-friendly.
stackoverflow
{ "language": "en", "length": 218, "provenance": "stackexchange_0000F.jsonl.gz:893167", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630641" }
fe1c11798bfb473133feb141d71708e1d22d0dd9
Stackoverflow Stackexchange Q: How can I call an async function without await? I have a controller action in aiohttp application. async def handler_message(request): try: content = await request.json() perform_message(x,y,z) except (RuntimeError): print("error in perform fb message") finally: return web.Response(text="Done") perform_message is async function. Now, when I call action I want that my action return as soon as possible and perform_message put in event loop. In this way, perform_message isn't executed A: One way would be to use create_task function: import asyncio async def handler_message(request): ... loop = asyncio.get_event_loop() loop.create_task(perform_message(x,y,z)) ... As per the loop documentation, starting Python 3.10, asyncio.get_event_loop() is deprecated. If you're trying to get a loop instance from a coroutine/callback, you should use asyncio.get_running_loop() instead. This method will not work if called from the main thread, in which case a new loop must be instantiated: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(perform_message(x, y, z)) loop.run_forever() Furthermore, if the call is only made once throughout your program's runtime and no other loop needs to be is instantiated (unlikely), you may use: asyncio.run(perform_message(x, y, z)) This function creates an event loop and terminates it once the coroutine ends, therefore should only be used in the aforementioned scenario.
Q: How can I call an async function without await? I have a controller action in aiohttp application. async def handler_message(request): try: content = await request.json() perform_message(x,y,z) except (RuntimeError): print("error in perform fb message") finally: return web.Response(text="Done") perform_message is async function. Now, when I call action I want that my action return as soon as possible and perform_message put in event loop. In this way, perform_message isn't executed A: One way would be to use create_task function: import asyncio async def handler_message(request): ... loop = asyncio.get_event_loop() loop.create_task(perform_message(x,y,z)) ... As per the loop documentation, starting Python 3.10, asyncio.get_event_loop() is deprecated. If you're trying to get a loop instance from a coroutine/callback, you should use asyncio.get_running_loop() instead. This method will not work if called from the main thread, in which case a new loop must be instantiated: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(perform_message(x, y, z)) loop.run_forever() Furthermore, if the call is only made once throughout your program's runtime and no other loop needs to be is instantiated (unlikely), you may use: asyncio.run(perform_message(x, y, z)) This function creates an event loop and terminates it once the coroutine ends, therefore should only be used in the aforementioned scenario. A: In simplest form: import asyncio from datetime import datetime def _log(msg : str): print(f"{datetime.utcnow()} {msg}") async def dummy(name, delay_sec): _log(f"{name} entering ...") await asyncio.sleep(delay_sec) _log(f"{name} done for the day!") async def main(): asyncio.create_task(dummy('dummy1', 5)) # last to finish asyncio.create_task(dummy('dummy2', 3)) # 2nd asyncio.create_task(dummy('dummy3', 1)) # First to finish _log(f"Yo I didn't wait for ya!") await asyncio.sleep(10) asyncio.get_event_loop().run_until_complete(main()) Output: 2022-09-18 00:53:13.428285 Yo I didn't wait for ya! 2022-09-18 00:53:13.428285 dummy1 entering ... 2022-09-18 00:53:13.428285 dummy2 entering ... 2022-09-18 00:53:13.428285 dummy3 entering ... 2022-09-18 00:53:14.436801 dummy3 done for the day! 2022-09-18 00:53:16.437226 dummy2 done for the day! 2022-09-18 00:53:18.424755 dummy1 done for the day! A: Other way would be to use ensure_future function: import asyncio async def handler_message(request): ... loop = asyncio.get_event_loop() loop.ensure_future(perform_message(x,y,z)) ...
stackoverflow
{ "language": "en", "length": 316, "provenance": "stackexchange_0000F.jsonl.gz:893176", "question_score": "57", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630676" }
04e57b297879c4708f41e468253349f58efe7f6b
Stackoverflow Stackexchange Q: Formatting Numbers in Swift 3 I want to format number to this: 123.234.234.234 from 123234234234 depends on what the user types into the text field. I don't want to manage currency, it's not about currency, it is about the user has to type in a number and this number should be formatted correctly to be easier to read. Not with a comma, with a dot. I found only currency stuff in the whole research A: You can do it with NumberFormatter: let yourNumber = 123234234234 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal numberFormatter.groupingSeparator = "." let formattedNumber = numberFormatter.string(from: NSNumber(value:yourNumber))
Q: Formatting Numbers in Swift 3 I want to format number to this: 123.234.234.234 from 123234234234 depends on what the user types into the text field. I don't want to manage currency, it's not about currency, it is about the user has to type in a number and this number should be formatted correctly to be easier to read. Not with a comma, with a dot. I found only currency stuff in the whole research A: You can do it with NumberFormatter: let yourNumber = 123234234234 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal numberFormatter.groupingSeparator = "." let formattedNumber = numberFormatter.string(from: NSNumber(value:yourNumber)) A: Details * *Xcode 9.2, Swift 4 *Xcode 10.2 (10E125), Swift 5 Solution import Foundation extension String { var toLocale: Locale { return Locale(identifier: self) } } extension NumberFormatter { convenience init(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) { self.init() set(numberStyle: numberStyle, groupingSeparator: groupingSeparator, decimalSeparator: decimalSeparator) } convenience init(numberStyle: NumberFormatter.Style, locale: Locale) { self.init() set(numberStyle: numberStyle, locale: locale) } func set(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) { self.locale = nil self.numberStyle = numberStyle self.groupingSeparator = groupingSeparator self.decimalSeparator = decimalSeparator } func set(numberStyle: NumberFormatter.Style, locale: Locale?) { self.numberStyle = numberStyle self.locale = locale } } extension Numeric { func format(formatter: NumberFormatter) -> String? { if let num = self as? NSNumber { return formatter.string(from: num) } return nil } } Usage let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale) print(value.format(formatter: formatter)) formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".") print(value.format(formatter: formatter)) Full sample Do not forget to add the solution code here func test<T: Numeric>(value: T) { print("=========================================================") print("\(T.self), value = \(value)") let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale) print(value.format(formatter: formatter) ?? "nil") formatter.set(numberStyle: .currency, locale: "de_DE".toLocale) print(value.format(formatter: formatter) ?? "nil") formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".") print(value.format(formatter: formatter) ?? "nil") } func print(title: String, value: String?) { if let value = value { print("\(title) \(value)") } } test(value: Int(10000)) test(value: Double(10000.231)) test(value: Float(10000.231)) Result ========================================================= Int, value = 10000 10 000 10.000,00 € 10 000 ========================================================= Double, value = 10000.231 10 000,231 10.000,23 € 10 000.231 ========================================================= Float, value = 10000.231 10 000,231 10.000,23 € 10 000.231 A: swift 4 extension Int { func formatnumber() -> String { let formater = NumberFormatter() formater.groupingSeparator = "." formater.numberStyle = .decimal return formater.string(from: NSNumber(value: self))! } } A: For leading zeros (Swift 5.2) String(format: "%02d", intNumber) // 6 -> "06" String(format: "%03d", intNumber) // 66 -> "066" String(format: "%04d", intNumber) // 666 -> "0666" from: https://stackoverflow.com/a/25566860/1064316 A: What you are looking for is probably groupingSeparator of NumberFormatter let formater = NumberFormatter() formater.groupingSeparator = "." formater.numberStyle = .decimal let formattedNumber = formater.string(from: number) A: There's actually much easier solution (there is no need to create NumberFormatter instance) and it takes into account the user's language: let result = String(format: "%ld %@", locale: Locale.current, viewCount, "views") Result for value 1000000 with English: 1,000,000 Russian: 1 000 000 p.s. in Android it's exactly the same String.format(Locale.getDefault(), "%,d %s", viewCount, "views") A: For swift 4, I implemented an extension where I can choose the formatting or use default one if none is selected. extension Int { func formatnumber(groupingSeparator: String?) -> String { let formater = NumberFormatter() formater.groupingSeparator = (groupingSeparator != nil) ? groupingSeparator! : "," formater.numberStyle = .decimal return formater.string(from: NSNumber(value: self))! } } A: My script as an example: 1) Add extension to project extension String { public func subString(startIndex: String.Index, endIndex: String.Index) -> String { return String(self[startIndex...endIndex]) } public func subString(_ from: Int, _ to: Int) -> String { let startIndex = self.index(self.startIndex, offsetBy: from) let endIndex = self.index(self.startIndex, offsetBy: to) return String(self[startIndex...endIndex]) } } 2) Create file Utilites.swift and add my method public func priceNumFormat(_ number: String)->String{ var formattedNumber = number var print = number var prefix = "" if number.range(of:"-") != nil { let index = number.index(of:"-") formattedNumber.remove(at: index ?? formattedNumber.endIndex) prefix = "-" } if formattedNumber.range(of:".") != nil { let index = formattedNumber.index(of:".") formattedNumber = formattedNumber.subString(startIndex: formattedNumber.startIndex, endIndex: index ?? formattedNumber.endIndex) formattedNumber.remove(at: index ?? formattedNumber.endIndex) } if formattedNumber.count == 8 //10 000 000 { let num0 = formattedNumber.subString(0, 1) let num1 = formattedNumber.subString(2, 4) let num2 = formattedNumber.subString(5, 7) print = "\(num0) \(num1) \(num2)" } if formattedNumber.count == 7 //1 000 000 { let num0 = formattedNumber.subString(0, 0) let num1 = formattedNumber.subString(1, 3) let num2 = formattedNumber.subString(4, 6) print = "\(num0) \(num1) \(num2)" } if formattedNumber.count == 6 //100 000 { let num0 = formattedNumber.subString(0, 2) let num1 = formattedNumber.subString(3, 5) print = "\(num0) \(num1)" } if formattedNumber.count == 5 //10 000 { let num0 = formattedNumber.subString(0, 1) let num1 = formattedNumber.subString(2, 4) print = "\(num0) \(num1)" } if formattedNumber.count == 4 //1 000 { let num0 = formattedNumber.subString(0, 0) let num1 = formattedNumber.subString(1, 3) print = "\(num0) \(num1)" } if formattedNumber.count == 3 //100 { print = formattedNumber } if prefix.count > 0 { print = "- \(print)" } return print; } 3) Add code in your UIController let utils = Utilites() private func test(){ var price = self.utils.priceNumFormat("-12345678.000") print("\(price)") //-12 345 678 price = self.utils.priceNumFormat("-1234567.000") print("\(price)") //-1 234 567 price = self.utils.priceNumFormat("-123456.000") print("\(price)") //-123 456 price = self.utils.priceNumFormat("-12345.000") print("\(price)") //-12 345 price = self.utils.priceNumFormat("-1234.000") print("\(price)") //-1 234 price = self.utils.priceNumFormat("-123.000") print("\(price)") //-123 }
stackoverflow
{ "language": "en", "length": 852, "provenance": "stackexchange_0000F.jsonl.gz:893186", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630702" }
fe68fb5c361919eb6c596fe212b3f9797b6faef0
Stackoverflow Stackexchange Q: Reading .exr files in OpenCV I have generated some depth maps using blender and have saved z-buffer values(32 bits) in OpenEXR format. Is there any way to access values from a .exr file (pixel by pixel depth info) using OpenCV 2.4.13 and python 2.7? There is no example anywhere to be found. All I can see in documentation that this file format is supported. But trying to read such a file results in error. new=cv2.imread("D:\\Test1\\0001.exr") cv2.imshow('exr',new) print new[0,0] Error: print new[0,0] TypeError: 'NoneType' object has no attribute '__getitem__' and cv2.imshow('exr',new) cv2.error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow Closest I found is this link and this link. A: You can use OpenEXR package pip --no-cache-dir install OpenEXR If the above fails, install the OpenEXR dev library and then install the python package as above sudo apt-get install openexr sudo apt-get install libopenexr-dev If gcc is not installed sudo apt-get install gcc sudo apt-get install g++ To read exr file def read_depth_exr_file(filepath: Path): exrfile = exr.InputFile(filepath.as_posix()) raw_bytes = exrfile.channel('B', Imath.PixelType(Imath.PixelType.FLOAT)) depth_vector = numpy.frombuffer(raw_bytes, dtype=numpy.float32) height = exrfile.header()['displayWindow'].max.y + 1 - exrfile.header()['displayWindow'].min.y width = exrfile.header()['displayWindow'].max.x + 1 - exrfile.header()['displayWindow'].min.x depth_map = numpy.reshape(depth_vector, (height, width)) return depth_map
Q: Reading .exr files in OpenCV I have generated some depth maps using blender and have saved z-buffer values(32 bits) in OpenEXR format. Is there any way to access values from a .exr file (pixel by pixel depth info) using OpenCV 2.4.13 and python 2.7? There is no example anywhere to be found. All I can see in documentation that this file format is supported. But trying to read such a file results in error. new=cv2.imread("D:\\Test1\\0001.exr") cv2.imshow('exr',new) print new[0,0] Error: print new[0,0] TypeError: 'NoneType' object has no attribute '__getitem__' and cv2.imshow('exr',new) cv2.error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow Closest I found is this link and this link. A: You can use OpenEXR package pip --no-cache-dir install OpenEXR If the above fails, install the OpenEXR dev library and then install the python package as above sudo apt-get install openexr sudo apt-get install libopenexr-dev If gcc is not installed sudo apt-get install gcc sudo apt-get install g++ To read exr file def read_depth_exr_file(filepath: Path): exrfile = exr.InputFile(filepath.as_posix()) raw_bytes = exrfile.channel('B', Imath.PixelType(Imath.PixelType.FLOAT)) depth_vector = numpy.frombuffer(raw_bytes, dtype=numpy.float32) height = exrfile.header()['displayWindow'].max.y + 1 - exrfile.header()['displayWindow'].min.y width = exrfile.header()['displayWindow'].max.x + 1 - exrfile.header()['displayWindow'].min.x depth_map = numpy.reshape(depth_vector, (height, width)) return depth_map A: Full solution @Iwohlhart's solution threw an error for me and following fixed it, # first import os and enable the necessary flags to avoid cv2 errors import os os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1" import cv2 # then just type in following img = cv2.imread(PATH2EXR, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH) ''' you might have to disable following flags, if you are reading a semantic map/label then because it will convert it into binary map so check both lines and see what you need ''' # img = cv2.imread(PATH2EXR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) A: I might be a little late to the party but; Yes you can definitely use OpenCV for that. cv2.imread(PATH_TO_EXR_FILE, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH) should get you what you need
stackoverflow
{ "language": "en", "length": 312, "provenance": "stackexchange_0000F.jsonl.gz:893215", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630793" }
6e655b067778337cc4c5bba111ac215213f99b71
Stackoverflow Stackexchange Q: Pandas Loop through list of Data Frames and Change Index This is a basic quesion, but I want to loop through a list of data frames and for each data frame, set the index as one of the columns in the data frame. The issue with the code below is that it doesn't save the data frame with a new index. How do I format this For loop so that the dataframes are permanently changed outside of the for loop? Thanks. dflist = [df_1, df_2, df_3] for i in dflist: i = i.set_index('column_2') A: As you have probably guessed, i is just a temporary value. Use i as only an index using enumerate for i, df in enumerate(dflist): dflist[i] = dflist[i].set_index('column_2'))
Q: Pandas Loop through list of Data Frames and Change Index This is a basic quesion, but I want to loop through a list of data frames and for each data frame, set the index as one of the columns in the data frame. The issue with the code below is that it doesn't save the data frame with a new index. How do I format this For loop so that the dataframes are permanently changed outside of the for loop? Thanks. dflist = [df_1, df_2, df_3] for i in dflist: i = i.set_index('column_2') A: As you have probably guessed, i is just a temporary value. Use i as only an index using enumerate for i, df in enumerate(dflist): dflist[i] = dflist[i].set_index('column_2')) A: for i in dflist: i.set_index('column_2', inplace=True) A: Try it with the in place option: i = i.set_index('column_2', inplace=True)
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:893219", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630805" }
d9ff147c38b14798cdf557ec32464aa46ddb4d14
Stackoverflow Stackexchange Q: Why would a small script continue using 70%+ of CPU after executing? I am very new to Python, but this does not make sense to me, here's an example script: import pygame as py import time py.init() song = py.mixer.Sound("pineSiskin.wav") # c1Mb/20sec long song.play(0 , 9000) time.sleep(8) song.fadeout(800) py.quit() print("quit") Running this on a Raspberry Pi*, the CPU goes up to 75% and stays there until I restart the Python shell. This soon leads to overheating on the RPi. Other questions (like this one & other mentioned in link), are dissimilar as they refer to scripts which have not completed. This link does hint that what I'm seeing is not "normal" behaviour. Any help to track this problem/diagnostic advice would be useful. Apologies if I've made a mistake about which forum; tell me and I'll move it! *Hardware/Software: * *Raspberry Pi 3 Model B running *Raspbian Jessie Pixel *Python 3.4.2 accessed via IDLE3 Python 3.4.2 as bundled with scipi & matplotlib added A: this problem turned out to be an OS problem. recreating the Raspbian OS from a new disk image solved it. Now scripts are behaving as I'd expect.
Q: Why would a small script continue using 70%+ of CPU after executing? I am very new to Python, but this does not make sense to me, here's an example script: import pygame as py import time py.init() song = py.mixer.Sound("pineSiskin.wav") # c1Mb/20sec long song.play(0 , 9000) time.sleep(8) song.fadeout(800) py.quit() print("quit") Running this on a Raspberry Pi*, the CPU goes up to 75% and stays there until I restart the Python shell. This soon leads to overheating on the RPi. Other questions (like this one & other mentioned in link), are dissimilar as they refer to scripts which have not completed. This link does hint that what I'm seeing is not "normal" behaviour. Any help to track this problem/diagnostic advice would be useful. Apologies if I've made a mistake about which forum; tell me and I'll move it! *Hardware/Software: * *Raspberry Pi 3 Model B running *Raspbian Jessie Pixel *Python 3.4.2 accessed via IDLE3 Python 3.4.2 as bundled with scipi & matplotlib added A: this problem turned out to be an OS problem. recreating the Raspbian OS from a new disk image solved it. Now scripts are behaving as I'd expect.
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:893236", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630863" }
0de25f64797323f3143015bd2629cbeb86c0956a
Stackoverflow Stackexchange Q: Where exactly do Tickets and Threads get Inserted Into osTicket Database? Can anyone tell me exactly where, in the overall code files of osTicket, the insertion of new ticket records and the insertion of thread records is performed? Are there multiple places in osTicket that actually execute the INSERT INTO or does it only happen in one spot? Thank you for helping. A: Threads - class.thread.php * *INSERT ThreadEntry::create($vars) (line 1112) *SET BODY ThreadEntry::create($vars) (line 1173), ThreadEntry::setBody($body) (line 331) Tickets - class.tickets.php * *Ticket::create($vars, &$errors, $origin, $autorespond=true, $alertstaff=true) (line 2941) Ticket line number might be different, because of my custom changes.
Q: Where exactly do Tickets and Threads get Inserted Into osTicket Database? Can anyone tell me exactly where, in the overall code files of osTicket, the insertion of new ticket records and the insertion of thread records is performed? Are there multiple places in osTicket that actually execute the INSERT INTO or does it only happen in one spot? Thank you for helping. A: Threads - class.thread.php * *INSERT ThreadEntry::create($vars) (line 1112) *SET BODY ThreadEntry::create($vars) (line 1173), ThreadEntry::setBody($body) (line 331) Tickets - class.tickets.php * *Ticket::create($vars, &$errors, $origin, $autorespond=true, $alertstaff=true) (line 2941) Ticket line number might be different, because of my custom changes. A: You might want to look at /include/class.ticket.php. Search for "static function create" all you need is there i guess.
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:893259", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630918" }
4725d38231f6d1b78b1973d6c495f7a7f8554ace
Stackoverflow Stackexchange Q: ignore rule on block Like with sonar-java and the annotation @SuppressWarnings("squid:S2078"), is there any way with sonar-js to ignore one rule on a block of code ?? The git repo doesn't have any exemple of that. I develop a react-redux ES6 app and i have reducer with default value : export default function myReducer(prev = initialState, action) and Sonar complain with "Function parameters with default values should be last". But i can't change the order of the parameters of a reducer and i need a default value. A: The options you have: * *in your project administration in SQ you can set up ignoring some files for some rule (see docs) *you mark issues in SQ as "won't fix" *you put "// NOSONAR" comment in the line with issue You can also report false-positive issue in SonarJS github issues.
Q: ignore rule on block Like with sonar-java and the annotation @SuppressWarnings("squid:S2078"), is there any way with sonar-js to ignore one rule on a block of code ?? The git repo doesn't have any exemple of that. I develop a react-redux ES6 app and i have reducer with default value : export default function myReducer(prev = initialState, action) and Sonar complain with "Function parameters with default values should be last". But i can't change the order of the parameters of a reducer and i need a default value. A: The options you have: * *in your project administration in SQ you can set up ignoring some files for some rule (see docs) *you mark issues in SQ as "won't fix" *you put "// NOSONAR" comment in the line with issue You can also report false-positive issue in SonarJS github issues.
stackoverflow
{ "language": "en", "length": 140, "provenance": "stackexchange_0000F.jsonl.gz:893268", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630941" }
b64a243c23e268f5b3d5ac60c7556ae90523d318
Stackoverflow Stackexchange Q: Jenkins GitHub connectivity error - Your account is suspended I am trying to connect to GitHub Enterprise from Jenkins but I am facing a connection issue saying - Failed to connect to repository : Command "/usr/bin/git ls-remote -h git@xxx/yyy.git HEAD" returned status code 128: stdout: stderr: ERROR: Your account is suspended. Please check with your installation administrator. fatal: The remote end hung up unexpectedly The funny thing is the account that I am using is able to login to GitHub and is not suspended. I have tried using both SSH and password to no avail. Any lead will be appreciated. A: This was a problem with expired SSH keys. I had to regenerate it and it started working again.
Q: Jenkins GitHub connectivity error - Your account is suspended I am trying to connect to GitHub Enterprise from Jenkins but I am facing a connection issue saying - Failed to connect to repository : Command "/usr/bin/git ls-remote -h git@xxx/yyy.git HEAD" returned status code 128: stdout: stderr: ERROR: Your account is suspended. Please check with your installation administrator. fatal: The remote end hung up unexpectedly The funny thing is the account that I am using is able to login to GitHub and is not suspended. I have tried using both SSH and password to no avail. Any lead will be appreciated. A: This was a problem with expired SSH keys. I had to regenerate it and it started working again. A: In my case, it was an issue on the GHE operator's side. They changed something and my account started working again. You could also try to change your PAT but that would likely indicate another issue. See this: VSTS issues connecting to GHE (HTTP 403) A: I cleared all keys stored in keychain access for github. And then gave my credentials agian to take a pull from the repo. A: In my case, I removed ~/.gitconfig and it worked. A: Remove your previous github SSH KEY and generate a new one. ssh-keygen -t rsa -b 4096 -C <emailId> A: In my case, there was expired/bad password stored in my Windows Credentials Manager. Once I deleted it, git asked me authenticate again. It started working again A: In my case it is an Internet connection with bad timing which hits all kinds of SSL network state machine bugs. Esp. libcurl is broken and closes the SSL connection three times instead of only once. This causes RSTs (resets) in the tcpdump and can cause the SSL handshake to hang. It hits something else with every Linux kernel update. This time it is git and I need to reclone my repos before I can use git fetch. It has been zypper, Firefox, and Chrome before.
stackoverflow
{ "language": "en", "length": 333, "provenance": "stackexchange_0000F.jsonl.gz:893280", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44630962" }
374382133112286b534bc462f347d6c935f95cd7
Stackoverflow Stackexchange Q: Python 3.5 - "Geckodriver executable needs to be in PATH" I added geckodriver.exe into PATH as you can see on this image and i restarted my computer after. But the error still show up. Here's my code : from selenium import webdriver driver = webdriver.Firefox() driver.get('https://stackoverflow.com') Do you have clues about what I did wrong ? A: I don't see any significant error in your code block. While working with Selenium 3.4.3, geckodriver v0.17.0, Mozilla Firefox 53.0 with Python 3.6.1 you can consider downloading the geckodriver and save it anywhere in your machine and configuring the absolute path of the geckodriver through executable_path. It is to be noted that the current Selenium-Python binding is unstable with geckodriver and looks to be Architecture specific. You can find the github discussion and merge here. So you may additionally need to pass the absolute path of the firefox binary as firefox_binary argument while initializing the webdriver Here is your own code block which executes well at my end: from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe') driver = webdriver.Firefox(firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe") driver.get('https://stackoverflow.com')
Q: Python 3.5 - "Geckodriver executable needs to be in PATH" I added geckodriver.exe into PATH as you can see on this image and i restarted my computer after. But the error still show up. Here's my code : from selenium import webdriver driver = webdriver.Firefox() driver.get('https://stackoverflow.com') Do you have clues about what I did wrong ? A: I don't see any significant error in your code block. While working with Selenium 3.4.3, geckodriver v0.17.0, Mozilla Firefox 53.0 with Python 3.6.1 you can consider downloading the geckodriver and save it anywhere in your machine and configuring the absolute path of the geckodriver through executable_path. It is to be noted that the current Selenium-Python binding is unstable with geckodriver and looks to be Architecture specific. You can find the github discussion and merge here. So you may additionally need to pass the absolute path of the firefox binary as firefox_binary argument while initializing the webdriver Here is your own code block which executes well at my end: from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe') driver = webdriver.Firefox(firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe") driver.get('https://stackoverflow.com') A: There are three ways to resolve this error. * *Download the gecko driver and keep it in directory where your python test script is there. *Set the environment variable "webdriver.gecko.driver" with driver path as value. os.environ["webdriver.gecko.driver"]="c:\geckodriver.exe" *Pass executable path to the constructor like driver = WebDriver.Firefox("path of executable") A: Are you setting the capabilities correctly? In case you are setting the version capability, verify that it is correct or remove it altogether. I am talking of the below: capabilities.SetCapability("version", "50.0"); A: In Windows 10 it can be solved after replacing Firefox driver with chrome driver. driver = webdriver.Chrome() Download Visual Studio 2015, 2017 and 2019 https://aka.ms/vs/16/release/vc_redist.x86.exe OR https://aka.ms/vs/16/release/vc_redist.x64.exe and install based on your Operating system. Download Chrome Driver from https://chromedriver.storage.googleapis.com/index.html?path=79.0.3945.36/ based on your operating system. Add chrome drivers in your PATH
stackoverflow
{ "language": "en", "length": 316, "provenance": "stackexchange_0000F.jsonl.gz:893293", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631020" }
da953904e910c665f46143cc41ef82ae49a7d6ef
Stackoverflow Stackexchange Q: Where can I download SDK for visual studio 2013? I have Visual Studio 2013 and want to install SDK for it. Can't add 2015 SDK because it is part of VS 2015 installation, I couldn't find a stand alone installation. 2013 SDK was removed from the official site. It is also not contained in my installation package for VS. Thanks A: Apart from excellent answer by Sara Liu - MSFT, I was able to find a Visual Studio 2013 SDK - Microsoft Go! download page from google. The direct link was go.microsoft.com/?linkid=9832352 and it downloaded a +13Mb vssdk_full.exe
Q: Where can I download SDK for visual studio 2013? I have Visual Studio 2013 and want to install SDK for it. Can't add 2015 SDK because it is part of VS 2015 installation, I couldn't find a stand alone installation. 2013 SDK was removed from the official site. It is also not contained in my installation package for VS. Thanks A: Apart from excellent answer by Sara Liu - MSFT, I was able to find a Visual Studio 2013 SDK - Microsoft Go! download page from google. The direct link was go.microsoft.com/?linkid=9832352 and it downloaded a +13Mb vssdk_full.exe A: Please navigate to this: Download older versions of VS and click the ‘Join now for free’ to sign in with your Microsoft account, if you are not a subscriber. Then confirm to join the VS Dev Essential if you have not joined before. Click ‘Downloads’ and search with the keyword ‘Visual Studio 2013 SDK’, you will get the download link as below:
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:893363", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631274" }
fa63b9859ed9473e0edb40d03a9d25581b988b56
Stackoverflow Stackexchange Q: how to get particular product quantity from the cart page in the woocommerce With this code: foreach ( WC()->cart->get_cart() as $cart_item ) { $quantity = $cart_item['quantity']; echo $quantity; } I can get the quantity of all the products added in cart but I need it for the particular product. A: global $woocommerce; $items = $woocommerce->cart->get_cart(); foreach($items as $item => $values) { $_product = $values['data']->post; echo "<b>".$_product->post_title.'</b> <br> Quantity: '.$values['quantity'].'<br>'; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."<br>"; }
Q: how to get particular product quantity from the cart page in the woocommerce With this code: foreach ( WC()->cart->get_cart() as $cart_item ) { $quantity = $cart_item['quantity']; echo $quantity; } I can get the quantity of all the products added in cart but I need it for the particular product. A: global $woocommerce; $items = $woocommerce->cart->get_cart(); foreach($items as $item => $values) { $_product = $values['data']->post; echo "<b>".$_product->post_title.'</b> <br> Quantity: '.$values['quantity'].'<br>'; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."<br>"; } A: $cart = WC()->cart->get_cart(); $product_cart_id = WC()->cart->generate_cart_id( $product->get_id() ); if( WC()->cart->find_product_in_cart( $product_cart_id )) { echo($cart[$product_cart_id]['quantity']); } A: You can loop through cart items to get the quantity for a specific product id as follows: // Set here your product ID (or variation ID) $targeted_id = 24; // Loop through cart items foreach ( WC()->cart->get_cart() as $cart_item ) { if( in_array( $targeted_id, array($cart_item['product_id'], $cart_item['variation_id']) )){ $quantity = $cart_item['quantity']; break; // stop the loop if product is found } } // Displaying the quantity if targeted product is in cart if( isset( $quantity ) && $quantity > 0 ) { printf( "<p>" . __("Quantity for Product ID %d is: %d") . "</p>", $targeted_id, $quantity ); } Or you can also use the WC_Cart method get_cart_item_quantities() as follow: // Set here your product ID (or variation ID) $targeted_id = 24; // Get quantities for each item in cart (array of product id / quantity pairs) $quantities = WC()->cart->get_cart_item_quantities(); // Displaying the quantity if targeted product is in cart if( isset($quantities[$targeted_id]) && $quantities[$targeted_id] > 0 ) { printf( "<p>" . __("Quantity for Product ID %d is: %d") . "</p>", $targeted_id, $quantities[$targeted_id] ); } Note: This last way doesn't allow to target the parent variable product. A: Try this : <?php global $woocommerce; $items = $woocommerce->cart->get_cart(); foreach($items as $item => $values) { $_product = $values['data']->post; echo "<b>".$_product->post_title.'</b> <br> Quantity: '.$values['quantity'].'<br>'; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."<br>"; } ?> A: 1) Make a child theme 2) Create a file named functions.php with this code : <?php if( !function_exists('in_cart_product_quantity') ) { function in_cart_product_quantity( $atts ) { $atts = shortcode_atts(array('id' => ''), $atts, 'product_qty'); // shortcode attributes if( empty($atts['id'])) return; // check id not null if ( WC()->cart ) { // check cart exists $qty = 0; // init qty foreach (WC()->cart->get_cart() as $cart_item) { if($cart_item['product_id'] == $atts['id']) { $qty = $cart_item['quantity']; break; // stop the loop if product is found } } return $qty; } return; } add_shortcode( 'product_qty', 'in_cart_product_quantity' ); } 3) Use the shortcode : [product_qty id="xxx"] (Change xxx with id of the product you want to know the quantity in cart) Thanks to LoicTheAztec (Same thread) A: WC_Cart::get_cart_item_quantities() – Get cart items quantities * *Via $product_id // Your product ID $product_id = 30; // Get cart items quantities $cart_item_quantities = WC()->cart->get_cart_item_quantities(); // Product quantity in cart - All PHP versions $product_qty_in_cart = isset( $cart_item_quantities[ $product_id ] ) ? $cart_item_quantities[ $product_id ] : null; // Product quantity in cart - Same as the previous one with PHP 7 $product_qty_in_cart = $cart_item_quantities[ $product_id ] ?? null; // Result echo $product_qty_in_cart; *Via $product // Product global $product; // Get cart items quantities $cart_item_quantities = WC()->cart->get_cart_item_quantities(); // Product quantity in cart $product_qty_in_cart = $cart_item_quantities[ $product->get_stock_managed_by_id() ]; // Result echo $product_qty_in_cart;
stackoverflow
{ "language": "en", "length": 537, "provenance": "stackexchange_0000F.jsonl.gz:893381", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631312" }
62d8be731196ed9e2b3329d3d9515ddf512ec0f8
Stackoverflow Stackexchange Q: Powershell script to schedule daily task error I have a very simple power shell script that will register console applications as daily scheduled tasks. $TaskCommand = Read-Host 'Enter the path to the console application' $TaskName = "TaskName" $TaskStartTime = "10PM" $TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted" $TaskAction = New-ScheduledTaskAction -Execute "$TaskCommand" -Argument "$TaskArg" $TaskTrigger = New-ScheduledTaskTrigger -At $TaskStartTime -Daily Register-ScheduledTask -Action $TaskAction -Trigger $TaskTrigger -TaskName "$TaskName" -User %computername%\theusername -Password "password" -RunLevel Highest The application reads the file path from user input and attempts to register the application as a task using a specific user account. I can get the script working by using -User "System" However when I try to use the above script I get this error: Register-ScheduledTask: No mapping between account names and security IDs was done. I have ensured that the account exists as it is currently running several services. I am also new to powershell so have tried adding quotations around the username with no luck. A: Don't think PowerShell recognises %computername%. Have a look at environment variables here. $env:USERNAME, $env:USERDOMAIN $env:COMPUTERNAME look relevant to your task.
Q: Powershell script to schedule daily task error I have a very simple power shell script that will register console applications as daily scheduled tasks. $TaskCommand = Read-Host 'Enter the path to the console application' $TaskName = "TaskName" $TaskStartTime = "10PM" $TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted" $TaskAction = New-ScheduledTaskAction -Execute "$TaskCommand" -Argument "$TaskArg" $TaskTrigger = New-ScheduledTaskTrigger -At $TaskStartTime -Daily Register-ScheduledTask -Action $TaskAction -Trigger $TaskTrigger -TaskName "$TaskName" -User %computername%\theusername -Password "password" -RunLevel Highest The application reads the file path from user input and attempts to register the application as a task using a specific user account. I can get the script working by using -User "System" However when I try to use the above script I get this error: Register-ScheduledTask: No mapping between account names and security IDs was done. I have ensured that the account exists as it is currently running several services. I am also new to powershell so have tried adding quotations around the username with no luck. A: Don't think PowerShell recognises %computername%. Have a look at environment variables here. $env:USERNAME, $env:USERDOMAIN $env:COMPUTERNAME look relevant to your task. A: For me, it was an issue of having trailing spaces where the variables were stored. Unrelated to the question at hand, but perhaps a sanity-check worth pursuing for others who reads this.
stackoverflow
{ "language": "en", "length": 216, "provenance": "stackexchange_0000F.jsonl.gz:893421", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631447" }
7f2ffe7c551d3df9f0804bb047742cfa8e47e007
Stackoverflow Stackexchange Q: os.rename [Errno 2] No such file or directory I tried to rename directories in MacOS, even have used codes of others but os.rename still throws me errors, I give the full path of my directories and their new names as path. May someone help to solve this problem? thanks in advance import os directory = "/../" dirs = next(os.walk(directory))[1] for file in dirs: path = os.path.join(directory, file) target = os.path.join(directory, '/' + file.replace('.','/')) os.rename(path, target) with dash [Errno 2] No such file or directory: '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m.01kk_s6' -> '/m/01kk_s6' without dash FileNotFoundError: [Errno 2] No such file or directory: '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m.01kk_s6' -> '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m/01kk_s6' P.S file exists and os.rename works when I do rename the file to the same name target = os.path.join(directory, file) os.rename(path, target) And by the way, I'm trying to rename the directories(full of images) inside the directory, maybe something is in here.Btw, when I try just to use os.rename on images ( not on directories full of images ) it works fine A: When renaming something to /j/k/l/m/foo, it is important that directory m exists. If not, you must mkdir m. Just before your rename call, do this: os.makedirs(os.path.dirname(target), exist_ok=True)
Q: os.rename [Errno 2] No such file or directory I tried to rename directories in MacOS, even have used codes of others but os.rename still throws me errors, I give the full path of my directories and their new names as path. May someone help to solve this problem? thanks in advance import os directory = "/../" dirs = next(os.walk(directory))[1] for file in dirs: path = os.path.join(directory, file) target = os.path.join(directory, '/' + file.replace('.','/')) os.rename(path, target) with dash [Errno 2] No such file or directory: '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m.01kk_s6' -> '/m/01kk_s6' without dash FileNotFoundError: [Errno 2] No such file or directory: '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m.01kk_s6' -> '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m/01kk_s6' P.S file exists and os.rename works when I do rename the file to the same name target = os.path.join(directory, file) os.rename(path, target) And by the way, I'm trying to rename the directories(full of images) inside the directory, maybe something is in here.Btw, when I try just to use os.rename on images ( not on directories full of images ) it works fine A: When renaming something to /j/k/l/m/foo, it is important that directory m exists. If not, you must mkdir m. Just before your rename call, do this: os.makedirs(os.path.dirname(target), exist_ok=True)
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:893422", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631449" }
42d0fcd9ed4b4a1b71f1a9cfb65c5d8b92c710a4
Stackoverflow Stackexchange Q: Remove a white background - sharp library Is it possible to replace a white background of an image with transparency using the sharp library?
Q: Remove a white background - sharp library Is it possible to replace a white background of an image with transparency using the sharp library?
stackoverflow
{ "language": "en", "length": 25, "provenance": "stackexchange_0000F.jsonl.gz:893444", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631531" }
30a5d1b15e4226557835a8c63cf574012bdfde2e
Stackoverflow Stackexchange Q: If defined for inheriting views @BindingAdapter resolves to which one? Let's assume that there is @BindingAdapter("imageUrl") defined for ImageView and MyImageView which inherits from ImageView. To which method annotated with @BindingAdapter would app:imageUrlresolve to if used in MyImageView? My understanding is that due to the inheritance relationship this should be ambiguous. A: If you are using your MyImageView in your layout.xml, the called method will be the method declared within the MyImageView class. If this method does not exist inside this class, it will call the method of its superclass (ImageView) that inherits it due to inheritance. In this case the method overload happens. If you are using just your ImageView in your layout.xml, the called method will be method declared inside the ImageView class.
Q: If defined for inheriting views @BindingAdapter resolves to which one? Let's assume that there is @BindingAdapter("imageUrl") defined for ImageView and MyImageView which inherits from ImageView. To which method annotated with @BindingAdapter would app:imageUrlresolve to if used in MyImageView? My understanding is that due to the inheritance relationship this should be ambiguous. A: If you are using your MyImageView in your layout.xml, the called method will be the method declared within the MyImageView class. If this method does not exist inside this class, it will call the method of its superclass (ImageView) that inherits it due to inheritance. In this case the method overload happens. If you are using just your ImageView in your layout.xml, the called method will be method declared inside the ImageView class.
stackoverflow
{ "language": "en", "length": 126, "provenance": "stackexchange_0000F.jsonl.gz:893486", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631662" }
98b6d141c82d352e3ddcc65a1b8670da7ff82b0f
Stackoverflow Stackexchange Q: How to revert markAsPending() in Angular 2 form? I am using form.markAsPending() to show a loading spinner while the form is submitting data and I would like to markAsNOTPending() as soon as it completes, something like: updateProfile(): void { this.updateProfileForm.markAsPending(); // <------- SET AS PENDING const formData = { username: this.updateProfileForm.value.username, email: this.updateProfileForm.value.email }; this.us.editProfile(formData) .first() .subscribe( res => { this.updateProfileForm.markAsNOTPending(); // <------- SET AS NOT PENDING }, err => { this.updateProfileForm.setErrors({ formError: true }); } ); } Is there anyway to achieve it? Thanks A: I don't think markAsPending() is made for that, it is a state that describe that a Validator is validating and not yet finished. You can check the PR for the implementation that gives more explanation.
Q: How to revert markAsPending() in Angular 2 form? I am using form.markAsPending() to show a loading spinner while the form is submitting data and I would like to markAsNOTPending() as soon as it completes, something like: updateProfile(): void { this.updateProfileForm.markAsPending(); // <------- SET AS PENDING const formData = { username: this.updateProfileForm.value.username, email: this.updateProfileForm.value.email }; this.us.editProfile(formData) .first() .subscribe( res => { this.updateProfileForm.markAsNOTPending(); // <------- SET AS NOT PENDING }, err => { this.updateProfileForm.setErrors({ formError: true }); } ); } Is there anyway to achieve it? Thanks A: I don't think markAsPending() is made for that, it is a state that describe that a Validator is validating and not yet finished. You can check the PR for the implementation that gives more explanation. A: I would set errors instead. Like the example below: this.updateProfileForm.setErrors({'incorrect': true}); and to remove it I would do this this.updateProfileForm.setErrors(null);
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:893512", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631754" }
6ee3f5919b331635a9a9792c2f69d59870356fb5
Stackoverflow Stackexchange Q: Able to run Python3 Script through IDE, Command Line, but not by double clicking or Task Scheduler So I have written a script that scrapes betting data from an odds aggregating site and outputs everything into a CSV. My script works perfectly, however, I can only run it from within Spyder. Whenever I double click the PY file a terminal opens up and closes quickly. After messing around with it for a while I also discovered that I can run it through the command line. I have the program/script line pointing to my python3: C:\Users\path\AppData\Local\Continuum\Anaconda3\python.exe And my argument line points to the script \networkname\path\moneylineScraper.py Best case scenario I would like to be able to run this script through task scheduler, but I also cannot even run it when I double click the Py file. Any help would be appreciated! A: An alternative is, to create a bat file and then execute it. A new bat file: -- change directory to that of python script file. -- using full path execute python with script file as argument. -- End the batch file. Make that bat file executable with sufficient previlages and execute that.
Q: Able to run Python3 Script through IDE, Command Line, but not by double clicking or Task Scheduler So I have written a script that scrapes betting data from an odds aggregating site and outputs everything into a CSV. My script works perfectly, however, I can only run it from within Spyder. Whenever I double click the PY file a terminal opens up and closes quickly. After messing around with it for a while I also discovered that I can run it through the command line. I have the program/script line pointing to my python3: C:\Users\path\AppData\Local\Continuum\Anaconda3\python.exe And my argument line points to the script \networkname\path\moneylineScraper.py Best case scenario I would like to be able to run this script through task scheduler, but I also cannot even run it when I double click the Py file. Any help would be appreciated! A: An alternative is, to create a bat file and then execute it. A new bat file: -- change directory to that of python script file. -- using full path execute python with script file as argument. -- End the batch file. Make that bat file executable with sufficient previlages and execute that.
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:893521", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631802" }
3a867c849ba07d9fe2304c3eaa1bf829c7d5c6ae
Stackoverflow Stackexchange Q: iOS swift How to create .p8 file? I am working with Pushy Notification where I need to register with the p8 file. So how can I create that p8 file from developer account? A: Follow these steps: Generate an APNs Auth Key Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key. In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page. Apple will then generate a .p8 key file containing your APNs Auth Key. Download the .p8 key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs. Send Push Notifications Ref: APNS (Configure push notifications) Important: Save a back up of your key in a secure place. It will not be presented again and cannot be retrieved later.
Q: iOS swift How to create .p8 file? I am working with Pushy Notification where I need to register with the p8 file. So how can I create that p8 file from developer account? A: Follow these steps: Generate an APNs Auth Key Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key. In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page. Apple will then generate a .p8 key file containing your APNs Auth Key. Download the .p8 key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs. Send Push Notifications Ref: APNS (Configure push notifications) Important: Save a back up of your key in a secure place. It will not be presented again and cannot be retrieved later. A: For the new current Apple Developer site these are the steps: Certificates, Identifiers & Profiles > Keys > Click "+" > Check Apple Push Notifications service (APNs) Choose a name, then register it. It will give you an option to download the p8 file. A: May 2021 - The p8 The issue that I had was I couldn't find the way to create the .p8 file and all methods gave me .cer file instead. * *Head to your Apple developer account *Go to the keys section and click on the plus button (or click here): ⚠️ It is very important to select the keys section and NOT the certificate or identifiers. otherwise you will get the .cer file at last ‍♂️ *Select the Apple push notification service: ⚠️ Note that since it is very powerful certificate, it is very limited and you can not have much of these. So if you already created one, you will face something like this image and you should use that file or just revoke the old one. *Download the.p8 file and secure it somewhere. A: First login Apple developer a/c. Go to Keys option, click + button Than on next page, enter valid Name, check Push notification option and click, click continue, click download button, It will download .p8 file.
stackoverflow
{ "language": "en", "length": 380, "provenance": "stackexchange_0000F.jsonl.gz:893522", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631803" }
fe693a0c404ad70155afab270ff97c37131c6236
Stackoverflow Stackexchange Q: Security Error in angular 2 application routing on using browser authentication in the URL I am running into a problem with my angular 2 application on using the URL with browser authentication credentials. If I load the URL without the credentials, it works as expected. But if I trigger the URL in the format: https://username:password@[REST_OF_URL], the different page sections are not loading withe such errors being thrown in the console: EXCEPTION: Uncaught (in promise): SecurityError: The operation is insecure. I am currently checking it in FireFox version 52. I debugged, and the issue appears to be due to failure in the routing mechanism when authentication credentials are used. I followed the router event tracking as suggested here: How to detect a route change in Angular? The NavigationStart and RoutesRecognized events are triggered as expected with correct resolution of routes. After this, NavigationError is triggered with the error mentioned above: SecurityError: The operation is insecure. How shall I address this? Any known issues to address with routing when using authentication credentials?
Q: Security Error in angular 2 application routing on using browser authentication in the URL I am running into a problem with my angular 2 application on using the URL with browser authentication credentials. If I load the URL without the credentials, it works as expected. But if I trigger the URL in the format: https://username:password@[REST_OF_URL], the different page sections are not loading withe such errors being thrown in the console: EXCEPTION: Uncaught (in promise): SecurityError: The operation is insecure. I am currently checking it in FireFox version 52. I debugged, and the issue appears to be due to failure in the routing mechanism when authentication credentials are used. I followed the router event tracking as suggested here: How to detect a route change in Angular? The NavigationStart and RoutesRecognized events are triggered as expected with correct resolution of routes. After this, NavigationError is triggered with the error mentioned above: SecurityError: The operation is insecure. How shall I address this? Any known issues to address with routing when using authentication credentials?
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:893544", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631852" }
26b137c0fe642b7847d2016deddf4dda79bc14b9
Stackoverflow Stackexchange Q: Kotlin: Cast ArrayList to Array I am trying to split a string that is input by the user. My code looks similar to the following: val aList = Array(5, {Array<String>(2){ " " }}) aList[0] = ArrayList(input.nextLine().split(" ")) // `split` returns a List But this results in the following error: error: type inference failed. Expected type mismatch: inferred type is ArrayList<String!> but Array<String> was expected. After some digging around I found that the T! operator means T or T?. How can I cast ArrayList<String!> to Array<String>? A: ArrayList<T> and Array<T> are completely different types, so, formally speaking, you cannot just make a cast. You can, however, convert a List<T> to an Array<T> using .toTypedArray(): aList[0] = input.nextLine().split(" ").toTypedArray()
Q: Kotlin: Cast ArrayList to Array I am trying to split a string that is input by the user. My code looks similar to the following: val aList = Array(5, {Array<String>(2){ " " }}) aList[0] = ArrayList(input.nextLine().split(" ")) // `split` returns a List But this results in the following error: error: type inference failed. Expected type mismatch: inferred type is ArrayList<String!> but Array<String> was expected. After some digging around I found that the T! operator means T or T?. How can I cast ArrayList<String!> to Array<String>? A: ArrayList<T> and Array<T> are completely different types, so, formally speaking, you cannot just make a cast. You can, however, convert a List<T> to an Array<T> using .toTypedArray(): aList[0] = input.nextLine().split(" ").toTypedArray()
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:893546", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631859" }
e1c3813131d24437dc8fe8980c65dd8a6f91005f
Stackoverflow Stackexchange Q: Nested loops in angular 2 I want to display the data of this array: array = [ {nom: nom1, composants: [composant11, composant12]}, {nom: nom2, composants: [composant21, composant22]} ] I want to display it this way in a table: composant nom composant11 nom1 composant12 nom1 composant21 nom2 composant22 nom2 This is my code: <table> <tr> <th>Composant</th> <th>Nom</th> </tr> <template *ngFor="let item of array"> <template *ngFor="let composant of item.composants"> <tr> <td>{{composant.nom}}</td> <td>{{composant.code}}</td> </tr> </template> </template> </table> My browser is not showing anything. I wonder if really there is a way to do that in the template. Or if I should first transform the array in the component before displaying it. Any suggestion will be appreciated! A: Try this: rows = [ {nom: "nom1", composants: ["composant11", "composant12"]}, {nom: "nom2", composants: ["composant21", "composant22"]} ]; <table> <ng-container *ngFor="let row of rows"> <tr *ngFor="let composant of row.composants"> <td> {{ composant }} </td> <td> {{ row.nom }} </td> </tr> <ng-container> </table>
Q: Nested loops in angular 2 I want to display the data of this array: array = [ {nom: nom1, composants: [composant11, composant12]}, {nom: nom2, composants: [composant21, composant22]} ] I want to display it this way in a table: composant nom composant11 nom1 composant12 nom1 composant21 nom2 composant22 nom2 This is my code: <table> <tr> <th>Composant</th> <th>Nom</th> </tr> <template *ngFor="let item of array"> <template *ngFor="let composant of item.composants"> <tr> <td>{{composant.nom}}</td> <td>{{composant.code}}</td> </tr> </template> </template> </table> My browser is not showing anything. I wonder if really there is a way to do that in the template. Or if I should first transform the array in the component before displaying it. Any suggestion will be appreciated! A: Try this: rows = [ {nom: "nom1", composants: ["composant11", "composant12"]}, {nom: "nom2", composants: ["composant21", "composant22"]} ]; <table> <ng-container *ngFor="let row of rows"> <tr *ngFor="let composant of row.composants"> <td> {{ composant }} </td> <td> {{ row.nom }} </td> </tr> <ng-container> </table> A: Change code like below: <table> <tr><th>Composant</th> <th>Nom</th> </tr> <template *ngFor="let item of array"> <template *ngFor="let composant of item.composants"> <tr> <td>{{item.nom}}</td> <td>{{composant|json}}</td> </tr> </template> </template> </table> A: I use a bit of a different syntax that got the job done http://plnkr.co/edit/Z94BxYiu2UTU7h3oySui?p=preview <table> <tr> <th>Composant</th> <th>Nom</th> </tr> <template ngFor #item [ngForOf]="array"> <template ngFor #noo [ngForOf]="item.composants"> <tr> <td>{{noo}}</td> <td>{{item.nom}}</td> </tr> </template> </template> </table>
stackoverflow
{ "language": "en", "length": 216, "provenance": "stackexchange_0000F.jsonl.gz:893558", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631886" }
913566c954d9fdd0f7595755496daade873be9e1
Stackoverflow Stackexchange Q: ERROR for site owner: Invalid site key I created a reCAPTCHA key and disabled Verify the origin of reCAPTCHA solutions, yet I am still getting there error ERROR for site owner: Invalid site key. How do I fix this? A: Same here. It seems to work for me if I add at least one domain or localhost in the Domains list, but then uncheck the option under Domain Name Validation.
Q: ERROR for site owner: Invalid site key I created a reCAPTCHA key and disabled Verify the origin of reCAPTCHA solutions, yet I am still getting there error ERROR for site owner: Invalid site key. How do I fix this? A: Same here. It seems to work for me if I add at least one domain or localhost in the Domains list, but then uncheck the option under Domain Name Validation. A: Right so it appears the reCAPTCHA unverified keys simply don't work and they don't seem to give a shit about fixing it. Ended up just specifying the domains. A: This might not be the case, but what I encountered before, was that I used http://example.com instead of example.com. For me it worked after I removed "http://"
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:893570", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631918" }
f731dedf0469382b3fe3b7d7a106e6688ac59c38
Stackoverflow Stackexchange Q: Which layer should be responsible for Notification management in Android MVP? I'm sure that it shouldn't be handled by any View or Presenter coupled with Activity because they are not present when app is running in the background. Is it a good idea to treat notifications as another View with a singleton Presenter?
Q: Which layer should be responsible for Notification management in Android MVP? I'm sure that it shouldn't be handled by any View or Presenter coupled with Activity because they are not present when app is running in the background. Is it a good idea to treat notifications as another View with a singleton Presenter?
stackoverflow
{ "language": "en", "length": 54, "provenance": "stackexchange_0000F.jsonl.gz:893594", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44631990" }
1958368e91617f7d5bc01c1f555543401da83bd4
Stackoverflow Stackexchange Q: Converting large scientific number to long I've spend a long time now, trying to convert the number 1.2846202978398e+19 in java, without any luck. Currently what I'm trying to do (long)Double.parseDouble(hashes), however this gives 9223372036854775807, which is obviously incorrect. The actual number should look something like this 12855103593745000000. Using int val = new BigDecimal(stringValue).intValue(); returns -134589568 as it's unable to hold the result. Switching the code to long val = new BigDecimal(hashes).longValue(); gives me -5600541095311551616 which is also incorrect. I'm assuming this is happening due to the size of a double compared to a long. Any ideas? A: Did you try to use String.format : String result = String.format("%.0f", Double.parseDouble("1.2846202978398e+19")); System.out.println(result); Output 12846202978398000000 Edit Why you don't work with BigDecimal to do the arithmetic operations, for example : String str = "1.2846202978398e+19"; BigDecimal d = new BigDecimal(str).multiply(BigDecimal.TEN); // ^^^^^^^^------example of arithmetic operations System.out.println(String.format("%.0f", d)); System.out.println(String.format("%.0f", Double.parseDouble(str))); Output 128462029783980000000 12846202978398000000
Q: Converting large scientific number to long I've spend a long time now, trying to convert the number 1.2846202978398e+19 in java, without any luck. Currently what I'm trying to do (long)Double.parseDouble(hashes), however this gives 9223372036854775807, which is obviously incorrect. The actual number should look something like this 12855103593745000000. Using int val = new BigDecimal(stringValue).intValue(); returns -134589568 as it's unable to hold the result. Switching the code to long val = new BigDecimal(hashes).longValue(); gives me -5600541095311551616 which is also incorrect. I'm assuming this is happening due to the size of a double compared to a long. Any ideas? A: Did you try to use String.format : String result = String.format("%.0f", Double.parseDouble("1.2846202978398e+19")); System.out.println(result); Output 12846202978398000000 Edit Why you don't work with BigDecimal to do the arithmetic operations, for example : String str = "1.2846202978398e+19"; BigDecimal d = new BigDecimal(str).multiply(BigDecimal.TEN); // ^^^^^^^^------example of arithmetic operations System.out.println(String.format("%.0f", d)); System.out.println(String.format("%.0f", Double.parseDouble(str))); Output 128462029783980000000 12846202978398000000 A: Your value exceeds the maximum size of long. You can not use long in this situation. Try BigDecimal value = new BigDecimal("1.2846202978398e+19"); After that, you can call value.toBigInteger() or value.toBigIntegerExact() if needed. A: What about: System.out.println(new BigDecimal("1.2846202978398e+19").toBigInteger());
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:893606", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632014" }
48278867ba9f832afa3c558464139add397c0797
Stackoverflow Stackexchange Q: PyQtGraph opening then closing straight away I'm running some basic code from the documentation import pyqtgraph as pg import numpy as np x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title="Three plot curves") for i in range(3): plotWidget.plot(x, y[i], pen=(i,3)) But for some reason the window open then closes straight away, i just see a flicker of it. Is there some sort of function in which i can keep the window open? A: You can keep the window open by creating a QApplication at the beginning of the script and then calling its exec_() method at the end of your script, like this: import pyqtgraph as pg import numpy as np import sys from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) # Create QApplication *** x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title="Three plot curves") for i in range(3): plotWidget.plot(x, y[i], pen=(i, 3)) # Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): app.exec_() # Start QApplication event loop *** I put *** on the key lines.
Q: PyQtGraph opening then closing straight away I'm running some basic code from the documentation import pyqtgraph as pg import numpy as np x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title="Three plot curves") for i in range(3): plotWidget.plot(x, y[i], pen=(i,3)) But for some reason the window open then closes straight away, i just see a flicker of it. Is there some sort of function in which i can keep the window open? A: You can keep the window open by creating a QApplication at the beginning of the script and then calling its exec_() method at the end of your script, like this: import pyqtgraph as pg import numpy as np import sys from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) # Create QApplication *** x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title="Three plot curves") for i in range(3): plotWidget.plot(x, y[i], pen=(i, 3)) # Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): app.exec_() # Start QApplication event loop *** I put *** on the key lines. A: The problem is that the Python process finishes after the last iteration of the for loop and thus also terminates the widgets. You can use the -i switch in order to enter the interactive Python interpreter after executing the script which retains all objects that were instantiated during execution of the script: python -i /path/to/script.py Admittedly this is rather a workaround and pyqtgraph probably has a "native" way of achieving this (such as the show function from matplotlib.pyplot does it by default) however I couldn't find a similar function for pyqtgraph. A: To further a_guest answer - To enable see the graph in Pycharm goto: Run -> Edit Configurations -> Interpreter Options. Leave the -i there.
stackoverflow
{ "language": "en", "length": 302, "provenance": "stackexchange_0000F.jsonl.gz:893608", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632018" }
45c36e9bcc3915803d2128b97eb6ba4ceefe801a
Stackoverflow Stackexchange Q: Cannot set property XXX of undefined in TypeScript I want to initialize an interface in TypeScript. export interface TestGroup { "id": number; "type": TestType; "interval"?: number; } import {TestGroup} from "../../gen/api"; public functionConfig: TestGroup; . . . this.functionConfig.id = testGroup.functionTestConfig; I get this error: TypeError: Cannot set property 'id' of undefined Could you please help me? A: Your functionConfig has a type but it is actually undefined. So you need to initialize it: public functionConfig: TestGroup = {id: 0, type: 'YourTestTypeHere'}; or your default values for it Comment var activateOnWeekDay: Array<boolean> = [];
Q: Cannot set property XXX of undefined in TypeScript I want to initialize an interface in TypeScript. export interface TestGroup { "id": number; "type": TestType; "interval"?: number; } import {TestGroup} from "../../gen/api"; public functionConfig: TestGroup; . . . this.functionConfig.id = testGroup.functionTestConfig; I get this error: TypeError: Cannot set property 'id' of undefined Could you please help me? A: Your functionConfig has a type but it is actually undefined. So you need to initialize it: public functionConfig: TestGroup = {id: 0, type: 'YourTestTypeHere'}; or your default values for it Comment var activateOnWeekDay: Array<boolean> = []; A: You can fix it by initializing an empty object {}. export interface TestGroup { id: number; type: TestType; interval?: number; } import {TestGroup} from "../../gen/api"; public functionConfig: TestGroup = {}; <=====Assign empty object . . . this.functionConfig.id = testGroup.functionTestConfig;
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:893624", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632083" }
fee700282cd03ef546108257f9be5cf11896729a
Stackoverflow Stackexchange Q: How to remove a single data which is store in a single key in ionic storage? I am trying to make a note app with ionic, where I am using a storage plugin. I set a key like this: private note: note[] = []; constructor(private storage: Storage) { } addNote(note: note) { this.note.push(note); this.storage.set('note', this.note); } getNote() { return this.storage.get('note') .then( (note) => { this.note= note== null ? [] : note; return this.note.slice(); } ) } Where all the data is an array object, like this: (3) [Object, Object, Object] 0:Object 1:Object 2:Object length:3 I just want to remove a single array object inside this note array. I tried this.storage.remove(note[index]); but it did not work. A: * *get the value. *slice the exact object. *rewrite the new value to the storage. try something like storage.get('note').then((note) => { note.splice(index, 1); // i don't know what is index refer to storage.set('note', note); });
Q: How to remove a single data which is store in a single key in ionic storage? I am trying to make a note app with ionic, where I am using a storage plugin. I set a key like this: private note: note[] = []; constructor(private storage: Storage) { } addNote(note: note) { this.note.push(note); this.storage.set('note', this.note); } getNote() { return this.storage.get('note') .then( (note) => { this.note= note== null ? [] : note; return this.note.slice(); } ) } Where all the data is an array object, like this: (3) [Object, Object, Object] 0:Object 1:Object 2:Object length:3 I just want to remove a single array object inside this note array. I tried this.storage.remove(note[index]); but it did not work. A: * *get the value. *slice the exact object. *rewrite the new value to the storage. try something like storage.get('note').then((note) => { note.splice(index, 1); // i don't know what is index refer to storage.set('note', note); }); A: let index = note.indexOf(value); if(index > -1) { storage.get('note').then((note) => { note.splice(index, 1); storage.set('note', note); }); }
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:893626", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632087" }
42f3954d05c4c0f29a9aa2abbe8b9503b998a139
Stackoverflow Stackexchange Q: Packaging nuget package on VSTS 'Newtonsoft.Json' already has a dependency defined for 'NETStandard.Library' Packaging a build use Nuget Packager in VSTS and i get the error: [error]'Newtonsoft.Json' already has a dependency defined for 'NETStandard.Library'. Most of the hints that solves this involves updating nuget, but since I am building on Team Services I can't really do this. A: It seems that the nuget used by nuget packager is not the latest. After testing locally with latest nuget.exe everything worked so I added a new powershell release step. This solution is appropriate for VSTS, for TFS where you have access to the server I recommend upgrading nuget.exe on the server itself: This script downloads nuget.exe into the artifacts directory (and outputs the path to the nuget.exe so you can see where it is put.). I then altered the Nuget Packager build step to use the freshly downloaded nuget.exe.
Q: Packaging nuget package on VSTS 'Newtonsoft.Json' already has a dependency defined for 'NETStandard.Library' Packaging a build use Nuget Packager in VSTS and i get the error: [error]'Newtonsoft.Json' already has a dependency defined for 'NETStandard.Library'. Most of the hints that solves this involves updating nuget, but since I am building on Team Services I can't really do this. A: It seems that the nuget used by nuget packager is not the latest. After testing locally with latest nuget.exe everything worked so I added a new powershell release step. This solution is appropriate for VSTS, for TFS where you have access to the server I recommend upgrading nuget.exe on the server itself: This script downloads nuget.exe into the artifacts directory (and outputs the path to the nuget.exe so you can see where it is put.). I then altered the Nuget Packager build step to use the freshly downloaded nuget.exe. A: Had the same issue today. Using your own build agent If you are using your own build agents (rather than the hosted agent) you can manually update the version of NuGet to the latest version. In my case, this has resolved my problems. e.g. C:\agent\externals\nuget\nuget.exe Using the hosted agent It's a bit messy but you could just upload the latest nuget.exe into the repo and set the NuGet Packager to use this. A: To anyone getting this in 2018, Microsoft have created a new version of the NuGet task that fixes this issue. No need for powershell install steps. Change the NuGet task version in your build step version to 2.* This caused some breaking changes for me, that I resolved with the following advanced settings Nuget Restore Nuget Pack Nuget push
stackoverflow
{ "language": "en", "length": 281, "provenance": "stackexchange_0000F.jsonl.gz:893633", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632107" }
41e2e46f31f5d8b933f0e882d71d3a7b1128b92c
Stackoverflow Stackexchange Q: Are there conditional blocks in GNU Radio? I was wondering if there was a way to use If statements and such in Gnu Radio without having to go into the generated code. For example if you have a probe and if the value of said probe is 1, branch off to some blocks, and if the value of the probe is 0, branch off to another set of blocks. A: Don't use probes to inspect signals. That is broken by design; if you want some stream to depend on another stream, threshold the "controlling" one (so that it is either 0 or 1) and then multiply with the other.
Q: Are there conditional blocks in GNU Radio? I was wondering if there was a way to use If statements and such in Gnu Radio without having to go into the generated code. For example if you have a probe and if the value of said probe is 1, branch off to some blocks, and if the value of the probe is 0, branch off to another set of blocks. A: Don't use probes to inspect signals. That is broken by design; if you want some stream to depend on another stream, threshold the "controlling" one (so that it is either 0 or 1) and then multiply with the other.
stackoverflow
{ "language": "en", "length": 110, "provenance": "stackexchange_0000F.jsonl.gz:893655", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632167" }
f7050839dd2f27f00a5650686b4cc1036048854a
Stackoverflow Stackexchange Q: Compile python into binary - pypy performance I am looking to compile python source code into a binary. I generally use pypy for performance reasons (my application runs significantly faster using pypy). I found this answer from 2012 stating compiling pypy into binary isn't possible using any of the existing tools (e.g. pyinstaller). Compile PyPy to Exe. I wasn't quite able to follow what the top response was explaining as a solution. I am wondering: * *Is there now a reasonably easy way to compile python code to binary using pypy as the interpreter? *I don't actually need to use pypy, I just use it for the performance gains. Is there a reasonable way to avoid using pypy but still get similar performance gains? This would still need to support compiling to binary. As an additional note, I use the 2.7 syntax. A: you can take a look to nuitka ( http://nuitka.net/doc/user-manual.html) nuitka --standalone --recurse-on --python-version=2.7 main.py
Q: Compile python into binary - pypy performance I am looking to compile python source code into a binary. I generally use pypy for performance reasons (my application runs significantly faster using pypy). I found this answer from 2012 stating compiling pypy into binary isn't possible using any of the existing tools (e.g. pyinstaller). Compile PyPy to Exe. I wasn't quite able to follow what the top response was explaining as a solution. I am wondering: * *Is there now a reasonably easy way to compile python code to binary using pypy as the interpreter? *I don't actually need to use pypy, I just use it for the performance gains. Is there a reasonable way to avoid using pypy but still get similar performance gains? This would still need to support compiling to binary. As an additional note, I use the 2.7 syntax. A: you can take a look to nuitka ( http://nuitka.net/doc/user-manual.html) nuitka --standalone --recurse-on --python-version=2.7 main.py
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:893668", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632204" }
2207d0ed68cdf591278f3d65b0ef226ede6a69d5
Stackoverflow Stackexchange Q: Firebase - store currency type value I'm building exchange rate app and using Firebase as datastore. On previous version 1 did store rates' data in string and convert string to BigDecimal on Android device for calculation. Now, while I'm working on version 2 I decided to review code and make updates. I found solution to store rates' data in Integer type than convert back to Decimal/Double/Float. Flow: Backend Python -> dataTostore = int(currency rate value * 100) Android Java -> rateValue = dataToStore / 100.00 Any experience with this problem ? How to solve it OR using string-BigDecimal good enough ? Thanks. A: Storing monetary values in counts of the smallest denomination is a common practice. It ensures that you can always count full values and reduces the risk of rounding errors associated with floating point types. Whether an integer type is enough depends on the maximum value you want to store. Firebase Database internally supports signed 64-bit longs (-2^63 ... 2^63-1). Note that JavaScript uses 64-bit double values internally so some large integers (greater than 2^53) are not precisely representable and will lose precision.
Q: Firebase - store currency type value I'm building exchange rate app and using Firebase as datastore. On previous version 1 did store rates' data in string and convert string to BigDecimal on Android device for calculation. Now, while I'm working on version 2 I decided to review code and make updates. I found solution to store rates' data in Integer type than convert back to Decimal/Double/Float. Flow: Backend Python -> dataTostore = int(currency rate value * 100) Android Java -> rateValue = dataToStore / 100.00 Any experience with this problem ? How to solve it OR using string-BigDecimal good enough ? Thanks. A: Storing monetary values in counts of the smallest denomination is a common practice. It ensures that you can always count full values and reduces the risk of rounding errors associated with floating point types. Whether an integer type is enough depends on the maximum value you want to store. Firebase Database internally supports signed 64-bit longs (-2^63 ... 2^63-1). Note that JavaScript uses 64-bit double values internally so some large integers (greater than 2^53) are not precisely representable and will lose precision.
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:893687", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632272" }
e39ab5a836fd9227dae571a7fa1429a49ffd8dd8
Stackoverflow Stackexchange Q: How to install specific Java version using Homebrew? I am looking to install Java on Mac using Homebrew. This works fine using the command brew cask install java.This installs the latest stable version which is currently - 1.8.0_141 However how can I install a specific version for example 1.8.0_131. A: * *Install homebrew /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" *Update homebrew if already installed: brew update *allow brew to lookup versions brew tap homebrew/cask-versions *list available java versions brew search java Optional: to find out the minor version of java brew info --cask java8 *install java 8 (or any other version available) brew install --cask java8
Q: How to install specific Java version using Homebrew? I am looking to install Java on Mac using Homebrew. This works fine using the command brew cask install java.This installs the latest stable version which is currently - 1.8.0_141 However how can I install a specific version for example 1.8.0_131. A: * *Install homebrew /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" *Update homebrew if already installed: brew update *allow brew to lookup versions brew tap homebrew/cask-versions *list available java versions brew search java Optional: to find out the minor version of java brew info --cask java8 *install java 8 (or any other version available) brew install --cask java8 A: Raising Sean Breckenridge's comment as an answer to increase visibility: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew tap homebrew/cask-versions brew cask install homebrew/cask-versions/adoptopenjdk8 There is no longer cask named "java8". A: run brew update command make sure that brew is update to date. then check brew by following command... to make sure brew works fine brew doctor if its has any issue you have to fix that first ... Then if you want to install specific version run following command .. brew install java11 in my case it's java11 you can check java available version on java website. Then go for location /Library/Java/JavaVirtualMachines/openjdk-11.jdk and make sure jdk file is there... if there is not any folder just run the following command in terminal... sudo ln -sfn /usr/local/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk change the version after @11 according to your required jdk version. its gonna tell system about java runtime. you can check java version by following command. java --version
stackoverflow
{ "language": "en", "length": 262, "provenance": "stackexchange_0000F.jsonl.gz:893693", "question_score": "50", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632292" }
c24d82815f78079426c4dab3933fad4c76c5afc2
Stackoverflow Stackexchange Q: How do I specify an empty alt attribute in React/JSX? I'm trying to add an empty alt attribute to an img element in a react component like so function SomeImageComponent(props) { return <img src={props.imgSrc} alt="" />; } But when this is rendered to the DOM and I inspect it in dev tools I see a boolean type of attribute like this <img src="/path/to/cat.gif" alt /> When I then test this with VoiceOver it ignores the valueless alt attribute and reads out the path to the image. So how can I get react to render an empty string for the attribute value? A: Can we also add alt tags? By doing this, we can overcome Google & tools errors notifications <img src="foo.png" alt="foo"> <img src="bar.png" alt="bar">
Q: How do I specify an empty alt attribute in React/JSX? I'm trying to add an empty alt attribute to an img element in a react component like so function SomeImageComponent(props) { return <img src={props.imgSrc} alt="" />; } But when this is rendered to the DOM and I inspect it in dev tools I see a boolean type of attribute like this <img src="/path/to/cat.gif" alt /> When I then test this with VoiceOver it ignores the valueless alt attribute and reads out the path to the image. So how can I get react to render an empty string for the attribute value? A: Can we also add alt tags? By doing this, we can overcome Google & tools errors notifications <img src="foo.png" alt="foo"> <img src="bar.png" alt="bar"> A: alt and alt="" are the same thing. From the spec: Attributes can be specified in four different ways: Empty attribute syntax Just the attribute name. The value is implicitly the empty string. ... It's true that you typically see this with boolean attributes, but it's not limited to them. Example: var imgs = document.querySelectorAll("img"); var alt0 = imgs[0].getAttribute("alt"); var alt1 = imgs[1].getAttribute("alt"); console.log("0 (" + typeof alt0 + "): '" + alt0 + "'"); console.log("1 (" + typeof alt1 + "): '" + alt1 + "'"); <img src="foo.png" alt> <img src="bar.png" alt=""> It's worth noting that there are only a very few places where a blank alt is appropriate, but if you're supplying it at all, you're probably someone who's already aware of those places. :-)
stackoverflow
{ "language": "en", "length": 253, "provenance": "stackexchange_0000F.jsonl.gz:893709", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632354" }
70547d0b169ea4e7bcd5de965945b24be5444339
Stackoverflow Stackexchange Q: Direct url to the lastest details page of a build I try to set up a public display on our department floor to present the current status of the Jenkin's maintained projects. Therefore I'm cycling through a session of Jenkins web pages like the Blue Ocean Pipeline overview or the detailed build history of particular pipelines. Blue Ocean Pipeline Build History Additionally I would like to show the detailed page of the last build step of a pipeline. Build details of a pipeline Unfortunately the url that is been called uses the build number which I don't have on my script side. Is there a way within Blue Ocean to call for the last detailed build page in depended of the build number. * instead of .../blue/organizations/jenkins/Playground_RTM/detail/Playground_RTM/112/pipeline * something like that .../blue/organizations/jenkins/Playground_RTM/detail/Playground_RTM/last/pipeline Any ideas? A: I could not find a direct dynamic URL in the blue ocean for the last build. If somebody is looking for providing a quick access link, they could provide link to activity page for a particular branch in blue ocean. https://<host-name>/blue/organizations/jenkins/<job-name>/activity?branch=<branch-name> Or provide the last build page URL for classic Jenkins by using the lastBuild keyword.
Q: Direct url to the lastest details page of a build I try to set up a public display on our department floor to present the current status of the Jenkin's maintained projects. Therefore I'm cycling through a session of Jenkins web pages like the Blue Ocean Pipeline overview or the detailed build history of particular pipelines. Blue Ocean Pipeline Build History Additionally I would like to show the detailed page of the last build step of a pipeline. Build details of a pipeline Unfortunately the url that is been called uses the build number which I don't have on my script side. Is there a way within Blue Ocean to call for the last detailed build page in depended of the build number. * instead of .../blue/organizations/jenkins/Playground_RTM/detail/Playground_RTM/112/pipeline * something like that .../blue/organizations/jenkins/Playground_RTM/detail/Playground_RTM/last/pipeline Any ideas? A: I could not find a direct dynamic URL in the blue ocean for the last build. If somebody is looking for providing a quick access link, they could provide link to activity page for a particular branch in blue ocean. https://<host-name>/blue/organizations/jenkins/<job-name>/activity?branch=<branch-name> Or provide the last build page URL for classic Jenkins by using the lastBuild keyword.
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:893739", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632463" }
74ec08d1e357f2013c050285d3083cbebd470c09
Stackoverflow Stackexchange Q: Pyplot Legend only displaying one letter In a plot of wind resistance versus coefficients of drag, I have the following line defining the legend for the black dashed curve: ax.legend(perpendicular_plate,'Flat Perpendicular Plate') However, the legend is displaying only one letter of the name. I have used a legend many times, but never the ax.legend api...(top right corner) What am I doing incorrectly to get this result? A: You need to give the label(s) as an iterable of strings (i.e. a list or a tuple), even if there's only one label. So, this should work: ax.legend([perpendicular_plate],['Flat Perpendicular Plate']) So what's happening in your case is because strings are iterable in python, its iterating on your string, and taking just the first item of the string (F), and using that.
Q: Pyplot Legend only displaying one letter In a plot of wind resistance versus coefficients of drag, I have the following line defining the legend for the black dashed curve: ax.legend(perpendicular_plate,'Flat Perpendicular Plate') However, the legend is displaying only one letter of the name. I have used a legend many times, but never the ax.legend api...(top right corner) What am I doing incorrectly to get this result? A: You need to give the label(s) as an iterable of strings (i.e. a list or a tuple), even if there's only one label. So, this should work: ax.legend([perpendicular_plate],['Flat Perpendicular Plate']) So what's happening in your case is because strings are iterable in python, its iterating on your string, and taking just the first item of the string (F), and using that.
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:893776", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632571" }
83826f5f73e633504e4a8eca682fe430e7be3efd
Stackoverflow Stackexchange Q: WORDPRESS : cURL error 60: SSL certificate I'm currently building a Wordpress install under a debian server. I install PHP7, curl and Apache2 While I'm trying to install new extension I have this error message : cURL error 60: SSL certificate problem: self signed certificate in certificate chain I try to modify the php.ini with this, after reading some post treating similar issue : curl.cainfo = /etc/php7.0/cacert.pem But I'm still facing the problem even with restart apache. Any ideas ? Thanks in advance A: WordPress uses it's own CA bundle, located in WP/wp-includes/certificates. The CA bundle that was shipped with WordPress up until recently was outdated, as discussed in this issue: https://core.trac.wordpress.org/ticket/45807. Setting sslverify to false is not recommended, and instead you can download an updated version of the bundle, https://github.com/WordPress/WordPress/tree/master/wp-includes/certificates and replace it in the wordpress folder.
Q: WORDPRESS : cURL error 60: SSL certificate I'm currently building a Wordpress install under a debian server. I install PHP7, curl and Apache2 While I'm trying to install new extension I have this error message : cURL error 60: SSL certificate problem: self signed certificate in certificate chain I try to modify the php.ini with this, after reading some post treating similar issue : curl.cainfo = /etc/php7.0/cacert.pem But I'm still facing the problem even with restart apache. Any ideas ? Thanks in advance A: WordPress uses it's own CA bundle, located in WP/wp-includes/certificates. The CA bundle that was shipped with WordPress up until recently was outdated, as discussed in this issue: https://core.trac.wordpress.org/ticket/45807. Setting sslverify to false is not recommended, and instead you can download an updated version of the bundle, https://github.com/WordPress/WordPress/tree/master/wp-includes/certificates and replace it in the wordpress folder. A: Based on my recent experience, I believe that the message "self signed certificate in certificate chain" tells you the issue exactly - which is that whichever SSL site you are trying to access has a certificate in the chain that is not in the bunch that is referenced by cacert.pem. This makes sense because the error reports that it is a self-signed certificate.. i.e. It would never be included in the downloaded cacert.pem file. My solution was to get a Base64 encoded file containing the certificate chain of the site that I am trying to access. How to: Use a browser to access the site you are trying to access, click the certificate part of the address (usually to the left of the address box with a lock icon) and the click on whatever your interface supports to see the list of certificates in the chain. Manually export those certificates to a text file. Then append this text file with a text editor to the list of certificates (cacert.pem) that PHP is using for CURL actions. You mention WordPress.. WordPress v4.9.6 has a bundle of certificates that it specifically references when it is upgrading or installing plugins at ./WordPress Instance\wp-includes\certificates. My stop-gap solution was to append the text file above (containing the local self signed-certificate chain) to the ca-bundle.crt file that you will find in that location. One caveat - when you upgrade WordPress it will overwrite the ca-bundle.crt file, so you will have to re-add them - unless someone has a better solution..? A: In case someone come across same issue with their WordPress installation on Local Machine, by adding http_request_args filter did the trick for me <?php /** * Plugin Name: Local Dev CaFile * Plugin URI: https://stackoverflow.com/q/44632619/881743 * Description: Another solution for `SSL certificate problem: self signed certificate in certificate chain apache` error for your local development * Version: 1.0 * Author: John Doe * Author URI: https://stackoverflow.com/ * License: WTFPL */ add_filter( 'http_request_args', function ( $args ) { if ( getenv('WP_ENV') !== 'development' ) { return $args; } $args['sslcertificates'] = ini_get( 'curl.cainfo' ) ?? $args['sslcertificates']; return $args; }, 0, 1 ); and save it in path/to/wp-content/plugins/dev-plugin.php and activate the plugin from wp-admin, or optionally you could put it in your WPMU_PLUGIN_DIR. Hope that helps Cheers A: Disable SSL verification within your testing site. You can do this by adding this line into the file Appearance > Theme Editor > functions.php or /wp-content/themes/YOUR_THEME/functions.php: add_filter('https_ssl_verify', '__return_false'); Only add this on a testing site, never on a live site. A: set 'sslverify' to false to fix the cURL error 60: SSL certificate in WordPress wp_remote_get request. wp_remote_get($url, array('sslverify' => FALSE)); A: Download this file http://curl.haxx.se/ca/cacert.pem Use your file's location in openssl.cafile=c:/cacert.pem Reference - https://github.com/auth0/auth0-PHP#i-am-getting-curl-error-60-ssl-certificate-problem-self-signed-certificate-in-certificate-chain-on-windows A: Upgrade from wp-cli 2.4 => 2.5 helped me. (with installing this https://github.com/wp-cli/profile-command ) A: None of the answers here worked for me (and may not work for people using Let's Encrypt certificates on their servers). I found that recently (Sept 30,2021 ) the Let's Encrypt Cretificates expired DST Root CA X3. In addition to the curl error 60 I also had Rest API errors and inability to updated plugins in wordpress. It is possible to update these in the wordpress installation: The patch is available here and should be available with Wordpress 5.9 (December 2021) if not earlier: https://core.trac.wordpress.org/changeset/51883/trunk/src/wp-includes/certificates/ca-bundle.crt A: For Wordpress you can use like this: $url = "YOUR_ENDPOINT"; $args = array( 'headers' => array( 'Authorization' => 'HASH_HERE' ), 'sslverify' => FALSE, 'data' => array( 'campaign_id' => $campaign_id ) ); $response = wp_remote_get($url, $args); $body = wp_remote_retrieve_body($response); A: I had this issue recently because our network does the ssl proxy trick. We had a custom CA bundle that included our internal cert. That was bundled up in the /etc/pki folders, so I just symlinked to it: ln -s /etc/pki/tls/certs/ca-bundle.crt /wp-includes/certificates/ Now it stays updated whenever I update the system.
stackoverflow
{ "language": "en", "length": 786, "provenance": "stackexchange_0000F.jsonl.gz:893785", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632619" }
d8a13b20fa86329db31e19e9bc7dd57bc4538b1b
Stackoverflow Stackexchange Q: Why passing directly Promise.all to a .then function throws an error? I want to pass directly Promise.all to a .then function like: const test = [ Promise.resolve(), Promise.resolve(), Promise.resolve(), Promise.resolve() ]; Promise.resolve(test) // It's supposed to be an AJAX call .then(Promise.all) // Get an array of promises .then(console.log('End'); But this code throws an error Uncaught (in promise) TypeError: Promise.all called on non-object. When I remove the shorthand syntax, it works: Promise.resolve(test) .then(queries => Promise.all(queries)) .then(console.log('End')); So why a Promise.all passed directly to a .then throws an error ? (And why a console.log works fine ?) A: You need to bind Promise.all.bind(Promise) From ES2015 spec: The all function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor. Or better use it directly on array. const test = [ Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4) ] Promise.resolve(test) .then(Promise.all.bind(Promise)) .then(x => console.log(x)) Promise.all(test) .then(x => console.log(x))
Q: Why passing directly Promise.all to a .then function throws an error? I want to pass directly Promise.all to a .then function like: const test = [ Promise.resolve(), Promise.resolve(), Promise.resolve(), Promise.resolve() ]; Promise.resolve(test) // It's supposed to be an AJAX call .then(Promise.all) // Get an array of promises .then(console.log('End'); But this code throws an error Uncaught (in promise) TypeError: Promise.all called on non-object. When I remove the shorthand syntax, it works: Promise.resolve(test) .then(queries => Promise.all(queries)) .then(console.log('End')); So why a Promise.all passed directly to a .then throws an error ? (And why a console.log works fine ?) A: You need to bind Promise.all.bind(Promise) From ES2015 spec: The all function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor. Or better use it directly on array. const test = [ Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4) ] Promise.resolve(test) .then(Promise.all.bind(Promise)) .then(x => console.log(x)) Promise.all(test) .then(x => console.log(x))
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:893830", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632732" }
6655203f25fc049c8e07072e11c8a11f6894d4eb
Stackoverflow Stackexchange Q: HDF5 ImportError with PyTables for Windows I have installed the HDF5.dll and HDF5dll.dll in every directory I can think of--PYTHONPATH, USERPROFILE, within the PyTables site-packages folder--and I still return the following error: ImportError: Could not load any of ['hdf5.dll', 'hdf5dll.dll'], please ensure that it can be found in the system path Both of these are definitely within the system path and I still can't test PyTables without this message. Does anyone know how to solve this? Thank you! A: I have the same error in Python 3.6.0 (x64) under Windows 10. Anecdotally, based on Google searches, there are reports that tables is broken for Python 3 since June 2017, and apparently not fixed yet. However, I can import tables in Python 2.7.13 (x64) under Windows 10. So see if you can run your script under Python 2.7.
Q: HDF5 ImportError with PyTables for Windows I have installed the HDF5.dll and HDF5dll.dll in every directory I can think of--PYTHONPATH, USERPROFILE, within the PyTables site-packages folder--and I still return the following error: ImportError: Could not load any of ['hdf5.dll', 'hdf5dll.dll'], please ensure that it can be found in the system path Both of these are definitely within the system path and I still can't test PyTables without this message. Does anyone know how to solve this? Thank you! A: I have the same error in Python 3.6.0 (x64) under Windows 10. Anecdotally, based on Google searches, there are reports that tables is broken for Python 3 since June 2017, and apparently not fixed yet. However, I can import tables in Python 2.7.13 (x64) under Windows 10. So see if you can run your script under Python 2.7. A: I installed PyTables 3.5.2 from PyPI and got "Fail: ImportError: HDFStore requires PyTables, "Could not load any of ['hdf5.dll', 'hdf5dll.dll'], please ensure that it can be found in the system path" when trying to pandas.read_hdf(). Then I followed a link on https://www.pytables.org/usersguide/installation.html to Christoph Gohlkes page https://www.lfd.uci.edu/~gohlke/pythonlibs/ and downloaded tables‑3.5.2‑cp37‑cp37m‑win_amd64.whl from there. After a pip uninstall/install everything is working fine now. I still don't have a hdf5*.dll in my path ... A: I had no luck with the documentation and every single post I went thru. I kept getting: LINK : fatal error LNK1181: cannot open input file 'hdf5.lib' * Using Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] * USE_PKGCONFIG: False * Found HDF5 using system PATH ('C:\Users\<user>\AppData\Roaming\Python\Python39\site-packages\h5py') .. ERROR:: Could not find a local HDF5 installation. This did the trick, though: Copy hdf5.dll to C:\Users<user>\AppData\Roaming\Python\Python39\site-packages\tables Latest dll can be found here: https://pypi.org/project/h5py/#files: pip install -U C:\downloads\h5py-3.1.0-cp39-cp39-win_amd64.whl I did add h5py to my Windows Path at some stage. Ex: C:\Users<user>\AppData\Roaming\Python\Python39\site-packages\h5py But I can't confirm the impact of that.
stackoverflow
{ "language": "en", "length": 312, "provenance": "stackexchange_0000F.jsonl.gz:893859", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632832" }
8bebf6b8d40124aea4f155a96100f179336fc1aa
Stackoverflow Stackexchange Q: JSON to Scala code generation I have a JSON which is an output of another application, I want to make dynamic Scala code (*.scala file ) from this JSON (can not pre define class/bean as the JSON structure depends many other parameters). Is there any API available for this ? A: You can use something like below: http://json2caseclass.cleverapps.io/ https://www.reddit.com/r/scala/comments/36m951/json2caseclass_a_tool_to_generate_scala_case/
Q: JSON to Scala code generation I have a JSON which is an output of another application, I want to make dynamic Scala code (*.scala file ) from this JSON (can not pre define class/bean as the JSON structure depends many other parameters). Is there any API available for this ? A: You can use something like below: http://json2caseclass.cleverapps.io/ https://www.reddit.com/r/scala/comments/36m951/json2caseclass_a_tool_to_generate_scala_case/ A: Please have a look at this one: https://github.com/julianpeeters/case-class-generator Allows runtime data to serve as Scala case class definitions: Case classes defined and loaded at runtime Pseudo Type-Provider via type alias And also this one: Maybe this one is better, you need to generate some code first, and then call it. http://yefremov.net/blog/scala-code-generation/
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:893877", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632885" }
15c67b6ab61e7cf428834dd1f615353e3fc36fd6
Stackoverflow Stackexchange Q: Unit testing of Azure Data Factory I have a VSTS CI/CD pipeline that deploys the Azure Data Factory project setup in my local to the existing data factory in Azure platform. Is there a way I can unit test my project? I understand that there is a visual studio test task in build definition. How do I create a unit test project for ADF ? Any suggestions will help. A: No, there isn’t Unit test for ADF project, there is a user voice that you can vote: Unit Testing for ADF Projects
Q: Unit testing of Azure Data Factory I have a VSTS CI/CD pipeline that deploys the Azure Data Factory project setup in my local to the existing data factory in Azure platform. Is there a way I can unit test my project? I understand that there is a visual studio test task in build definition. How do I create a unit test project for ADF ? Any suggestions will help. A: No, there isn’t Unit test for ADF project, there is a user voice that you can vote: Unit Testing for ADF Projects A: I would suggest you to try to create unit test that utilizes the ADF LocalEnvironment assembly (instead of the Console application used in their demo try to create a Unit Test project) A: Maybe you can use "Test Plans" in Azure Devops if you are using CI/CD. A: While there isn't built in unit testing in ADF, Richard Ssinbank's example provides what appears to be a reasonable approach to implementing unit testing. Basically what he does is add parameters to the pipeline that allow dependency injection. The parameters start with the '_' and default to the normal dependencies that you would use in the pipeline for accessing external objects. This allows you to invoke the pipeline with stubs for testing.
stackoverflow
{ "language": "en", "length": 214, "provenance": "stackexchange_0000F.jsonl.gz:893883", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632904" }
9a9bba71d07854da74d5f3d2f4cf286fcc5eb968
Stackoverflow Stackexchange Q: Uncaught TypeError: this.function is not a function Hi this is my (shortcuted) example code: export class SolarSystemInfo { constructor() { this.test(); } // click on solar system clickSolarSystem() { $("body").on("click",".hex", function() { this.test(); }); } public test () { alert('test'); } } My problem is, that in constructor is test function called right, but in clickSolarSystem function after calling this.test() I get: Uncaught TypeError: this.test is not a function How I have to call test function in my function inner class? Thanks A: The context of this is lost when the callback function is being executed. To solve that you can use an arrow function: clickSolarSystem() { $("body").on("click",".hex", () => { this.test(); }); } Or you can use the bind method: clickSolarSystem() { $("body").on("click",".hex", function() { this.test(); }).bind(this); }
Q: Uncaught TypeError: this.function is not a function Hi this is my (shortcuted) example code: export class SolarSystemInfo { constructor() { this.test(); } // click on solar system clickSolarSystem() { $("body").on("click",".hex", function() { this.test(); }); } public test () { alert('test'); } } My problem is, that in constructor is test function called right, but in clickSolarSystem function after calling this.test() I get: Uncaught TypeError: this.test is not a function How I have to call test function in my function inner class? Thanks A: The context of this is lost when the callback function is being executed. To solve that you can use an arrow function: clickSolarSystem() { $("body").on("click",".hex", () => { this.test(); }); } Or you can use the bind method: clickSolarSystem() { $("body").on("click",".hex", function() { this.test(); }).bind(this); }
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:893891", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632946" }
9de51d1979eb5c126c70182af3861da5e5418059
Stackoverflow Stackexchange Q: Stop printing amount of the element in foreach loop powershell The foreach loop just keeps print out the amount of element in it as the following code. I want to stop it from printing it out. $ADSearch = New-Object System.DirectoryServices.DirectorySearcher $ADSearch.SearchRoot ="LDAP://$Domain" $ADSearch.SearchScope = "subtree" $ADSearch.PageSize = 100 $ADSearch.Filter = "(objectClass=$objectClass)" $properies =@("distinguishedName", "sAMAccountName", "mail", "lastLogonTimeStamp", "pwdLastSet", "accountExpires", "userAccountControl") foreach($pro in $properies) { $ADSearch.PropertiesToLoad.add($pro) } At the moment it gives: 0 1 2 3 4 5 6 A: Change this: foreach($pro in $properies) { $ADSearch.PropertiesToLoad.add($pro) } To: foreach($pro in $properies) { $ADSearch.PropertiesToLoad.add($pro)| out-null }
Q: Stop printing amount of the element in foreach loop powershell The foreach loop just keeps print out the amount of element in it as the following code. I want to stop it from printing it out. $ADSearch = New-Object System.DirectoryServices.DirectorySearcher $ADSearch.SearchRoot ="LDAP://$Domain" $ADSearch.SearchScope = "subtree" $ADSearch.PageSize = 100 $ADSearch.Filter = "(objectClass=$objectClass)" $properies =@("distinguishedName", "sAMAccountName", "mail", "lastLogonTimeStamp", "pwdLastSet", "accountExpires", "userAccountControl") foreach($pro in $properies) { $ADSearch.PropertiesToLoad.add($pro) } At the moment it gives: 0 1 2 3 4 5 6 A: Change this: foreach($pro in $properies) { $ADSearch.PropertiesToLoad.add($pro) } To: foreach($pro in $properies) { $ADSearch.PropertiesToLoad.add($pro)| out-null } A: Another solution is to [void] the "offending" line: foreach($pro in $properies) { [void]$ADSearch.PropertiesToLoad.add($pro) }
stackoverflow
{ "language": "en", "length": 110, "provenance": "stackexchange_0000F.jsonl.gz:893903", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44632969" }
22566a04de29575f94df0870eea766ae25a046ec
Stackoverflow Stackexchange Q: Steps to create a pocketsphinx wrapper in C# pocketsphinx has a SWIG interface "pocketsphinx.i" to generate wrappers in multiple language and one of them is C#. It is not clear how to run the swig command in Windows and how to use the resulting library in a NetCore C# project. What are the steps required to generate the wrapper library and use it in a C# NetCore app? A: There is an official swig-based wrapper in github, you can compile it for Linux with Make or for Microsoft with CMake: https://github.com/cmusphinx/pocketsphinx/tree/master/swig/csharp You can also check https://github.com/cmusphinx/pocketsphinx-unity-demo
Q: Steps to create a pocketsphinx wrapper in C# pocketsphinx has a SWIG interface "pocketsphinx.i" to generate wrappers in multiple language and one of them is C#. It is not clear how to run the swig command in Windows and how to use the resulting library in a NetCore C# project. What are the steps required to generate the wrapper library and use it in a C# NetCore app? A: There is an official swig-based wrapper in github, you can compile it for Linux with Make or for Microsoft with CMake: https://github.com/cmusphinx/pocketsphinx/tree/master/swig/csharp You can also check https://github.com/cmusphinx/pocketsphinx-unity-demo A: You can use SWIG to generate a C# wrapper for PocketSphinx lib, like it done here: https://github.com/cmusphinx/pocketsphinx-unity-demo/tree/master/Assets/Pocketsphinx
stackoverflow
{ "language": "en", "length": 115, "provenance": "stackexchange_0000F.jsonl.gz:893923", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44633038" }
1913c26cf5b6242e571e41b40c7057f41d9f4cfc
Stackoverflow Stackexchange Q: Simplest way to convert an optional String to an optional Int in Swift It seems to me there ought to be a simple way to do an optional conversion from a String to an Int in Swift but I can't figure it out. value is a String? and I need to return an Int?. Basically I want to do this, but without the boilerplate: return value != nil ? Int(value) : nil I tried this, which seems to fit with Swift's conventions and would be nice and concise, but it doesn't recognize the syntax: return Int?(value) A: You can use the flatMap() method of Optional: func foo(_ value: String?) -> Int? { return value.flatMap { Int($0) } } If value == nil then flatMap returns nil. Otherwise it evaluates Int($0) where $0 is the unwrapped value, and returns the result (which can be nil if the conversion fails): print(foo(nil) as Any) // nil print(foo("123") as Any) // Optional(123) print(foo("xyz") as Any) // nil
Q: Simplest way to convert an optional String to an optional Int in Swift It seems to me there ought to be a simple way to do an optional conversion from a String to an Int in Swift but I can't figure it out. value is a String? and I need to return an Int?. Basically I want to do this, but without the boilerplate: return value != nil ? Int(value) : nil I tried this, which seems to fit with Swift's conventions and would be nice and concise, but it doesn't recognize the syntax: return Int?(value) A: You can use the flatMap() method of Optional: func foo(_ value: String?) -> Int? { return value.flatMap { Int($0) } } If value == nil then flatMap returns nil. Otherwise it evaluates Int($0) where $0 is the unwrapped value, and returns the result (which can be nil if the conversion fails): print(foo(nil) as Any) // nil print(foo("123") as Any) // Optional(123) print(foo("xyz") as Any) // nil A: With String extension you shouldn't worry about string == nil extension String { func toInt() -> Int? { return Int(self) } } Usage: var nilString: String? print("".toInt()) // nil print(nilString?.toInt()) // nil print("123".toInt()) // Optional(123) A: You can use the nil coalescing operator ?? to unwrap the String? and use a default value "" that you know will produce nil: return Int(value ?? "") Another approach: Int initializer that takes String? From the comments: It's very odd to me that the initializer would not accept an optional and would just return nil if any nil were passed in. You can create your own initializer for Int that does just that: extension Int { init?(_ value: String?) { guard let value = value else { return nil } self.init(value) } } and now you can just do: var value: String? return Int(value)
stackoverflow
{ "language": "en", "length": 306, "provenance": "stackexchange_0000F.jsonl.gz:893954", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44633144" }
8961ee7bb3c80076e66c985f45888a8d5f752783
Stackoverflow Stackexchange Q: How to save the results analysed by the Chrome's Coverage tool? At a first glance it looks like very useful tool, however I cannot find any operation like Save or similar option. Does anyone know whether it is possible to save the results analysed by the Chrome's Coverage tool? Thanks A: As mentioned int the comments above, and in the marked duplicate, a feature request has been filed for this. In the meanwhile, as stated in the comments section of this page, one can use CoverageRange, FunctionCoverage or ScriptCoverage to gather the same data via Chrome's RDP.
Q: How to save the results analysed by the Chrome's Coverage tool? At a first glance it looks like very useful tool, however I cannot find any operation like Save or similar option. Does anyone know whether it is possible to save the results analysed by the Chrome's Coverage tool? Thanks A: As mentioned int the comments above, and in the marked duplicate, a feature request has been filed for this. In the meanwhile, as stated in the comments section of this page, one can use CoverageRange, FunctionCoverage or ScriptCoverage to gather the same data via Chrome's RDP.
stackoverflow
{ "language": "en", "length": 98, "provenance": "stackexchange_0000F.jsonl.gz:893992", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44633247" }