qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
1,986,872
I'm porting a Delphi 5 app to D2010, and I've got a bit of a problem. On one form is a TImage component with an OnMouseMove event that's supposed to update a label whenever the mouse is moved over the image. This worked just fine in the original app, but now the OnMouseMove event fires constantly whenever the mouse is over the image, whether it's moving or not, which causes the label to flicker horribly. Does anyone know what's causing this and how to fix it?
2009/12/31
[ "https://Stackoverflow.com/questions/1986872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
*My psychic debugging sense tells me that you are on Windows, the label is a tooltip window and you are updating on every mousemove.* In all seriousness, I've seen this exact thing with tooltip window when we switched to Vista. It seems that more recent versions of the Windows tooltip window somehow generate WM\_MOUSEMOVE messages when you update them. The only fix I could find was to only update the label when the text actually changes. So, If you aren't on windows, Ignore me. But if you are on Windows, try updating the label text only when it actually changes.
Since I couldn't add a comment I'm using the answer section to confirm this behavior change. I have a project that was developed in Delphi 2007 where the `OnMouseMove` event is only called when the mouse position changes. I found that with XE `OnMouseMove` is constantly being called for the same code. I don't know why since they're both triggered by `WM_MOUSEMOVE`. What I am doing till I get to the bottom of this is to compare the previous `XY` coordinates and exit if no change: ``` if ( x = ZoomRect.Right ) and ( y = ZoomRect.Bottom ) then exit ; ```
1,986,872
I'm porting a Delphi 5 app to D2010, and I've got a bit of a problem. On one form is a TImage component with an OnMouseMove event that's supposed to update a label whenever the mouse is moved over the image. This worked just fine in the original app, but now the OnMouseMove event fires constantly whenever the mouse is over the image, whether it's moving or not, which causes the label to flicker horribly. Does anyone know what's causing this and how to fix it?
2009/12/31
[ "https://Stackoverflow.com/questions/1986872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
Since I couldn't add a comment I'm using the answer section to confirm this behavior change. I have a project that was developed in Delphi 2007 where the `OnMouseMove` event is only called when the mouse position changes. I found that with XE `OnMouseMove` is constantly being called for the same code. I don't know why since they're both triggered by `WM_MOUSEMOVE`. What I am doing till I get to the bottom of this is to compare the previous `XY` coordinates and exit if no change: ``` if ( x = ZoomRect.Right ) and ( y = ZoomRect.Bottom ) then exit ; ```
Mason, I can't reproduce this is a new D2010 (Update 4 & 5) VCL Forms application on Windows XP SP2. Here's what I did: * File|New|VCL Forms Application * Dropped a TImage and TLabel on the form * Picked a random image out of the default images folder (GreenBar.bmp) for the TImage.Picture * Double-clicked the TImage.OnMouseMove event in the Object Inspector, and added the following code: ``` procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Label1.Caption := Format('X: %d Y: %d', [X, Y]); end; ``` * Ran the application (F9). The label showed "Label1" (the default caption, of course) until I first moved the mouse over the image. It then updated correctly to show the X and Y coordinates. As soon as I moved the mouse pointer out of the image, the label stopped updating. It appears to be something in your specific code, or something specific to the version of Windows you're using, and not Delphi 2010 itself.
32,123,637
I am using the below code to open a pdf file but its not working- ``` <iframe src="file:///C:\Users\Downloads\0895custbill08132015.pdf" style="height: 638px;" frameborder="0"></iframe> ``` For a google doc the below code is working fine, I am not sure what is required to open a locally saved doc. ``` <iframe src="http://docs.google.com/gview?url=http://webshire-aioopsss.com/pdfs/sample_contract.pdf&embedded=true" style="height:638px;" frameborder="0"></iframe> ```
2015/08/20
[ "https://Stackoverflow.com/questions/32123637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5248452/" ]
Most browsers won't let you open a locally stored file from a website for security reasons. Typically I will host the file on an IIS server and then retrieve it from there (which is what you're doing when you're retrieving it from googledoc).
You are using backslashes in your `src`. Please change them to slashes ``` <iframe src="file:///C:/Users/Downloads/0895custbill08132015.pdf" style="height: 638px;" frameborder="0"></iframe> ```
32,123,637
I am using the below code to open a pdf file but its not working- ``` <iframe src="file:///C:\Users\Downloads\0895custbill08132015.pdf" style="height: 638px;" frameborder="0"></iframe> ``` For a google doc the below code is working fine, I am not sure what is required to open a locally saved doc. ``` <iframe src="http://docs.google.com/gview?url=http://webshire-aioopsss.com/pdfs/sample_contract.pdf&embedded=true" style="height:638px;" frameborder="0"></iframe> ```
2015/08/20
[ "https://Stackoverflow.com/questions/32123637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5248452/" ]
Most browsers won't let you open a locally stored file from a website for security reasons. Typically I will host the file on an IIS server and then retrieve it from there (which is what you're doing when you're retrieving it from googledoc).
You can use var pdf = $('\<\object type="application/pdf">'); pdf.attr('data', "you pdf scr"); append it in your iframe..
390,186
Is there any admin setting in salesforce where child records are automatically deleted when the parent record is deleted when it is a lookup relationship?
2022/11/17
[ "https://salesforce.stackexchange.com/questions/390186", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/124977/" ]
You can use **Cascade Delete Feature**. > > Cascade Delete Feature Provides Lookup Relationships the same cascading delete functionality previously only available to Master Detail Relationships > > > However, be careful with it: > > Cascade delete, while useful for intentional deletions, increases the number of items that can be accidentally deleted without an admin noticing. In cases of accidental deletion, admins may miss the associated deletion of any child or grandchild objects, making it difficult to identify exactly which data was lost. > > > **Resources**: * <https://help.salesforce.com/s/articleView?id=000382017&type=1> * <https://help.salesforce.com/s/articleView?id=000380112&type=1&language=en_US> * <https://www.ownbackup.com/blog/how-cascade-delete-can-put-your-salesforce-data-at-risk/>
By using `cascade-delete` option you can able to delete the child records for lookup relationship and you need to contact salesforce support to enable `cascade-delete` feature. Delete this record also Available only if a custom object contains the lookup relationship, not if it’s contained by a standard object. However, the lookup object can be either standard or custom. Choose when the lookup field and its associated record are tightly coupled and you want to completely delete related data. > > WARNING Choosing Delete this record also can result in a > cascade-delete. A cascade-delete bypasses security and sharing > settings, which means users can delete records when the target lookup > record is deleted even if they don’t have access to the records. To > prevent records from being accidentally deleted, cascade-delete is > disabled by default. Contact Salesforce to get the cascade-delete > option enabled for your organization. Cascade-delete and its related > options aren’t available for lookup relationships to business hours, > network, lead, price book, product, or user objects. > > > Refer the [Considerations for Relationships](https://help.salesforce.com/s/articleView?id=sf.relationships_considerations.htm&type=5) Refer [Enable 'cascade delete on custom lookup relationships' feature](https://help.salesforce.com/s/articleView?id=000382017&type=1)
26,675,636
I have an ES index that contains parameter data from some scientific experiments. I have the following terms aggregation: ``` { "aggs": { "variables": { "terms": { "field": "value", "size": 100 } } }, "size": 0 } ``` Which returns a result like this: ``` { "took" : 3, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 9928, "max_score" : 0.0, "hits" : [ ] }, "aggregations" : { "variables" : { "buckets" : [ { "key" : "00", "doc_count" : 158 }, { "key" : "1", "doc_count" : 158 }, { "key" : "2", "doc_count" : 158 }, { "key" : "pressure", "doc_count" : 158 }, { "key" : "seconds", "doc_count" : 158 }, { "key" : "since", "doc_count" : 158 }, { "key" : "s", "doc_count" : 156 }, { "key" : "speed", "doc_count" : 127 }, { "key" : "sample", "doc_count" : 121 }, { "key" : "a", "doc_count" : 104 } ] } } } ``` What I want to do is tell ElasticSearch to ignore all keys with a length smaller than 5; e.g. to filter out `"key": "a"`, `"key": "s"`, and so on. Is this possible?
2014/10/31
[ "https://Stackoverflow.com/questions/26675636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321244/" ]
finally my error solveed but that is not exact solution what i wanted. what i did i have created one new project and took min sdk version is 15 bcoz action bar feature is present in 15 and further api .i think that feature introduced in 11 api .so i have taken new project with min sdk version and then no need of appcompat library now no error is coming... but i solved this problem by alternative solution but i also want answer of my question.
you have not added the appcompat\_v7 library properly check whether you have the library in Right click your project->properties->select android->appcompact lib (this library should be refered you are missing this one) So follow these Steps:- 1)Right-click your project and select Properties. 2)In the category panel on the left side of the dialog, select Android. 3)In the Library pane, click the Add button. 4)Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-appcompat. 5)In the properties window, click OK. If you don't see anything when you click Add button(step 3) ,then you should refer this link :-<https://developer.android.com/tools/support-library/setup.html> , in that link read adding libraries with resources and the follow the steps . OR ``` Make sure you have downloaded the Android Support Library using the SDK Manager. Create a library project and ensure the required JAR files are included in the project's build path: 1) Select File > Import. 2)Select Existing Android Code Into Workspace and click Next. Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to <sdk>/extras/android/support/v7/appcompat/. 3)Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat. 4) In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path. 5) Right-click the library project folder and select Build Path > Configure Build Path. 6) In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files. Uncheck Android Dependencies. 7) Click OK to complete the changes. ```
26,675,636
I have an ES index that contains parameter data from some scientific experiments. I have the following terms aggregation: ``` { "aggs": { "variables": { "terms": { "field": "value", "size": 100 } } }, "size": 0 } ``` Which returns a result like this: ``` { "took" : 3, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 9928, "max_score" : 0.0, "hits" : [ ] }, "aggregations" : { "variables" : { "buckets" : [ { "key" : "00", "doc_count" : 158 }, { "key" : "1", "doc_count" : 158 }, { "key" : "2", "doc_count" : 158 }, { "key" : "pressure", "doc_count" : 158 }, { "key" : "seconds", "doc_count" : 158 }, { "key" : "since", "doc_count" : 158 }, { "key" : "s", "doc_count" : 156 }, { "key" : "speed", "doc_count" : 127 }, { "key" : "sample", "doc_count" : 121 }, { "key" : "a", "doc_count" : 104 } ] } } } ``` What I want to do is tell ElasticSearch to ignore all keys with a length smaller than 5; e.g. to filter out `"key": "a"`, `"key": "s"`, and so on. Is this possible?
2014/10/31
[ "https://Stackoverflow.com/questions/26675636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321244/" ]
you have not added the appcompat\_v7 library properly check whether you have the library in Right click your project->properties->select android->appcompact lib (this library should be refered you are missing this one) So follow these Steps:- 1)Right-click your project and select Properties. 2)In the category panel on the left side of the dialog, select Android. 3)In the Library pane, click the Add button. 4)Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-appcompat. 5)In the properties window, click OK. If you don't see anything when you click Add button(step 3) ,then you should refer this link :-<https://developer.android.com/tools/support-library/setup.html> , in that link read adding libraries with resources and the follow the steps . OR ``` Make sure you have downloaded the Android Support Library using the SDK Manager. Create a library project and ensure the required JAR files are included in the project's build path: 1) Select File > Import. 2)Select Existing Android Code Into Workspace and click Next. Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to <sdk>/extras/android/support/v7/appcompat/. 3)Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat. 4) In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path. 5) Right-click the library project folder and select Build Path > Configure Build Path. 6) In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files. Uncheck Android Dependencies. 7) Click OK to complete the changes. ```
Yes this thing was coming to me too since too days. Go to your Project Properties and select that android api version that all things is downloaded with you in sdk for example in my case api 17 I choose and in sdk I have everything installed. ![Your project properties](https://i.stack.imgur.com/b9o55.png) I also did one thing extra in (image) bottom you can see check box (Is Library) I removed the refrence appcompat\_v7 and click Apply. After this everyting work with me like charm..... At last I come to the point that
26,675,636
I have an ES index that contains parameter data from some scientific experiments. I have the following terms aggregation: ``` { "aggs": { "variables": { "terms": { "field": "value", "size": 100 } } }, "size": 0 } ``` Which returns a result like this: ``` { "took" : 3, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 9928, "max_score" : 0.0, "hits" : [ ] }, "aggregations" : { "variables" : { "buckets" : [ { "key" : "00", "doc_count" : 158 }, { "key" : "1", "doc_count" : 158 }, { "key" : "2", "doc_count" : 158 }, { "key" : "pressure", "doc_count" : 158 }, { "key" : "seconds", "doc_count" : 158 }, { "key" : "since", "doc_count" : 158 }, { "key" : "s", "doc_count" : 156 }, { "key" : "speed", "doc_count" : 127 }, { "key" : "sample", "doc_count" : 121 }, { "key" : "a", "doc_count" : 104 } ] } } } ``` What I want to do is tell ElasticSearch to ignore all keys with a length smaller than 5; e.g. to filter out `"key": "a"`, `"key": "s"`, and so on. Is this possible?
2014/10/31
[ "https://Stackoverflow.com/questions/26675636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321244/" ]
you have not added the appcompat\_v7 library properly check whether you have the library in Right click your project->properties->select android->appcompact lib (this library should be refered you are missing this one) So follow these Steps:- 1)Right-click your project and select Properties. 2)In the category panel on the left side of the dialog, select Android. 3)In the Library pane, click the Add button. 4)Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-appcompat. 5)In the properties window, click OK. If you don't see anything when you click Add button(step 3) ,then you should refer this link :-<https://developer.android.com/tools/support-library/setup.html> , in that link read adding libraries with resources and the follow the steps . OR ``` Make sure you have downloaded the Android Support Library using the SDK Manager. Create a library project and ensure the required JAR files are included in the project's build path: 1) Select File > Import. 2)Select Existing Android Code Into Workspace and click Next. Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to <sdk>/extras/android/support/v7/appcompat/. 3)Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat. 4) In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path. 5) Right-click the library project folder and select Build Path > Configure Build Path. 6) In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files. Uncheck Android Dependencies. 7) Click OK to complete the changes. ```
appcompat\_v7 -> project.properties ,I have changed the target =19 to target=21 . Then refreshed the project ,that fixed my issue. Reference: [Got an error while building a project in new workspace](https://stackoverflow.com/questions/26623083/got-an-error-while-building-a-project-in-new-workspace)
26,675,636
I have an ES index that contains parameter data from some scientific experiments. I have the following terms aggregation: ``` { "aggs": { "variables": { "terms": { "field": "value", "size": 100 } } }, "size": 0 } ``` Which returns a result like this: ``` { "took" : 3, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 9928, "max_score" : 0.0, "hits" : [ ] }, "aggregations" : { "variables" : { "buckets" : [ { "key" : "00", "doc_count" : 158 }, { "key" : "1", "doc_count" : 158 }, { "key" : "2", "doc_count" : 158 }, { "key" : "pressure", "doc_count" : 158 }, { "key" : "seconds", "doc_count" : 158 }, { "key" : "since", "doc_count" : 158 }, { "key" : "s", "doc_count" : 156 }, { "key" : "speed", "doc_count" : 127 }, { "key" : "sample", "doc_count" : 121 }, { "key" : "a", "doc_count" : 104 } ] } } } ``` What I want to do is tell ElasticSearch to ignore all keys with a length smaller than 5; e.g. to filter out `"key": "a"`, `"key": "s"`, and so on. Is this possible?
2014/10/31
[ "https://Stackoverflow.com/questions/26675636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321244/" ]
finally my error solveed but that is not exact solution what i wanted. what i did i have created one new project and took min sdk version is 15 bcoz action bar feature is present in 15 and further api .i think that feature introduced in 11 api .so i have taken new project with min sdk version and then no need of appcompat library now no error is coming... but i solved this problem by alternative solution but i also want answer of my question.
Yes this thing was coming to me too since too days. Go to your Project Properties and select that android api version that all things is downloaded with you in sdk for example in my case api 17 I choose and in sdk I have everything installed. ![Your project properties](https://i.stack.imgur.com/b9o55.png) I also did one thing extra in (image) bottom you can see check box (Is Library) I removed the refrence appcompat\_v7 and click Apply. After this everyting work with me like charm..... At last I come to the point that
26,675,636
I have an ES index that contains parameter data from some scientific experiments. I have the following terms aggregation: ``` { "aggs": { "variables": { "terms": { "field": "value", "size": 100 } } }, "size": 0 } ``` Which returns a result like this: ``` { "took" : 3, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 9928, "max_score" : 0.0, "hits" : [ ] }, "aggregations" : { "variables" : { "buckets" : [ { "key" : "00", "doc_count" : 158 }, { "key" : "1", "doc_count" : 158 }, { "key" : "2", "doc_count" : 158 }, { "key" : "pressure", "doc_count" : 158 }, { "key" : "seconds", "doc_count" : 158 }, { "key" : "since", "doc_count" : 158 }, { "key" : "s", "doc_count" : 156 }, { "key" : "speed", "doc_count" : 127 }, { "key" : "sample", "doc_count" : 121 }, { "key" : "a", "doc_count" : 104 } ] } } } ``` What I want to do is tell ElasticSearch to ignore all keys with a length smaller than 5; e.g. to filter out `"key": "a"`, `"key": "s"`, and so on. Is this possible?
2014/10/31
[ "https://Stackoverflow.com/questions/26675636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321244/" ]
finally my error solveed but that is not exact solution what i wanted. what i did i have created one new project and took min sdk version is 15 bcoz action bar feature is present in 15 and further api .i think that feature introduced in 11 api .so i have taken new project with min sdk version and then no need of appcompat library now no error is coming... but i solved this problem by alternative solution but i also want answer of my question.
appcompat\_v7 -> project.properties ,I have changed the target =19 to target=21 . Then refreshed the project ,that fixed my issue. Reference: [Got an error while building a project in new workspace](https://stackoverflow.com/questions/26623083/got-an-error-while-building-a-project-in-new-workspace)
45,044,526
I'm trying to fix a CSV file that has a trailing `,\r\n` in it. No matter what I do, it simply doesn't do anything. I tried putting the expression in `[]` which makes it replace every single comma. That implies that the issue is that it can't match the newline character. I have saved the file with Windows line endings using Sublime Text, and have tried both variations of `\r\n`, `\n\r`, and just `\n`. ``` (Get-Content file.txt) | ForEach-Object { $_ -replace '\,\r\n', [System.Environmen t]::NewLine } | Set-Content file2.txt ``` I'm using PowerShell version 5.1.15063.413
2017/07/11
[ "https://Stackoverflow.com/questions/45044526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1142368/" ]
PowerShell turns out to be quite... *special*. `Get-Content` by default returns an array of strings. It finds all new line characters and uses them to split the input into said array. Meaning there are no new lines present for the regexp to match. A slight variation of this command using the `-Raw` parameter fixed my issue. ```powershell (Get-Content file.txt -Raw).replace(",`r`n", [System.Environment]::NewLine) | Set-Content file2.txt ```
Indeed, **[`Get-Content`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-content) by defaults reads and emits the input file's content *line by line*, with newlines of any flavor - CRLF, LF, CR - *stripped***. While the behavior may be *unfamiliar*, is *generally helpful* for processing files in the pipeline. As [your answer](https://stackoverflow.com/a/45044873/45375) shows, **`-Raw` can be used to read a file *in full*, as a *single, multi-line string* instead - which can offer great *performance benefits***. To give an example of the ***convenience* that *line-by-line* reading can provide**, combined with the regex-based [`-replace` operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Comparison_Operators#replacement-operator)'s ability to operate on *each element* of an input *array* (if your file has LF (`\n`) endings and you're selectively looking for rogue CRLF (`\r\n`) line endings preceded by `,`, that won't help, however): ```sh # Convenient, but can be made faster with -ReadCount 0 - see below. @(Get-Content file.txt) -replace ',$' | Set-Content file2.txt ``` Note: `@(...)`, the [array-subexpression operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#array-subexpression-operator--), is used to ensure that the `Get-Content` call also outputs an *array* even if the file happens to have just *one* line. Regex anchor `$` matches the end of each input string (line), in effect removing a *trailing `,`* from each line, *where present*. --- **[`Get-Content`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-content) performance notes**: As hinted at above, **`-Raw` is by far the fastest** way to **read a text file *in full*** - but by design **as a single, multiline string**. The default behavior, **line-by-line reading is slow**, not least because **PowerShell decorates *each output line* with metadata[1]** (in the case of `-Raw`, given that there's only *one* output string, that happens only *once*). However, you can **speed things up by reading lines *in batches* - arrays of lines of a given size - using the `-ReadCount` parameter**, in which case only each array, not the individual lines, are decorated. `-ReadCount 0` reads *all* lines, into a single array. Note: * **`-ReadCount` changes the streaming behavior *in the pipeline***: Each array is then sent *as a whole* through the pipeline, which **the receiving command needs to be plan for**, typically by performing its own enumeration of the array received, such as with a [`foreach` loop](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Foreach). * By contrast, using **`-ReadCount 0` in the context of an *expression*** results in *no* behavioral difference, which means that it can be used as a **simple performance optimization that requires no other parts of the expression to accommodate it**; using an expression with a `-replace` operation as an example: ```sh # Read all lines directly into an array, with -ReadCount 0, # instead of more slowly letting PowerShell stream the lines # (emit them one by one) and then collect them in an array for you. # The -replace operator then acts on each element of the array. (Get-Content -ReadCount 0 file.txt) -replace ',$' ``` Note: `@(...)` is *not* necessary in this case, because `-ReadCount 0` *always* emits an array, even for single-line files. A **better-performing line-by-line-processing alternative** - although it cannot directly be used as part of an *expression* - is to use the **[`-switch` statement](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Switch) with the `-File` parameter** - see [this answer](https://stackoverflow.com/a/48915223/45375) for details. --- [1] This metadata is provided in the form of [ETS (Extended Type System)](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_types.ps1xml) properties, which notably provide information about the line number and the path of the originating file. Pipe a `Get-Content` call to `| Format-List -Force` to see these properties. While this extra information can be helpful, the performance impact of attaching it is noticeable. Given that the information is often *not* needed, having a least an *opt-out* would be helpful: see [GitHub issue #7537](https://github.com/PowerShell/PowerShell/issues/7537).
55,876,067
For my program i am asking the user for a zip code. I am trying to make the program ask the user for their zip code again if the one they typed in isn't only numbers and is exactly 5 characters. It does ask for the zip code again if it isn't 5 characters, but it doesn't ask again if the user typed in something that isn't a number. For example if you typed in "8789" it wouldn't work, but if you typed in "8jkf0" it would work. I've tried switching my or to an and but that's about it. I couldn't think of anything else to try. I am very new to python. I use it in school and do it sometimes in my free time. ``` zipcode = input("What is your ZIP code? ") ziplen = len(zipcode) while not (char.isnumber() for char in zipcode) or not ziplen == 5: zipcode = input("What is your ZIP code? ") ziplen = len(zipcode) ``` I expected that the program would ask for the user's zipcode again if what they typed in wasn't only numbers and exactly 5 characters, but it only checks if it is exactly 5 characters.
2019/04/26
[ "https://Stackoverflow.com/questions/55876067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11418059/" ]
isnumeric checks the entire string, so it's just: ``` while not zipcode.isnumeric() or not len(zipcode) == 5: ... ```
You need to call the `all()` function to return the result of testing all the characters in `zipcode`. Your list comprehension produces a generator, which will always be truthy. And the correct function is `isdigit`, not `isnumber`. ``` while ziplen != 5 or not all(map(str.isdigit, zipcode)): ```
10,277,638
Is it possible to host a .NET 4 application under a .NET 2 site? For several reasons we have to run the main site on .NET 3.5, but there is an application written in entity framework 4, which hosted under the same domain/port. When I try to add an application under the site (using a different .net 4.0 application pool), i get an error stating duplicate content in web.config. I have searched the net for fixes, but none of them seems to be working for me. I am running a Windows Server 2008 R2 with IIS7.5 Any help would be appreciated.
2012/04/23
[ "https://Stackoverflow.com/questions/10277638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/622661/" ]
No, that's not possible. An assembly compiled against .NET 4.0 must be run inside CLR 4.0. It is possible the other way around: run an assembly compiled against .NET 2.0 inside CLR 4.0.
No, the nested application will not be able to set a seperate framework version. I would suggest changing the version on the main site to v4. I don't think you should experience problems running a 3.5 app on version 4. What are your reasons for running it in 3.5?
10,277,638
Is it possible to host a .NET 4 application under a .NET 2 site? For several reasons we have to run the main site on .NET 3.5, but there is an application written in entity framework 4, which hosted under the same domain/port. When I try to add an application under the site (using a different .net 4.0 application pool), i get an error stating duplicate content in web.config. I have searched the net for fixes, but none of them seems to be working for me. I am running a Windows Server 2008 R2 with IIS7.5 Any help would be appreciated.
2012/04/23
[ "https://Stackoverflow.com/questions/10277638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/622661/" ]
It is possible to fix, if you carefully read Microsoft's document, <http://msdn.microsoft.com/en-us/library/a99txfy5.aspx> and <http://www.asp.net/whitepapers/aspnet4/breaking-changes#0.1__Toc256770150>
No, the nested application will not be able to set a seperate framework version. I would suggest changing the version on the main site to v4. I don't think you should experience problems running a 3.5 app on version 4. What are your reasons for running it in 3.5?
10,277,638
Is it possible to host a .NET 4 application under a .NET 2 site? For several reasons we have to run the main site on .NET 3.5, but there is an application written in entity framework 4, which hosted under the same domain/port. When I try to add an application under the site (using a different .net 4.0 application pool), i get an error stating duplicate content in web.config. I have searched the net for fixes, but none of them seems to be working for me. I am running a Windows Server 2008 R2 with IIS7.5 Any help would be appreciated.
2012/04/23
[ "https://Stackoverflow.com/questions/10277638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/622661/" ]
It is possible to fix, if you carefully read Microsoft's document, <http://msdn.microsoft.com/en-us/library/a99txfy5.aspx> and <http://www.asp.net/whitepapers/aspnet4/breaking-changes#0.1__Toc256770150>
No, that's not possible. An assembly compiled against .NET 4.0 must be run inside CLR 4.0. It is possible the other way around: run an assembly compiled against .NET 2.0 inside CLR 4.0.
4,248,521
Let $A$ be a C$^\*$-algebra, $f$ a representation of $A$, $F$ the universal representation of $A$, and $g=f\circ F^{-1}$. For an ultraweakly continuous linear functional $w$ on $f(A)$, $w\circ g$ is bounded and hence according to a well-known theorem, is ultraweakly continuous linear functional on $F(A)$. My question: it results that g is ultraweakly continuous. How is its proof? Thank you for consideration.
2021/09/12
[ "https://math.stackexchange.com/questions/4248521", "https://math.stackexchange.com", "https://math.stackexchange.com/users/854737/" ]
Suppose $\{ w\_1, w\_2, \dots, w\_r \}$ is a basis of $W$. You can complete it to get a basis $\{ w\_1, \dots, w\_r, v\_{r+1}, \dots, v\_n \}$ of the whole space. The clases $\{ v\_{r+1} + W, \dots, v\_n + W \}$ are a basis of the quotient space (Why?) A proof of the dimension now follows easily. Since you ask for another proof. If you have studied First Isomorphism Theorem you can apply it to the map $\phi: V \to V\W$ where $\phi(x) = x + W$.
Let $\{w\_i\}$ be a basis for $W$ and extend by $\{v\_j\}$ to get a basis for $V$. Then you can show $\{v\_j + W\}$ is a basis for the quotient.
4,248,521
Let $A$ be a C$^\*$-algebra, $f$ a representation of $A$, $F$ the universal representation of $A$, and $g=f\circ F^{-1}$. For an ultraweakly continuous linear functional $w$ on $f(A)$, $w\circ g$ is bounded and hence according to a well-known theorem, is ultraweakly continuous linear functional on $F(A)$. My question: it results that g is ultraweakly continuous. How is its proof? Thank you for consideration.
2021/09/12
[ "https://math.stackexchange.com/questions/4248521", "https://math.stackexchange.com", "https://math.stackexchange.com/users/854737/" ]
Another proof that may be circular depending on how you proved the Rank-Nullity theorem is as follows: Let $\pi:V\to V/W$ be the canonical projection. Notice that it is linear and surjective and the kernel by definition is $W$ hence: $$\dim(V)=\dim(V/W)+\dim(W)$$ And your equality follows.
Let $\{w\_i\}$ be a basis for $W$ and extend by $\{v\_j\}$ to get a basis for $V$. Then you can show $\{v\_j + W\}$ is a basis for the quotient.
17,595,349
I have the following sql comparison using `IIF` keyword ``` DECLARE @a int, @b int SET @a = 10 SET @b = 20 BEGIN SELECT IIF( @a < @b, 'True', 'False') As Result END ``` However, on execution it gives an error ``` Incorrect syntax near '<' ``` What is causing this?
2013/07/11
[ "https://Stackoverflow.com/questions/17595349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544079/" ]
As mentioned in comments, `IIF` is a new function in SQL Server 2012+, so you'll have to use a `CASE` statement instead: ``` DECLARE @a int, @b int SET @a = 10 SET @b = 20 BEGIN SELECT CASE WHEN @a < @b THEN 'True' ELSE 'False' END As Result END ```
IIF was used in VBA, but not available in SQL Server until the 2012 release. use the SELECT CASE statement instead. ``` DECLARE @a int, @b int SET @a = 10 SET @b = 20 BEGIN SELECT CASE WHEN @a < @b THEN 'True' ELSE 'False' END As Result END ```
30,031,241
I have been looking around for a method to plot points outside a polygon's area(hexagon in my case). Here's the scenario that I want to achieve, I have a small hexagon located inside a big hexagon. The picture is as follows: ![Points outside the small hexagon](https://i.stack.imgur.com/kTMWl.jpg) In the picture, I created a small hexagon (whom area indicated in pale red) and generate a random points (three in my case) inside it using `inpolygon`. Problem arise when I want to plot points (red triangles) in big hexagon (indicated in pale purple) **without touching the small hexagon area**. I have look around the net for this simple solutions 3 days to no avail. **I would really appreciate any helps or guidance I could get**. Thank you so much! My code is as follows: ``` clear clc bighexagon = 20; smallhexagon = 4; axis_min = 0; axis_max = 40; axis([axis_min axis_max axis_min axis_max],'square'); hold on L = linspace(30,390,7); bhex_x = bighexagon * (1+cosd(L))'; bhex_y = bighexagon*(1+sind(L))'; L2 = linspace(30,390,7); shex_x = smallhexagon * (1+cosd(L2))'; shex_y = smallhexagon * (1+sind(L2))'; plot(bhex_x,bhex_y,'LineWidth',3); %---Move small hexagon into big hexagon shex_vertices_x2(:,1) = shex_x + 16; shex_vertices_y2(:,1) = shex_y + 16; plot(shex_vertices_x2(:,1),shex_vertices_y2(:,1),'--k','LineWidth',3); %---Plot points in small hexagon no = 3; point_x2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; point_y2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; inside = inpolygon(point_x2,point_y2,shex_vertices_x2,shex_vertices_y2); point_x2 = point_x2(inside); point_y2 = point_y2(inside); idx2 = randperm(length(point_x2)); point_x2 = point_x2(idx2(1:no)); point_y2 = point_y2(idx2(1:no)); plot(point_x2,point_y2,'ro','MarkerSize',1.5,'LineWidth',1, ... 'MarkerFaceColor','r'); %---Plot points in big hexagon no2 = 4; point_x = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; point_y = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; inside2 = inpolygon(point_x,point_y,bhex_x,bhex_y); point_x = point_x(inside2); point_y = point_y(inside2); idx = randperm(length(point_x)); point_x = point_x(idx(1:no2)); point_y = point_y(idx(1:no2)); plot(point_x,point_y,'g^','MarkerSize',3,'LineWidth',3, ... 'MarkerFaceColor','g'); ```
2015/05/04
[ "https://Stackoverflow.com/questions/30031241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4643715/" ]
**UPDATE** Thank to `Hoki`'s suggestion, I finally able to work it out. **Note that I change this part inside the code:** > > `validpoint = inpolygon(point_x,point_y,bhex_x,bhex_y) & ~inpolygon(point_x,point_y,shex_vertices_x2,shex_vertices_y2);` > > > Hopefully, this clear the confusions and would help other users as well. I would like to thank `Hoki` and `xenoclast` for their help. The code is as follows: ``` clear clc bighexagon = 20; smallhexagon = 4; axis_min = 0; axis_max = 40; axis([axis_min axis_max axis_min axis_max],'square'); hold on L = linspace(30,390,7); bhex_x = bighexagon * (1+cosd(L))'; bhex_y = bighexagon*(1+sind(L))'; L2 = linspace(30,390,7); shex_x = smallhexagon * (1+cosd(L2))'; shex_y = smallhexagon * (1+sind(L2))'; plot(bhex_x,bhex_y,'LineWidth',3); %---Move small hexagon into big hexagon shex_vertices_x2(:,1) = shex_x + 16; shex_vertices_y2(:,1) = shex_y + 16; plot(shex_vertices_x2(:,1),shex_vertices_y2(:,1),'--k','LineWidth',3); %---Plot points in small hexagon no = 3; point_x2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; point_y2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; inside = inpolygon(point_x2,point_y2,shex_vertices_x2,shex_vertices_y2); point_x2 = point_x2(inside); point_y2 = point_y2(inside); idx2 = randperm(length(point_x2)); point_x2 = point_x2(idx2(1:no)); point_y2 = point_y2(idx2(1:no)); plot(point_x2,point_y2,'ro','MarkerSize',1.5,'LineWidth',1, ... 'MarkerFaceColor','r'); %---Plot points in big hexagon no2 = 30; point_x = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; point_y = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; %---As per Hoki's suggestion, it ensure the points are outside the small hexagon validpoint = inpolygon(point_x,point_y,bhex_x,bhex_y) & ... ~inpolygon(point_x,point_y,shex_vertices_x2,shex_vertices_y2); point_x = point_x(validpoint); point_y = point_y(validpoint); idx = randperm(length(point_x)); point_x = point_x(idx(1:no2)); point_y = point_y(idx(1:no2)); plot(point_x,point_y,'g^','MarkerSize',3,'LineWidth',3, ... 'MarkerFaceColor','g'); ```
If your inner hexagon is defined by the vertices then you could use `inpolygon` ([link](http://uk.mathworks.com/help/matlab/ref/inpolygon.html)) to test whether a given point is inside it or not.
30,031,241
I have been looking around for a method to plot points outside a polygon's area(hexagon in my case). Here's the scenario that I want to achieve, I have a small hexagon located inside a big hexagon. The picture is as follows: ![Points outside the small hexagon](https://i.stack.imgur.com/kTMWl.jpg) In the picture, I created a small hexagon (whom area indicated in pale red) and generate a random points (three in my case) inside it using `inpolygon`. Problem arise when I want to plot points (red triangles) in big hexagon (indicated in pale purple) **without touching the small hexagon area**. I have look around the net for this simple solutions 3 days to no avail. **I would really appreciate any helps or guidance I could get**. Thank you so much! My code is as follows: ``` clear clc bighexagon = 20; smallhexagon = 4; axis_min = 0; axis_max = 40; axis([axis_min axis_max axis_min axis_max],'square'); hold on L = linspace(30,390,7); bhex_x = bighexagon * (1+cosd(L))'; bhex_y = bighexagon*(1+sind(L))'; L2 = linspace(30,390,7); shex_x = smallhexagon * (1+cosd(L2))'; shex_y = smallhexagon * (1+sind(L2))'; plot(bhex_x,bhex_y,'LineWidth',3); %---Move small hexagon into big hexagon shex_vertices_x2(:,1) = shex_x + 16; shex_vertices_y2(:,1) = shex_y + 16; plot(shex_vertices_x2(:,1),shex_vertices_y2(:,1),'--k','LineWidth',3); %---Plot points in small hexagon no = 3; point_x2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; point_y2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; inside = inpolygon(point_x2,point_y2,shex_vertices_x2,shex_vertices_y2); point_x2 = point_x2(inside); point_y2 = point_y2(inside); idx2 = randperm(length(point_x2)); point_x2 = point_x2(idx2(1:no)); point_y2 = point_y2(idx2(1:no)); plot(point_x2,point_y2,'ro','MarkerSize',1.5,'LineWidth',1, ... 'MarkerFaceColor','r'); %---Plot points in big hexagon no2 = 4; point_x = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; point_y = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; inside2 = inpolygon(point_x,point_y,bhex_x,bhex_y); point_x = point_x(inside2); point_y = point_y(inside2); idx = randperm(length(point_x)); point_x = point_x(idx(1:no2)); point_y = point_y(idx(1:no2)); plot(point_x,point_y,'g^','MarkerSize',3,'LineWidth',3, ... 'MarkerFaceColor','g'); ```
2015/05/04
[ "https://Stackoverflow.com/questions/30031241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4643715/" ]
**UPDATE** Thank to `Hoki`'s suggestion, I finally able to work it out. **Note that I change this part inside the code:** > > `validpoint = inpolygon(point_x,point_y,bhex_x,bhex_y) & ~inpolygon(point_x,point_y,shex_vertices_x2,shex_vertices_y2);` > > > Hopefully, this clear the confusions and would help other users as well. I would like to thank `Hoki` and `xenoclast` for their help. The code is as follows: ``` clear clc bighexagon = 20; smallhexagon = 4; axis_min = 0; axis_max = 40; axis([axis_min axis_max axis_min axis_max],'square'); hold on L = linspace(30,390,7); bhex_x = bighexagon * (1+cosd(L))'; bhex_y = bighexagon*(1+sind(L))'; L2 = linspace(30,390,7); shex_x = smallhexagon * (1+cosd(L2))'; shex_y = smallhexagon * (1+sind(L2))'; plot(bhex_x,bhex_y,'LineWidth',3); %---Move small hexagon into big hexagon shex_vertices_x2(:,1) = shex_x + 16; shex_vertices_y2(:,1) = shex_y + 16; plot(shex_vertices_x2(:,1),shex_vertices_y2(:,1),'--k','LineWidth',3); %---Plot points in small hexagon no = 3; point_x2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; point_y2 = (smallhexagon+20) - rand(1,9*no)*2*smallhexagon; inside = inpolygon(point_x2,point_y2,shex_vertices_x2,shex_vertices_y2); point_x2 = point_x2(inside); point_y2 = point_y2(inside); idx2 = randperm(length(point_x2)); point_x2 = point_x2(idx2(1:no)); point_y2 = point_y2(idx2(1:no)); plot(point_x2,point_y2,'ro','MarkerSize',1.5,'LineWidth',1, ... 'MarkerFaceColor','r'); %---Plot points in big hexagon no2 = 30; point_x = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; point_y = (bighexagon+20) - rand(1,9*no2)*2*bighexagon; %---As per Hoki's suggestion, it ensure the points are outside the small hexagon validpoint = inpolygon(point_x,point_y,bhex_x,bhex_y) & ... ~inpolygon(point_x,point_y,shex_vertices_x2,shex_vertices_y2); point_x = point_x(validpoint); point_y = point_y(validpoint); idx = randperm(length(point_x)); point_x = point_x(idx(1:no2)); point_y = point_y(idx(1:no2)); plot(point_x,point_y,'g^','MarkerSize',3,'LineWidth',3, ... 'MarkerFaceColor','g'); ```
Pls check by adding following two lines after `inside2 = inpolygon(point_x,point_y,bhex_x,bhex_y);` ``` in1 = inpolygon(point_x,point_y,shex_vertices_x2,shex_vertices_y2); inside2= logical(inside2-in1); ```
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
This is a sign of much bigger problem to come. > > The LogonUserIdentity property exposes the properties and methods of the WindowsIdentity object **for the currently connected user to Microsoft Internet Information Services (IIS)**. The instance of the WindowsIdentity class that is exposed by LogonUserIdentity tracks the IIS request token and provides easy access to this token for the current HTTP request being processed inside of ASP.NET. **An instance of the WindowsIdentity class is automatically created so it does not need to be constructed to in order to gain access to its methods and properties**. > > > [Source](https://msdn.microsoft.com/en-us/library/system.web.httprequest.logonuseridentity(v=vs.110).aspx#Anchor_2) ***(emphasis mine)*** > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > > You can't. Not in a unit test as IIS is not available. Avoid tightly coupling your code to untestable code you cannot control like `HttpContext` and most of `System.Web` namespace. Instead, encapsulate them behind abstraction you control and can mock.
You can mock the context as shown here ``` var requestMock = new Mock<HttpRequestBase>(); var contextMock = new Mock<HttpContextBase>(); var mockIIdentity = new Mock<IIdentity>(); mockIIdentity.SetupGet(x => x.Name).Returns("MyName"); WindowsIdentity windowsIdentity = mockIIdentity.Object as WindowsIdentity; requestMock.Setup(x => x.LogonUserIdentity).Returns(windowsIdentity); contextMock.Setup(x => x.Request).Returns(requestMock.Object); yourControllerInstance.ControllerContext new ControllerContext(contextMock.Object, new RouteData(), yourControllerInstance) ``` I have also a test helper that I wrote, you can find it in Github and try using it, you can modify it to incorporate the above setup <https://github.com/danielhunex/TestHelper>
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
This is a sign of much bigger problem to come. > > The LogonUserIdentity property exposes the properties and methods of the WindowsIdentity object **for the currently connected user to Microsoft Internet Information Services (IIS)**. The instance of the WindowsIdentity class that is exposed by LogonUserIdentity tracks the IIS request token and provides easy access to this token for the current HTTP request being processed inside of ASP.NET. **An instance of the WindowsIdentity class is automatically created so it does not need to be constructed to in order to gain access to its methods and properties**. > > > [Source](https://msdn.microsoft.com/en-us/library/system.web.httprequest.logonuseridentity(v=vs.110).aspx#Anchor_2) ***(emphasis mine)*** > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > > You can't. Not in a unit test as IIS is not available. Avoid tightly coupling your code to untestable code you cannot control like `HttpContext` and most of `System.Web` namespace. Instead, encapsulate them behind abstraction you control and can mock.
You can mock it using (System.Web.Fakes) like this: ShimHttpRequest.AllInstances.LogonUserIdentityGet = (a) => { return WindowsIdentity.GetCurrent(); };
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
This is a sign of much bigger problem to come. > > The LogonUserIdentity property exposes the properties and methods of the WindowsIdentity object **for the currently connected user to Microsoft Internet Information Services (IIS)**. The instance of the WindowsIdentity class that is exposed by LogonUserIdentity tracks the IIS request token and provides easy access to this token for the current HTTP request being processed inside of ASP.NET. **An instance of the WindowsIdentity class is automatically created so it does not need to be constructed to in order to gain access to its methods and properties**. > > > [Source](https://msdn.microsoft.com/en-us/library/system.web.httprequest.logonuseridentity(v=vs.110).aspx#Anchor_2) ***(emphasis mine)*** > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > > You can't. Not in a unit test as IIS is not available. Avoid tightly coupling your code to untestable code you cannot control like `HttpContext` and most of `System.Web` namespace. Instead, encapsulate them behind abstraction you control and can mock.
Not really the best mock, but sometimes you're trapped. In this solution you must handle locally logged user (johndoe) on controller and/or in your db. But works. ``` var mockRequest = new HttpRequest("", "http://tempuri.org", ""); HttpContext.Current = new HttpContext( mockRequest, new HttpResponse(new StringWriter()) ); mockRequest.GetType().InvokeMember( "_logonUserIdentity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance, System.Type.DefaultBinder, mockRequest, new object[] { WindowsIdentity.GetCurrent() } ); ```
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
I spent a lot of time trying to mock HttpContext or HttpContextBase, then trying to shim with fakes WindowsIdentity class or HttpRequest.LogonUserIdentity property. Nothing works - you don't need completely mocked HttpContext because you want see real responses, not your mock set ups returned. Shims are just not generating for WindowsIdentity class ("due to internal limitations") and for LogonUserIdentity property (no reason given in fakes messages, it's just not there). The best approach how to get testable HttpContext with request and response is described here: <http://jonlanceley.blogspot.com/2015/08/unit-testing-part-2-faking-httpcontext.html> I was able to override LogonUserIdentity property in my fake request wrapper and set there whatever I need.
You can mock the context as shown here ``` var requestMock = new Mock<HttpRequestBase>(); var contextMock = new Mock<HttpContextBase>(); var mockIIdentity = new Mock<IIdentity>(); mockIIdentity.SetupGet(x => x.Name).Returns("MyName"); WindowsIdentity windowsIdentity = mockIIdentity.Object as WindowsIdentity; requestMock.Setup(x => x.LogonUserIdentity).Returns(windowsIdentity); contextMock.Setup(x => x.Request).Returns(requestMock.Object); yourControllerInstance.ControllerContext new ControllerContext(contextMock.Object, new RouteData(), yourControllerInstance) ``` I have also a test helper that I wrote, you can find it in Github and try using it, you can modify it to incorporate the above setup <https://github.com/danielhunex/TestHelper>
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
Not really the best mock, but sometimes you're trapped. In this solution you must handle locally logged user (johndoe) on controller and/or in your db. But works. ``` var mockRequest = new HttpRequest("", "http://tempuri.org", ""); HttpContext.Current = new HttpContext( mockRequest, new HttpResponse(new StringWriter()) ); mockRequest.GetType().InvokeMember( "_logonUserIdentity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance, System.Type.DefaultBinder, mockRequest, new object[] { WindowsIdentity.GetCurrent() } ); ```
You can mock the context as shown here ``` var requestMock = new Mock<HttpRequestBase>(); var contextMock = new Mock<HttpContextBase>(); var mockIIdentity = new Mock<IIdentity>(); mockIIdentity.SetupGet(x => x.Name).Returns("MyName"); WindowsIdentity windowsIdentity = mockIIdentity.Object as WindowsIdentity; requestMock.Setup(x => x.LogonUserIdentity).Returns(windowsIdentity); contextMock.Setup(x => x.Request).Returns(requestMock.Object); yourControllerInstance.ControllerContext new ControllerContext(contextMock.Object, new RouteData(), yourControllerInstance) ``` I have also a test helper that I wrote, you can find it in Github and try using it, you can modify it to incorporate the above setup <https://github.com/danielhunex/TestHelper>
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
I spent a lot of time trying to mock HttpContext or HttpContextBase, then trying to shim with fakes WindowsIdentity class or HttpRequest.LogonUserIdentity property. Nothing works - you don't need completely mocked HttpContext because you want see real responses, not your mock set ups returned. Shims are just not generating for WindowsIdentity class ("due to internal limitations") and for LogonUserIdentity property (no reason given in fakes messages, it's just not there). The best approach how to get testable HttpContext with request and response is described here: <http://jonlanceley.blogspot.com/2015/08/unit-testing-part-2-faking-httpcontext.html> I was able to override LogonUserIdentity property in my fake request wrapper and set there whatever I need.
You can mock it using (System.Web.Fakes) like this: ShimHttpRequest.AllInstances.LogonUserIdentityGet = (a) => { return WindowsIdentity.GetCurrent(); };
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
Not really the best mock, but sometimes you're trapped. In this solution you must handle locally logged user (johndoe) on controller and/or in your db. But works. ``` var mockRequest = new HttpRequest("", "http://tempuri.org", ""); HttpContext.Current = new HttpContext( mockRequest, new HttpResponse(new StringWriter()) ); mockRequest.GetType().InvokeMember( "_logonUserIdentity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance, System.Type.DefaultBinder, mockRequest, new object[] { WindowsIdentity.GetCurrent() } ); ```
You can mock it using (System.Web.Fakes) like this: ShimHttpRequest.AllInstances.LogonUserIdentityGet = (a) => { return WindowsIdentity.GetCurrent(); };
51,565,544
I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name` The error that I get is because `LogonUserIdentity` is null. I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null: ``` HttpContext.Current = new HttpContext( new HttpRequest("", "http://localhost:8609", ""), new HttpResponse(new StringWriter()) ); ``` > > How can I assign a value to `LogonUserIdentity` so that I can test my function? > > >
2018/07/27
[ "https://Stackoverflow.com/questions/51565544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113839/" ]
I spent a lot of time trying to mock HttpContext or HttpContextBase, then trying to shim with fakes WindowsIdentity class or HttpRequest.LogonUserIdentity property. Nothing works - you don't need completely mocked HttpContext because you want see real responses, not your mock set ups returned. Shims are just not generating for WindowsIdentity class ("due to internal limitations") and for LogonUserIdentity property (no reason given in fakes messages, it's just not there). The best approach how to get testable HttpContext with request and response is described here: <http://jonlanceley.blogspot.com/2015/08/unit-testing-part-2-faking-httpcontext.html> I was able to override LogonUserIdentity property in my fake request wrapper and set there whatever I need.
Not really the best mock, but sometimes you're trapped. In this solution you must handle locally logged user (johndoe) on controller and/or in your db. But works. ``` var mockRequest = new HttpRequest("", "http://tempuri.org", ""); HttpContext.Current = new HttpContext( mockRequest, new HttpResponse(new StringWriter()) ); mockRequest.GetType().InvokeMember( "_logonUserIdentity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance, System.Type.DefaultBinder, mockRequest, new object[] { WindowsIdentity.GetCurrent() } ); ```
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
Try the following: ``` javac file1.java file2.java ```
Here is another example, for compiling a java file in a nested directory. I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see '[gradle: java quickstart](https://docs.gradle.org/1.11/userguide/tutorial_java_projects.html)' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar. **Note:** You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart' ``` % mkdir -p temp/classes % curl --get \ http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \ --output commons-collections-3.2.2.jar % javac -g -classpath commons-collections-3.2.2.jar \ -sourcepath src/main/java -d temp/classes \ src/main/java/org/gradle/Person.java % jar cf my_example.jar -C temp/classes org/gradle/Person.class % jar tvf my_example.jar 0 Wed Jun 07 14:11:56 CEST 2017 META-INF/ 69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class ```
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
Try the following: ``` javac file1.java file2.java ```
OR you could just use `javac file1.java` and then also use `javac file2.java` afterwards.
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
Try the following: ``` javac file1.java file2.java ```
1.[use wildcard](https://i.stack.imgur.com/lln2q.png) 2.[use options](https://i.stack.imgur.com/57O6G.png) 3.<https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html>
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
or you can use the following to compile the all java source files in current directory.. ``` javac *.java ```
Here is another example, for compiling a java file in a nested directory. I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see '[gradle: java quickstart](https://docs.gradle.org/1.11/userguide/tutorial_java_projects.html)' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar. **Note:** You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart' ``` % mkdir -p temp/classes % curl --get \ http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \ --output commons-collections-3.2.2.jar % javac -g -classpath commons-collections-3.2.2.jar \ -sourcepath src/main/java -d temp/classes \ src/main/java/org/gradle/Person.java % jar cf my_example.jar -C temp/classes org/gradle/Person.class % jar tvf my_example.jar 0 Wed Jun 07 14:11:56 CEST 2017 META-INF/ 69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class ```
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
or you can use the following to compile the all java source files in current directory.. ``` javac *.java ```
OR you could just use `javac file1.java` and then also use `javac file2.java` afterwards.
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
or you can use the following to compile the all java source files in current directory.. ``` javac *.java ```
1.[use wildcard](https://i.stack.imgur.com/lln2q.png) 2.[use options](https://i.stack.imgur.com/57O6G.png) 3.<https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html>
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
Here is another example, for compiling a java file in a nested directory. I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see '[gradle: java quickstart](https://docs.gradle.org/1.11/userguide/tutorial_java_projects.html)' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar. **Note:** You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart' ``` % mkdir -p temp/classes % curl --get \ http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \ --output commons-collections-3.2.2.jar % javac -g -classpath commons-collections-3.2.2.jar \ -sourcepath src/main/java -d temp/classes \ src/main/java/org/gradle/Person.java % jar cf my_example.jar -C temp/classes org/gradle/Person.class % jar tvf my_example.jar 0 Wed Jun 07 14:11:56 CEST 2017 META-INF/ 69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class ```
OR you could just use `javac file1.java` and then also use `javac file2.java` afterwards.
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
Here is another example, for compiling a java file in a nested directory. I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see '[gradle: java quickstart](https://docs.gradle.org/1.11/userguide/tutorial_java_projects.html)' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar. **Note:** You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart' ``` % mkdir -p temp/classes % curl --get \ http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \ --output commons-collections-3.2.2.jar % javac -g -classpath commons-collections-3.2.2.jar \ -sourcepath src/main/java -d temp/classes \ src/main/java/org/gradle/Person.java % jar cf my_example.jar -C temp/classes org/gradle/Person.class % jar tvf my_example.jar 0 Wed Jun 07 14:11:56 CEST 2017 META-INF/ 69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class ```
1.[use wildcard](https://i.stack.imgur.com/lln2q.png) 2.[use options](https://i.stack.imgur.com/57O6G.png) 3.<https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html>
4,800,781
I know running `javac file1.java` produces `file1.class` if `file1.java` is the only source file, then I can just say `java file1` to run it. However, if I have 2 source files, `file1.java` and `file2.java`, then how do I build the program?
2011/01/26
[ "https://Stackoverflow.com/questions/4800781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590015/" ]
1.[use wildcard](https://i.stack.imgur.com/lln2q.png) 2.[use options](https://i.stack.imgur.com/57O6G.png) 3.<https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html>
OR you could just use `javac file1.java` and then also use `javac file2.java` afterwards.
1,018,338
Hopefully this example will illustrate my point better than simply trying to explain it: I'm using one of the many jQuery watermark plugins. To attach a watermark to a textbox, the syntax is: ``` $(document).ready(function(){ $("#item_description").watermark("Description"); }); ``` This works wonderfully if I have a page that already contains a textbox with id = item\_description. However, if I try to do any ajaxy-type stuff by loading up a partial view containing that textbox on a button click, then `$(document).ready()` has already been called and the watermark is not applied. I tried putting a seperate `$(document).ready()` inside of the partial view, but it looks like rails (?) strips out any `<script>` blocks when it renders the page, meaning that it still never gets called. Is there an easy way to do this? Am I just missing something obvious? **Edit**: I'm using the [jQuery Colorbox](http://colorpowered.com/colorbox/) plugin to load up the partial view inside of a lightbox (via `$(.colorbox).colorbox();`) -- I'm not actually doing the ajax request myself. If I'm understanding the answers so far, the best way might be to use the callback functionality of the plugin to execute any javascript I need inside of the partial. **Working Example**: Based on the feedback, I was able to get this working using colorbox by simply changing the colorbox call to be: ``` $(".colorbox").colorbox({}, function(){ $(".description").watermark("Description"); //Changed to a class }); ```
2009/06/19
[ "https://Stackoverflow.com/questions/1018338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
Why must it be in `$(document).ready`? You already have javascript loading the ajax, so you can activate `$("#item_description").watermark("Description");` on the callback.
From the ajax, just make the call directly without wrapping it inside `$(document).ready()` ``` $("#item_description").watermark("Description"); ```
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
Are you probably using Composer v2? When I use the given JSON in my local environment using Composer v1, it tells me: > > Deprecation warning: Your package name vendor\_name/PhpProjec is invalid, it should not contain uppercase characters. We suggest using vendor\_name/php-projec instead. Make sure you fix this as Composer 2.0 will error. > > > The error message you've provided does not occur on my system. If you are still facing problems after using another package name, please share more details
composer is case sensitive from v1.9 onwards... so change "PhpProject" to "phpproject" ``` { "name": "vendor_name/phpproject", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
Are you probably using Composer v2? When I use the given JSON in my local environment using Composer v1, it tells me: > > Deprecation warning: Your package name vendor\_name/PhpProjec is invalid, it should not contain uppercase characters. We suggest using vendor\_name/php-projec instead. Make sure you fix this as Composer 2.0 will error. > > > The error message you've provided does not occur on my system. If you are still facing problems after using another package name, please share more details
Easy fix go to `composer.json` file find where is capitalizised e.g Izupay/PayMent to izupay/payment this will fix the error. ```json { "name": "IzuPay/PayMent", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ``` Working answer is: ```json { "name": "izupay/payment", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
Are you probably using Composer v2? When I use the given JSON in my local environment using Composer v1, it tells me: > > Deprecation warning: Your package name vendor\_name/PhpProjec is invalid, it should not contain uppercase characters. We suggest using vendor\_name/php-projec instead. Make sure you fix this as Composer 2.0 will error. > > > The error message you've provided does not occur on my system. If you are still facing problems after using another package name, please share more details
This most likely has to do with the version of Composer you're using. Before Composer version 2.0, a name could contain *any character*, including white spaces. However, from version 2.0 upwards: * the name can consists of words separated by -, . or \_. * the complete name should match ^a-z0-9*/a-z0-9*$. * the name must be **lowercased** (so instead of `vendor_name/PhpProjec`, it would be `vendor_name/phpprojec`
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
The problem is in the **"name"** property ``` - name : Does not match the regex pattern ^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$ ``` Change the "name" property accordingly **"vendor-name/project-name"** eg: `"name": "nismi/my-php-project"`
composer is case sensitive from v1.9 onwards... so change "PhpProject" to "phpproject" ``` { "name": "vendor_name/phpproject", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
composer is case sensitive from v1.9 onwards... so change "PhpProject" to "phpproject" ``` { "name": "vendor_name/phpproject", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
Easy fix go to `composer.json` file find where is capitalizised e.g Izupay/PayMent to izupay/payment this will fix the error. ```json { "name": "IzuPay/PayMent", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ``` Working answer is: ```json { "name": "izupay/payment", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
composer is case sensitive from v1.9 onwards... so change "PhpProject" to "phpproject" ``` { "name": "vendor_name/phpproject", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
This most likely has to do with the version of Composer you're using. Before Composer version 2.0, a name could contain *any character*, including white spaces. However, from version 2.0 upwards: * the name can consists of words separated by -, . or \_. * the complete name should match ^a-z0-9*/a-z0-9*$. * the name must be **lowercased** (so instead of `vendor_name/PhpProjec`, it would be `vendor_name/phpprojec`
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
The problem is in the **"name"** property ``` - name : Does not match the regex pattern ^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$ ``` Change the "name" property accordingly **"vendor-name/project-name"** eg: `"name": "nismi/my-php-project"`
Easy fix go to `composer.json` file find where is capitalizised e.g Izupay/PayMent to izupay/payment this will fix the error. ```json { "name": "IzuPay/PayMent", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ``` Working answer is: ```json { "name": "izupay/payment", "description": "description", "minimum-stability": "stable", "license": "proprietary", "authors": [ { "name": "***", "email": "[email protected]" } ], "require": { "barryvdh/laravel-ide-helper": "v2.7.0" } ```
63,223,502
I am actually doing the `Daily Coding Problem #2` I believe I have the result and I used it with recursion but I am wondering if it's good that I passed the `arr` in each recursion? Will passing it cause more memory or time? The coding problem question is > > Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. > > > For example, if our input was [1, 2, 3, 4, 5], the expected output > would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the > expected output would be [2, 3, 6] > > > My code looks like ``` const multiply_without_index = (arr, index, result) => { result = result || []; index = index || 0; if(index === arr.length) return result; const copy_arr = [...arr]; copy_arr.splice(index, 1); let total = 1; for(let n of copy_arr){ total *= n; } result.push(total); index++; return multiply_without_index(arr, index, result); } ``` Thanks in advance for any advices.
2020/08/03
[ "https://Stackoverflow.com/questions/63223502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850712/" ]
The problem is in the **"name"** property ``` - name : Does not match the regex pattern ^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$ ``` Change the "name" property accordingly **"vendor-name/project-name"** eg: `"name": "nismi/my-php-project"`
This most likely has to do with the version of Composer you're using. Before Composer version 2.0, a name could contain *any character*, including white spaces. However, from version 2.0 upwards: * the name can consists of words separated by -, . or \_. * the complete name should match ^a-z0-9*/a-z0-9*$. * the name must be **lowercased** (so instead of `vendor_name/PhpProjec`, it would be `vendor_name/phpprojec`
31,750,293
Why can't we declare an array of 10000000 integers (or say, large enough) inside the main function or inside any function locally while it is possible globally?
2015/07/31
[ "https://Stackoverflow.com/questions/31750293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4695532/" ]
**tl;dr:** space for local variables is limited. That's how CPU's and Operating Systems work. --- This is an implementation detail that is shared by many languages and implementations, e.g. C, C++ on typical desktop OS. Most platforms where the code runs on set aside some memory called the *Stack* to be used for return adresses and local storage. This is just a detail of how the CPU (Intel, AMD, etc.) execute machine code. Allocation from the stack is very fast, but the memory is valid only until the function call returns. This makes it ideal for C/C++ local variables. However, stack space is limited, so a large allocation will fail with a *Stack Overflow* - even if there's still enough memory "elsewhere". Memory for global variables is allocated when the program starts. E.g. the executable would indicate "I need so much space filled with zeroes, and I need so much space for data, and so much space for code." The "third" memory location is the *Heap*: it is used for memory allocated with `malloc` / `new` etc. Allocation on the heap are more expensive than on the stack (and have more problems to cope with), and they stay around until you free them, which is both good and a burden. --- Some side notes, intentionally left out because it's not directly relevant for the question: The Stack is just a range of (contiguos) memory, where you can allocate and free memory only from the top. This makes it limited, convenient and fast. On modern desktop systems, 32 bit processes usually don't run out of memory anymore, but out of address space: there's still physical memory available, but all available possible adresses in a 32 bit word are used up. Each thread of execution gets its own stack, whereas global variables and the heap are shared between all threads of a process. --- Why don't compilers move large allocations elsewhere? First, "it has always been this way". A lot of existing code may subtly depend on the old behavior, and "improving" the compiler might break this code. Second, for various reasons, the only generally suitable "elsewhere" is the heap. The performance difference between stack and heap allocations is significant: * heap allocation is more expensive * heap is shared so access to the heap from multiple threads must be synchronized which can be very costly. * the top of the stack is almost always in the CPU's cache (because that adress range is accessed very frequently). The heap is more likely not Most of the time, these details don't matter, but for some operations, this difference is significant. If the compiler would decide to put some allocations on the heap, we would lose predictability.
(edit: global variables don't typically go in the heap) It's likely due to the difference between available **stack** memory and total memory. Local variables get placed on the stack, whereas global variables get placed in a statically allocated section of memory. The following is a more general question that has a good answer that gives an overview of program memory allocation: [Global memory management in C++ in stack or heap?](https://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap)
231,772
Remodeling a kitchen. I'll be adding two new circuits dedicated to the microwave and fridge. I'll also be reconfiguring the countertops which will result in having to add another outlet to meet code for power distribution. Haven't done any major wiring changes for a while and I'm now seeing that AFCI is required basically anywhere in a dwelling outside the bathroom. The two new circuits I'm adding will require AFCI breakers so I'm now planning to purchase those. Since I am adding an outlet down the line to an existing series of countertop receptacles, am I required to also update this circuit to AFCI? I'm not having any luck finding an NEC reference that states this is a requirement, but I also can't find anything that dictates what might be grandfathered in certain circumstances. However, I also know that typically any changes require bringing whatever is being changed up to code so I feel like this is probably the obvious answer to the question. How about lighting? If I add another light to a circuit serving only luminaires, do I also update that to AFCI? The existing outlets are already GFCI protected so the only concern is adding AFCI here. Obviously, AFCI is better and I do understand the purposes of the protection it offers but the cost of upgrading half my panel due to a bunch of little changes would not be small. Edit: I'm located in MI. I couldn't find anything in the MI IRC but I could have missed something.
2021/08/11
[ "https://diy.stackexchange.com/questions/231772", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/140252/" ]
If you are following 2014 NEC or newer, the answer would be yes, 210.12 specifies AFCI protection where branch circuit wiring is "modified, replaced, or extended". So "adding an outlet down the line" would be an extension of the branch circuit wiring. The current NEC reference is 210.12(D)(1). I believe it was 210.12(B) in some older versions.
This is really a local jurisdiction issue. In my city, the rule would be adding an outlet requires a permit which triggers crazy local rules. For AFCI retrofit, my building department would require all circuits servicing the room/area be retrofitted. In my house, since the lighting circuit for kitchen also feeds family room & laundry room, I would have to fully retrofit those rooms as well. If I had an open floor plan with my kitchen open to the dining room or living room, those would also have to be fully brought to current code. My AHJ requires AFCI breakers for dishwasher, microwave, fridge, garbage disposal. If the outlet is 5 feet or less above floor, or these items are hardwired, it needs to be AFCI/GCI combo breakers. AFCI or GFCI outlet controls are not allowed for these items as the local building dept considers access obstructed. The next town over which is 100 yards from my front door would only require AFCI retrofit for the actual circuits being worked on. They have no additional requirements or amendments to the NEC. Either call your building department or call a local electrician that works in your city/county. Otherwise it is a lot of conjecture.
42,456
Given a Turing machine, how can I identify the language it accepts and write a set notation for L(M)?
2015/05/12
[ "https://cs.stackexchange.com/questions/42456", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/33571/" ]
A Turing machine implements an algorithm. The algorithm can be implicit by an explicit definition of the language such as: $M$ is a TM such that $L(M)=\left \{ x\in \Sigma^\* \ | \ |x|\in \mathbb{N}\_{even}\right \}$. Which is usually the case. In other cases, you might have to understand a turing machine based on a state diagram, this will be a simple reverse engineering problem where based on some inputs you understand the algorithm (and then you can prove your assumption). Generally, there is no fixed approach towards understanding the language a machine accepts.
The problem of identifying the language that is accepted by a Turing machine (using or not some form of set construction notation) does not have a general solution. This means that - with the exception of a minority of trivial cases - you will have to take them one at a time, as separate problems, *by logical necessity*. The fact that this question constantly reappears (in different guises) just shows how its answer is counterintuitive. It may be worth noting that Turing proposed the model of computation that carries his name precisely to explore the limits of computation, so this negative result should not be treated as something unexpected, or surprising.
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
You are probably using the `node` native EventEmitter from `node/index.d.ts` i.e. ``` import { EventEmitter } from 'events'; ``` Fix === Change the import to the one from angular: ``` import { EventEmitter } from '@angular/core'; ```
In visual studio code when your try to listen to user click event from your html file of the component `@Output() event: EventEmitter<string> = new EventEmitter<string>();` it automatically import this to the component `import { EventEmitter } from '@angular/event'` instead of `import { EventEmitter } from '@angular/core'`. Resource: <https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2>
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
You are probably using the `node` native EventEmitter from `node/index.d.ts` i.e. ``` import { EventEmitter } from 'events'; ``` Fix === Change the import to the one from angular: ``` import { EventEmitter } from '@angular/core'; ```
I was doing the same tutorial and faced the same issue. It is a problem with an import. `EventEmitter` must be imported from `@angular/core` Use: ``` import { EventEmitter } from '@angular/core'; ``` This will fix it.
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
You are probably using the `node` native EventEmitter from `node/index.d.ts` i.e. ``` import { EventEmitter } from 'events'; ``` Fix === Change the import to the one from angular: ``` import { EventEmitter } from '@angular/core'; ```
For me, VS code IDE V1.60.0 has added automatically this code: ``` import { EventEmitter } from 'stream'; ``` However, it is wrong and you should replace it with this ``` import { EventEmitter } from '@angular/core'; ```
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
You are probably using the `node` native EventEmitter from `node/index.d.ts` i.e. ``` import { EventEmitter } from 'events'; ``` Fix === Change the import to the one from angular: ``` import { EventEmitter } from '@angular/core'; ```
**This is the latest update for Angular 13** This is happening because the `EventEmitter` might be imported from the `events` module. ``` import * as EventEmitter from 'events'; ``` Or ``` import { EventEmitter } from 'events'; ``` **To fix this**, import `EventEmitter` from `@angular/core` ``` import { EventEmitter } from '@angular/core'; ```
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
I was doing the same tutorial and faced the same issue. It is a problem with an import. `EventEmitter` must be imported from `@angular/core` Use: ``` import { EventEmitter } from '@angular/core'; ``` This will fix it.
In visual studio code when your try to listen to user click event from your html file of the component `@Output() event: EventEmitter<string> = new EventEmitter<string>();` it automatically import this to the component `import { EventEmitter } from '@angular/event'` instead of `import { EventEmitter } from '@angular/core'`. Resource: <https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2>
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
For me, VS code IDE V1.60.0 has added automatically this code: ``` import { EventEmitter } from 'stream'; ``` However, it is wrong and you should replace it with this ``` import { EventEmitter } from '@angular/core'; ```
In visual studio code when your try to listen to user click event from your html file of the component `@Output() event: EventEmitter<string> = new EventEmitter<string>();` it automatically import this to the component `import { EventEmitter } from '@angular/event'` instead of `import { EventEmitter } from '@angular/core'`. Resource: <https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2>
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
**This is the latest update for Angular 13** This is happening because the `EventEmitter` might be imported from the `events` module. ``` import * as EventEmitter from 'events'; ``` Or ``` import { EventEmitter } from 'events'; ``` **To fix this**, import `EventEmitter` from `@angular/core` ``` import { EventEmitter } from '@angular/core'; ```
In visual studio code when your try to listen to user click event from your html file of the component `@Output() event: EventEmitter<string> = new EventEmitter<string>();` it automatically import this to the component `import { EventEmitter } from '@angular/event'` instead of `import { EventEmitter } from '@angular/core'`. Resource: <https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2>
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
For me, VS code IDE V1.60.0 has added automatically this code: ``` import { EventEmitter } from 'stream'; ``` However, it is wrong and you should replace it with this ``` import { EventEmitter } from '@angular/core'; ```
I was doing the same tutorial and faced the same issue. It is a problem with an import. `EventEmitter` must be imported from `@angular/core` Use: ``` import { EventEmitter } from '@angular/core'; ``` This will fix it.
49,911,879
I'm currently following a tutorial and the tutorial is making use of `EventEmitter`. The code goes like this ``` @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); ``` But it visual studio code gives me these errors: 1. Type 'EventEmitter' is not generic. 2. Expected 0 type arguments, but got 1. Even in the [angular website](https://angular.io/api/core/EventEmitter) it looks like that code is correct. I'm currently using Angular CLI: 1.7.4; Node: 8.11.1; Typescript: 2.8.1
2018/04/19
[ "https://Stackoverflow.com/questions/49911879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660753/" ]
For me, VS code IDE V1.60.0 has added automatically this code: ``` import { EventEmitter } from 'stream'; ``` However, it is wrong and you should replace it with this ``` import { EventEmitter } from '@angular/core'; ```
**This is the latest update for Angular 13** This is happening because the `EventEmitter` might be imported from the `events` module. ``` import * as EventEmitter from 'events'; ``` Or ``` import { EventEmitter } from 'events'; ``` **To fix this**, import `EventEmitter` from `@angular/core` ``` import { EventEmitter } from '@angular/core'; ```
3,254,671
Ok, I think I overcomplicated things and now I'm lost. Basically, I need to translate this, from Perl to Lua: ``` my $mem; my $memfree; open(FILE, 'proc/meminfo'); while (<FILE>) { if (m/MemTotal/) { $mem = $_; $mem =~ s/.*:(.*)/$1/; } } close(FILE); ``` So far I've written this: ``` for Line in io.lines("/proc/meminfo") do if Line:find("MemTotal") then Mem = Line Mem = string.gsub(Mem, ".*", ".*", 1) end end ``` But it is obviously wrong. What am I not getting? I understand why it is wrong, and what it is actually doing and why when I do ``` print(Mem) ``` it returns ``` .* ``` but I don't understand what is the proper way to do it. Regular expressions confuse me!
2010/07/15
[ "https://Stackoverflow.com/questions/3254671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385364/" ]
Lua doesn't use regular expressions. See Programming in Lua, sections [20.1](http://www.lua.org/pil/20.1.html) and following to understand how pattern matching and replacement works in Lua and where it differs from regular expressions. In your case you're replacing the complete string (`.*`) by the literal string `.*` – it's no surprise that you're getting just `.*` returned. The original regular expression replaced anything containing a colon (`.*:(.*)`) by the part after the colon, so a similar statement in Lua might be ``` string.gsub(Mem, ".*:(.*)", "%1") ```
The code below parses the contents of that file and puts it in a table: ``` meminfo={} for Line in io.lines("/proc/meminfo") do local k,v=Line:match("(.-): *(%d+)") if k~=nil and v~=nil then meminfo[k]=tonumber(v) end end ``` You can then just do ``` print(meminfo.MemTotal) ```
18,869,163
I make a menu to load (without refreshing the page) a page in a div (id="main-content"), and everything is working except the slider, there is the JS code : ``` jQuery(document).ready(function(){ // load index page when the page loads jQuery("#main-content").load("/tpl/index.tpl.php"); jQuery("#index").click(function(){ // load home page on click jQuery("#main-content").load("/tpl/index.tpl.php"); }); jQuery("#about").click(function(){ // load about page on click jQuery("#main-content").load("about.html"); }); jQuery("#contact").click(function(){ // load contact form onclick jQuery("#main-content").load("contact.html"); }); }); ``` There is a part of index code (with the div main content) : ``` <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>test</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="stylesheet" href="css/global.css" media="all"> <link rel="stylesheet" href="style.css" media="all"> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <link rel="stylesheet" href="css/ie.css" type="text/css" media="all" /> <![endif]--> <link rel="shortcut icon" href="images/favicon.ico"> <link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,200,300,300italic,200italic,400italic,600italic,600,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'> </head> <body class="dark-footer flx-home-page-4"> <div id="main-content"> </div> <script src="js/jquery-1.8.3.min.js"></script> <script src="js/superfish.js"></script> <script src="js/retina.js"></script> <script src="js/bootstrap.js"></script> <script src="js/jquery.form.js"></script> <script src="js/jquery.validate.min.js"></script> <script src="js/jquery.nivo.slider.js"></script> <script src="js/jquery.flexslider.js"></script> <script src="js/jquery.carouFredSel-5.6.4.js"></script> <script src="js/jquery.prettyPhoto.js"></script> <script src="js/jflickrfeed.min.js"></script> <script src="js/mediaelement-and-player.min.js"></script> <script src="js/modernizr.custom.63321.js"></script> <script src="js/jquery.hoverdir.js"></script> <script src="js/jquery.dropdown.js"></script> <script src="js/modernizr.custom.js"></script> <script src="js/jquery.dlmenu.js"></script> <script src="js/jquery.isotope.min.js"></script> <script src="js/jquery.eislideshow.js"></script> <script src="js/raphael-min.js"></script> <script src="js/iview.js"></script> <script src="js/tweetable.jquery.js"></script> <script src="js/jquery.timeago.js"></script> <script src="js/custom.js"></script> <script src="js/jquery.easing.1.3.js"></script> <script src="js/jquery.quicksand.js"></script> <script src="js/main.js"></script> <script src="js/bra_social_media.js"></script> <script src="js/jquery.themepunch.plugins.min.js"></script> <script src="js/jquery.themepunch.revolution.min.js"></script> <script src="js/classie.js"></script> <script src="js/cbpAnimatedHeader.min.js"></script> <script src="js/styleswitch.js"></script> <script src="js/loader.js"></script> <script type="text/javascript"> var tpj=jQuery; tpj.noConflict(); tpj(document).ready(function() { if (tpj.fn.cssOriginal!=undefined) tpj.fn.css = tpj.fn.cssOriginal; tpj('.fullwidthbanner').revolution( { delay:9000, startwidth:1000, startheight:500, onHoverStop:"on", // Stop Banner Timet at Hover on Slide on/off thumbWidth:100, // Thumb With and Height and Amount (only if navigation Tyope set to thumb !) thumbHeight:50, thumbAmount:3, hideThumbs:0, navigationType:"bullet", // bullet, thumb, none navigationArrows:"solo", // nexttobullets, solo (old name verticalcentered), none navigationStyle:"round", // round,square,navbar,round-old,square-old,navbar-old, or any from the list in the docu (choose between 50+ different item), custom navigationHAlign:"left", // Vertical Align top,center,bottom navigationVAlign:"bottom", // Horizontal Align left,center,right navigationHOffset:30, navigationVOffset:30, soloArrowLeftHalign:"left", soloArrowLeftValign:"center", soloArrowLeftHOffset:0, soloArrowLeftVOffset:0, soloArrowRightHalign:"right", soloArrowRightValign:"center", soloArrowRightHOffset:0, soloArrowRightVOffset:0, touchenabled:"on", // Enable Swipe Function : on/off stopAtSlide:-1, // Stop Timer if Slide "x" has been Reached. If stopAfterLoops set to 0, then it stops already in the first Loop at slide X which defined. -1 means do not stop at any slide. stopAfterLoops has no sinn in this case. stopAfterLoops:-1, // Stop Timer if All slides has been played "x" times. IT will stop at THe slide which is defined via stopAtSlide:x, if set to -1 slide never stop automatic hideCaptionAtLimit:0, // It Defines if a caption should be shown under a Screen Resolution ( Basod on The Width of Browser) hideAllCaptionAtLilmit:0, // Hide all The Captions if Width of Browser is less then this value hideSliderAtLimit:0, // Hide the whole slider, and stop also functions if Width of Browser is less than this value fullWidth:"on", shadow:0 //0 = no Shadow, 1,2,3 = 3 Different Art of Shadows - (No Shadow in Fullwidth Version !) }); }); </script> </body> </html> ``` And the index.tpl.php code : ``` <div class="fullwidthbanner-container"> <div class="fullwidthbanner"> <ul> <!-- THE FIRST SLIDE --> <li data-transition="fade" data-slotamount="10" data-masterspeed="300" data-thumb="images/thumbs/thumb1.jpg"> <!-- THE MAIN IMAGE IN THE FIRST SLIDE --> <img src="placeholders/slider/revolution-bg-1.jpg" alt="" > <!-- THE CAPTIONS IN THIS SLDIE --> <div class="caption lft rev-entry-2" data-x="25" data-y="30" data-speed="900" data-start="500" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-2.png" alt="" /></div> <div class="caption lfb rev-entry-1" data-x="70" data-y="120" data-speed="900" data-start="500" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-1.png" alt="" /></div> <div class="caption sft medium_white" data-x="645" data-y="250" data-speed="300" data-start="1200" data-easing="easeOutExpo">test</div> <div class="caption lfb big_yellow" data-x="645" data-y="285" data-speed="300" data-start="1300" data-easing="easeOutExpo">test</div> <div class="caption lfb small_yellow" data-x="645" data-y="330" data-speed="200" data-start="1500" data-easing="easeOutExpo">test</div> <div class="caption lfb small_white" data-x="645" data-y="380" data-speed="300" data-start="1500" data-easing="easeOutExpo">test test test test test test test test</div> </li> <!-- THE SECOND SLIDE --> <li data-transition="boxfade" data-slotamount="15" data-masterspeed="300" data-delay="9400" data-thumb="images/thumbs/thumb2.jpg"> <img src="placeholders/slider/revolution-bg-2.jpg" alt="" > <div class="caption sfb rev-entry-3" data-x="730" data-y="130" data-speed="900" data-start="1000" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-3.png" alt="" /></div> <div class="caption lft rev-entry-4" data-x="540" data-y="20" data-speed="900" data-start="1000" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-4.png" alt="" /></div> <div class="caption lfl very_big_white" data-x="0" data-y="216" data-speed="300" data-start="1200" data-easing="easeOutExpo">test</div> <div class="caption lfl very_big_white" data-x="0" data-y="275" data-speed="300" data-start="1300" data-easing="easeOutExpo">test</div> <div class="caption lfb big_white" data-x="0" data-y="360" data-speed="300" data-start="1500" data-easing="easeOutExpo"><a href="index.html#">test Now</a></div> </li> <!-- THE THIRD SLIDE --> <li data-transition="turnoff" data-slotamount="15" data-masterspeed="300"> <img src="placeholders/slider/revolution-bg-3.jpg" alt="" > <div class="caption sfb rev-entry-5" data-x="650" data-y="168" data-speed="700" data-start="500" data-easing="easeOutExpo"><img src="placeholders/slider/rev-entry-5.png" alt="" /></div> <div data-easing="easeOutExpo" data-start="900" data-speed="600" data-y="140" data-x="540" class="caption lft tp-caption start rev-entry-6" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-6.png" alt="" /></div> <div data-easing="easeOutExpo" data-start="1500" data-speed="800" data-y="70" data-x="400" class="caption lft tp-caption start rev-entry-7" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-7.png" alt="" /></div> <div data-easing="easeOutExpo" data-start="2000" data-speed="1000" data-y="20" data-x="280" class="caption lft tp-caption start rev-entry-8" data-easing="easeOutBack"><img src="placeholders/slider/rev-entry-8.png" alt="" /></div> <div class="caption lfl stl bg-op" data-x="0" data-y="380" data-speed="300" data-start="500" data-easing="easeOutExpo" ><p class="big_yellow">test</p><span class="medium_white">test</span></div> </li> </ul> <div class="tp-bannertimer"></div> </div> </div> ``` If anyone has a solution, that'd be great. Thanks you. **EDITED** : Image when it's working -- <http://gyazo.com/cea705bdd1badfc22a3ef6f7699940e8> -- Image when it's not working -- <http://gyazo.com/e0db6b14e4049b3cc570913e8bef1b4d> -- **Solved** : please check the @pawel reply, this is (for me) a solution.
2013/09/18
[ "https://Stackoverflow.com/questions/18869163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2782444/" ]
You have 3 records. If you write `assert_difference 'Review.count', 1`... it expects 4 at the end. But if you write `assert_difference 'Review.count', -1`... it expects 2, thus 1 less.
This line tells that you are expecting the difference of Plus one(1 or +1). ``` assert_difference 'Review.count', 1 , "a review should be deleted" ``` But actually you want the difference in Negative one(-1), so you should write ``` assert_difference 'Review.count', -1 , "a review should be deleted" ``` For more guide visit [assert\_difference](http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html)
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Apparently, something like this will help: ``` x = cos(theta) y = sin(theta) ``` Simple Google search threw this up, and the guy who asked the question said it solved it.
According [this reference](http://pgl.yoyo.org/luai/i/math.atan2): > > Returns the arc tangent of y/x (in radians), but uses the signs of > both parameters to find the quadrant of the result. (It also handles > correctly the case of x being zero.) > > > So I guess you can use `math.tan` to invert it also.
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Given only the angle you can only derive a unit vector pointing to `(dx, dy)`. To get the original `(dx, dy)` you also need to know the length of the vector `(dx, dy)`, which I'll call `len`. You also have to convert the angle you derived from degrees back to radians and then use the trig equations mentioned elsewhere in this post. That is you have: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi local len = sqrt(dx*dx + dy*dy) ``` Given `angle` (in degrees) and the vector length, `len`, you can derive `dx` and `dy` by: ``` local theta = angle * pi / 180 local dx = len * cos(theta) local dy = len * sin(theta) ```
Apparently, something like this will help: ``` x = cos(theta) y = sin(theta) ``` Simple Google search threw this up, and the guy who asked the question said it solved it.
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Apparently, something like this will help: ``` x = cos(theta) y = sin(theta) ``` Simple Google search threw this up, and the guy who asked the question said it solved it.
You'll probably get the wrong numbers if you use: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi ``` If you are using the coordinate system where y gets bigger going down the screen and x gets bigger going to the right then you should use: ``` local dy = y1 - y2 local dx = x2 - x1 local angle = math.deg(math.atan2(dy, dx)) if (angle < 0) then angle = 360 + angle end ``` The reason you want to use this is because atan2 in lua will give you a number between -180 and 180. It will be correct until you hit 180 then as it should go beyond 180 (i.e. 187) it will invert it to a negative number going down from -180 to 0 as you get closer to 360. To correct for this we check to see if the angle is less than 0 and if it is we add 360 to give us the correct angle.
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Apparently, something like this will help: ``` x = cos(theta) y = sin(theta) ``` Simple Google search threw this up, and the guy who asked the question said it solved it.
As atan2 works as tan-1, so the inverse could be tan, taking into consideration conversion between radian and degree
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Given only the angle you can only derive a unit vector pointing to `(dx, dy)`. To get the original `(dx, dy)` you also need to know the length of the vector `(dx, dy)`, which I'll call `len`. You also have to convert the angle you derived from degrees back to radians and then use the trig equations mentioned elsewhere in this post. That is you have: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi local len = sqrt(dx*dx + dy*dy) ``` Given `angle` (in degrees) and the vector length, `len`, you can derive `dx` and `dy` by: ``` local theta = angle * pi / 180 local dx = len * cos(theta) local dy = len * sin(theta) ```
According [this reference](http://pgl.yoyo.org/luai/i/math.atan2): > > Returns the arc tangent of y/x (in radians), but uses the signs of > both parameters to find the quadrant of the result. (It also handles > correctly the case of x being zero.) > > > So I guess you can use `math.tan` to invert it also.
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
You'll probably get the wrong numbers if you use: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi ``` If you are using the coordinate system where y gets bigger going down the screen and x gets bigger going to the right then you should use: ``` local dy = y1 - y2 local dx = x2 - x1 local angle = math.deg(math.atan2(dy, dx)) if (angle < 0) then angle = 360 + angle end ``` The reason you want to use this is because atan2 in lua will give you a number between -180 and 180. It will be correct until you hit 180 then as it should go beyond 180 (i.e. 187) it will invert it to a negative number going down from -180 to 0 as you get closer to 360. To correct for this we check to see if the angle is less than 0 and if it is we add 360 to give us the correct angle.
According [this reference](http://pgl.yoyo.org/luai/i/math.atan2): > > Returns the arc tangent of y/x (in radians), but uses the signs of > both parameters to find the quadrant of the result. (It also handles > correctly the case of x being zero.) > > > So I guess you can use `math.tan` to invert it also.
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Given only the angle you can only derive a unit vector pointing to `(dx, dy)`. To get the original `(dx, dy)` you also need to know the length of the vector `(dx, dy)`, which I'll call `len`. You also have to convert the angle you derived from degrees back to radians and then use the trig equations mentioned elsewhere in this post. That is you have: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi local len = sqrt(dx*dx + dy*dy) ``` Given `angle` (in degrees) and the vector length, `len`, you can derive `dx` and `dy` by: ``` local theta = angle * pi / 180 local dx = len * cos(theta) local dy = len * sin(theta) ```
You'll probably get the wrong numbers if you use: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi ``` If you are using the coordinate system where y gets bigger going down the screen and x gets bigger going to the right then you should use: ``` local dy = y1 - y2 local dx = x2 - x1 local angle = math.deg(math.atan2(dy, dx)) if (angle < 0) then angle = 360 + angle end ``` The reason you want to use this is because atan2 in lua will give you a number between -180 and 180. It will be correct until you hit 180 then as it should go beyond 180 (i.e. 187) it will invert it to a negative number going down from -180 to 0 as you get closer to 360. To correct for this we check to see if the angle is less than 0 and if it is we add 360 to give us the correct angle.
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
Given only the angle you can only derive a unit vector pointing to `(dx, dy)`. To get the original `(dx, dy)` you also need to know the length of the vector `(dx, dy)`, which I'll call `len`. You also have to convert the angle you derived from degrees back to radians and then use the trig equations mentioned elsewhere in this post. That is you have: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi local len = sqrt(dx*dx + dy*dy) ``` Given `angle` (in degrees) and the vector length, `len`, you can derive `dx` and `dy` by: ``` local theta = angle * pi / 180 local dx = len * cos(theta) local dy = len * sin(theta) ```
As atan2 works as tan-1, so the inverse could be tan, taking into consideration conversion between radian and degree
11,394,706
What is the inverse of the function ``` math.atan2 ``` I use this in Lua where I can get the inverse of `math.atan` by `math.tan`. But I am lost here. **EDIT** OK, let me give you more details. I needed to calculate angle between 2 points (x1,y1) and (x2,y2) and I did, ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx)* 180 / pi ``` Now if I have the angle, is it possible to get back dy and dx?
2012/07/09
[ "https://Stackoverflow.com/questions/11394706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137788/" ]
You'll probably get the wrong numbers if you use: ``` local dy = y1-y2 local dx = x1-x2 local angle = atan2(dy,dx) * 180 / pi ``` If you are using the coordinate system where y gets bigger going down the screen and x gets bigger going to the right then you should use: ``` local dy = y1 - y2 local dx = x2 - x1 local angle = math.deg(math.atan2(dy, dx)) if (angle < 0) then angle = 360 + angle end ``` The reason you want to use this is because atan2 in lua will give you a number between -180 and 180. It will be correct until you hit 180 then as it should go beyond 180 (i.e. 187) it will invert it to a negative number going down from -180 to 0 as you get closer to 360. To correct for this we check to see if the angle is less than 0 and if it is we add 360 to give us the correct angle.
As atan2 works as tan-1, so the inverse could be tan, taking into consideration conversion between radian and degree
5,158,014
I'm writing some C++ codes for fun and practice, to learn more about language features. I want to know more about static variables and their behaviour in recursive functions. Trying this code in g++ compiler, I'm given expected result: ``` #include <iostream> using namespace std; int f(const int& value) { static int result = 0; return result += value; } int main() { cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10))); return 0; } ``` But my friend tested same code in Microsoft Visual C++ 6. output is `50, 80, 90` I tested it with other C++ compilers (g++, Borland, Code::blocks and MingW under Linux, Win and Mac) output was `110, 100, 40`. I can't understand how output could be `50, 80, 90` ... Why MSVC's output is different?
2011/03/01
[ "https://Stackoverflow.com/questions/5158014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275221/" ]
The order of evaluation of the following three subexpressions is unspecified: ``` f(10) f(f(10)) f(f(f(10))) ``` The compiler may evaluate those subexpressions in any order. You should not rely on a particular order of evaluation in your program, especially if you intend to compile using multiple compilers. This is because there is no sequence point anywhere in that expression. The only requirement is that each of those subexpressions is evaluated before the result is needed (that is, before the result is to be printed). In your example, there are actually several subexpressions, which I've labelled as a through k here: ``` // a b c d e f g h i j k cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10))); ``` The calls to `operator<<` (`a`, `c`, `d`, `g`, and `h`) all have to be evaluated in order because each depends on the result of the previous call. Likewise, `b` has to be evaluated before `a` can be evaluated, and `k` has to be evaluated before `j`, `i`, or `h` can be evaluated. However, there are no dependencies between some of these subexpressions: the result of `b` is not dependent upon the result of `k`, so the compiler is free to generate code that evaluates `k` then `b` or `b` then `k`. For more information on sequence points and related unspecified and undefined behavior, consider reading the Stack Overflow C++ FAQ article, ["Undefined Behavior and Sequence Points"](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) (your program doesn't have any undefined behavior, but much of the article still applies).
Just because the output appears left-to-right on the screen does not mean the *order of evaluation* follows the same direction. In C++, the order of evaluation of function arguments is *unspecified*. Plus, printing data via the `<<` operator is just fancy syntax for calling functions. In short, if you say `operator<<(foo(), bar())`, the compiler can call `foo` or `bar` first. That's why it's generally a bad idea to call functions with side effects and use those as arguments to other functions.
5,158,014
I'm writing some C++ codes for fun and practice, to learn more about language features. I want to know more about static variables and their behaviour in recursive functions. Trying this code in g++ compiler, I'm given expected result: ``` #include <iostream> using namespace std; int f(const int& value) { static int result = 0; return result += value; } int main() { cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10))); return 0; } ``` But my friend tested same code in Microsoft Visual C++ 6. output is `50, 80, 90` I tested it with other C++ compilers (g++, Borland, Code::blocks and MingW under Linux, Win and Mac) output was `110, 100, 40`. I can't understand how output could be `50, 80, 90` ... Why MSVC's output is different?
2011/03/01
[ "https://Stackoverflow.com/questions/5158014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275221/" ]
The order of evaluation of the following three subexpressions is unspecified: ``` f(10) f(f(10)) f(f(f(10))) ``` The compiler may evaluate those subexpressions in any order. You should not rely on a particular order of evaluation in your program, especially if you intend to compile using multiple compilers. This is because there is no sequence point anywhere in that expression. The only requirement is that each of those subexpressions is evaluated before the result is needed (that is, before the result is to be printed). In your example, there are actually several subexpressions, which I've labelled as a through k here: ``` // a b c d e f g h i j k cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10))); ``` The calls to `operator<<` (`a`, `c`, `d`, `g`, and `h`) all have to be evaluated in order because each depends on the result of the previous call. Likewise, `b` has to be evaluated before `a` can be evaluated, and `k` has to be evaluated before `j`, `i`, or `h` can be evaluated. However, there are no dependencies between some of these subexpressions: the result of `b` is not dependent upon the result of `k`, so the compiler is free to generate code that evaluates `k` then `b` or `b` then `k`. For more information on sequence points and related unspecified and undefined behavior, consider reading the Stack Overflow C++ FAQ article, ["Undefined Behavior and Sequence Points"](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) (your program doesn't have any undefined behavior, but much of the article still applies).
An easy way to see exactly what it is doing: ``` int f(const int& value, int fID) { static int result = 0; static int fCounter = 0; fCounter++; cout << fCounter << ". ID:" << fID << endl; return result += value; } int main() { cout << f(10, 6) << ", " << f(f(10, 4), 5) << ", " << f(f(f(10, 1),2),3); return 0; } ``` I agree with what others have said in their answers, but this would allow you to see exactly what it is doing. :)
5,158,014
I'm writing some C++ codes for fun and practice, to learn more about language features. I want to know more about static variables and their behaviour in recursive functions. Trying this code in g++ compiler, I'm given expected result: ``` #include <iostream> using namespace std; int f(const int& value) { static int result = 0; return result += value; } int main() { cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10))); return 0; } ``` But my friend tested same code in Microsoft Visual C++ 6. output is `50, 80, 90` I tested it with other C++ compilers (g++, Borland, Code::blocks and MingW under Linux, Win and Mac) output was `110, 100, 40`. I can't understand how output could be `50, 80, 90` ... Why MSVC's output is different?
2011/03/01
[ "https://Stackoverflow.com/questions/5158014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275221/" ]
The order of evaluation of the following three subexpressions is unspecified: ``` f(10) f(f(10)) f(f(f(10))) ``` The compiler may evaluate those subexpressions in any order. You should not rely on a particular order of evaluation in your program, especially if you intend to compile using multiple compilers. This is because there is no sequence point anywhere in that expression. The only requirement is that each of those subexpressions is evaluated before the result is needed (that is, before the result is to be printed). In your example, there are actually several subexpressions, which I've labelled as a through k here: ``` // a b c d e f g h i j k cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10))); ``` The calls to `operator<<` (`a`, `c`, `d`, `g`, and `h`) all have to be evaluated in order because each depends on the result of the previous call. Likewise, `b` has to be evaluated before `a` can be evaluated, and `k` has to be evaluated before `j`, `i`, or `h` can be evaluated. However, there are no dependencies between some of these subexpressions: the result of `b` is not dependent upon the result of `k`, so the compiler is free to generate code that evaluates `k` then `b` or `b` then `k`. For more information on sequence points and related unspecified and undefined behavior, consider reading the Stack Overflow C++ FAQ article, ["Undefined Behavior and Sequence Points"](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) (your program doesn't have any undefined behavior, but much of the article still applies).
The prefix operator syntax is translated into the following prefix notation: ``` <<( <<( <<( cout, f(10) ), f(f(10)) ), f(f(f(10))) ) A B C ``` Now there are three different function calls, identified as A, B and C above. with the arguments of each call being: ``` arg1 arg2 A: result of B, f(10) B: result of C, f(f(10)) C: cout , f(f(f(10))) ``` For each one of the calls, the compiler is allowed to evaluate the arguments in any order, for the correct evaluation of the first argument of A, B has to be evaluated first, and similarly for the first argument of B, the whole C expression has to be evaluated. This implies that there is a partial order on the execution of A, B, and C required by the first argument dependency. There is also a partial ordering on the evaluation of each call and both arguments, so B1 and B2 (referring to the first and second arguments of the call B) have to be evaluated before B. Those partial orderings do not lead to a unique requirement for the execution of the calls, since the compiler can decide to execute all second arguments before trying to evaluate the first argument, leading to the equivalent path: ``` tmp1 = f(10); tmp2 = f(f(10)); tmp3 = f(f(f(10))); cout << tmp1 << tmp2 << tmp3; ``` or ``` tmp3 = f(f(f(10))); tmp2 = f(f(10)); tmp1 = f(10); cout << tmp1 << tmp2 << tmp3; ``` or ``` tmp2 = f(f(10)); tmp1 = f(10); tmp3 = f(f(f(10))); cout << tmp1 << tmp2 << tmp3; ``` or ... keep combining.
58,726,779
This is something I just noticed but can't find any information, not in PEPs, APIs, or examples. We all know `print` changed to `print()` in Python 3, but I've always seen `return` written as a statement, not a function. However it has exactly the same behaviour as a function. I can see the similarity between this and the changes that happened with `print`, and `print()` shows up in the Built-in Functions section of Python 3. But not `return()`. So what's going on with the `return()` function?
2019/11/06
[ "https://Stackoverflow.com/questions/58726779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260169/" ]
It's not a function. It's a statement with unnecessary parentheses. `(val)` means `val`, so `return (val)` is the same as `return val`. Writing `return(val)`, making it look like a function, is just bad style.
It process it as: ``` return (val) ``` As a number with a paired parenthesis, not a function, but ``` >>> val = 10 >>> (val) 10 >>> ``` `(val)` is not changing anything, only thing it does is to keep it as a number, so it ends with: ``` return val ``` Which is the same as the other one
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
Change ``` dif = (end - start) * 1000; ``` to ``` dif = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; ``` In pseudocode: ``` Get the seconds part of the time delta Multiply by 1000 to get milliseconds Get the microseconds part of the time delta Divide that part by 1000 Add that part to the milliseconds from seconds delta ```
For quick benchmark, I'd use `clock()` and `CLOCKS_PER_SEC`. Here's some macro code I use: ``` #define CLOCK_TICK(acc, ctr) ctr = std::clock() #define CLOCK_TOCK(acc, ctr) acc += (std::clock() - ctr) #define CLOCK_RESET(acc) acc = 0 #define CLOCK_REPORT(acc) (1000. * double(acc) / double(CLOCKS_PER_SEC)) static clock_t t1a, t1c; int main() { while (true) { CLOCK_RESET(t1a); init_stuff(); CLOCK_TICK(t1a, t1c); critical_function(); CLOCK_TOCK(t1a, t1c); std::cout << "This round took " << CLOCK_REPORT(t1a) << "ms.\n"; } } ``` You can get a higher-resolution clock out of the new `<chrono>` header. The macros should be straight-forward to adapt.
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
Change ``` dif = (end - start) * 1000; ``` to ``` dif = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; ``` In pseudocode: ``` Get the seconds part of the time delta Multiply by 1000 to get milliseconds Get the microseconds part of the time delta Divide that part by 1000 Add that part to the milliseconds from seconds delta ```
1. Make sure you're including the correct header ("#include ") 2. Use "timersub()" to get the difference, instead of subtracting end-start: <http://linux.die.net/man/3/timeradd> 'Hope that helps .. PSM
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
Change ``` dif = (end - start) * 1000; ``` to ``` dif = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; ``` In pseudocode: ``` Get the seconds part of the time delta Multiply by 1000 to get milliseconds Get the microseconds part of the time delta Divide that part by 1000 Add that part to the milliseconds from seconds delta ```
You want: ``` dif = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000.0; ``` Note 1: You need the tv\_sec to handle even a short duration crossing a second ticking over. Note 2: Second term divides by a 1000.0 so as to use floating point rather than integer division.
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
Change ``` dif = (end - start) * 1000; ``` to ``` dif = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; ``` In pseudocode: ``` Get the seconds part of the time delta Multiply by 1000 to get milliseconds Get the microseconds part of the time delta Divide that part by 1000 Add that part to the milliseconds from seconds delta ```
On Linux the best way to achieve this is to use the times(2) interface rather than gettimeofday(2) have a read of the man page. > > man 2 times. > > > It has exquisite fidelity.
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
You want: ``` dif = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000.0; ``` Note 1: You need the tv\_sec to handle even a short duration crossing a second ticking over. Note 2: Second term divides by a 1000.0 so as to use floating point rather than integer division.
For quick benchmark, I'd use `clock()` and `CLOCKS_PER_SEC`. Here's some macro code I use: ``` #define CLOCK_TICK(acc, ctr) ctr = std::clock() #define CLOCK_TOCK(acc, ctr) acc += (std::clock() - ctr) #define CLOCK_RESET(acc) acc = 0 #define CLOCK_REPORT(acc) (1000. * double(acc) / double(CLOCKS_PER_SEC)) static clock_t t1a, t1c; int main() { while (true) { CLOCK_RESET(t1a); init_stuff(); CLOCK_TICK(t1a, t1c); critical_function(); CLOCK_TOCK(t1a, t1c); std::cout << "This round took " << CLOCK_REPORT(t1a) << "ms.\n"; } } ``` You can get a higher-resolution clock out of the new `<chrono>` header. The macros should be straight-forward to adapt.
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
You want: ``` dif = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000.0; ``` Note 1: You need the tv\_sec to handle even a short duration crossing a second ticking over. Note 2: Second term divides by a 1000.0 so as to use floating point rather than integer division.
1. Make sure you're including the correct header ("#include ") 2. Use "timersub()" to get the difference, instead of subtracting end-start: <http://linux.die.net/man/3/timeradd> 'Hope that helps .. PSM
8,146,045
I'm trying to create a simple doc on google docs, I have a sheet called "Income" With A Being name, B being a date, and C being the amount What I need to do is get the amount for this month, date format is dd/mm/yyyy Any help would be appreciated!
2011/11/16
[ "https://Stackoverflow.com/questions/8146045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810304/" ]
You want: ``` dif = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000.0; ``` Note 1: You need the tv\_sec to handle even a short duration crossing a second ticking over. Note 2: Second term divides by a 1000.0 so as to use floating point rather than integer division.
On Linux the best way to achieve this is to use the times(2) interface rather than gettimeofday(2) have a read of the man page. > > man 2 times. > > > It has exquisite fidelity.
10,505,561
I have a listbox with items bound to an ObservableCollection. Now, from within the viewModel, I need to cause an update to the UI. I dont have a refernce to the listbox from my view model. If I remove or add an item from my ObservableCollection, the ui gets updated. Based on some other logic I need to update the UI...but the ObservableCollection is the same. How can I update the UI WITHOUT either adding or removing items from my ObservableCollection? Thanks
2012/05/08
[ "https://Stackoverflow.com/questions/10505561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1202434/" ]
If you need to change your UI because you've edited the items *in* your collection, then you should arrange for those items to implement the `INotifyPropertyChanged` interface. If the objects within your collection have a `PropertyChanged` event, the UI will be listening for that event from individual items. (If possible, you could also change the items in your collection to be `DependencyObjects` with `DependencyProperties`, which accomplishes the same goal.) If you *really* need to trigger a UI update when *nothing at all* about your collection has changed, the way to do it is to manually raise the `CollectionChanged` event. This can't be done with the `ObservableCollection<>` as is, but you could derive a new collection from that class, and call the `protected OnCollectionChanged` method from within some new, `public` method.
I've had a similar issue where I wanted to change the background on an item, but obviously neither the item nor the collection changed. It was achieved by calling: ``` CollectionViewSource.GetDefaultView(your_collection_name).Refresh(); ``` This refreshed the view from the view model without altering the collections
10,505,561
I have a listbox with items bound to an ObservableCollection. Now, from within the viewModel, I need to cause an update to the UI. I dont have a refernce to the listbox from my view model. If I remove or add an item from my ObservableCollection, the ui gets updated. Based on some other logic I need to update the UI...but the ObservableCollection is the same. How can I update the UI WITHOUT either adding or removing items from my ObservableCollection? Thanks
2012/05/08
[ "https://Stackoverflow.com/questions/10505561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1202434/" ]
If you need to change your UI because you've edited the items *in* your collection, then you should arrange for those items to implement the `INotifyPropertyChanged` interface. If the objects within your collection have a `PropertyChanged` event, the UI will be listening for that event from individual items. (If possible, you could also change the items in your collection to be `DependencyObjects` with `DependencyProperties`, which accomplishes the same goal.) If you *really* need to trigger a UI update when *nothing at all* about your collection has changed, the way to do it is to manually raise the `CollectionChanged` event. This can't be done with the `ObservableCollection<>` as is, but you could derive a new collection from that class, and call the `protected OnCollectionChanged` method from within some new, `public` method.
This is a good case for an extension method. It hides away the implementation in case it changes in future versions, can be modified in one place, and the calling code looks simpler and less confusing. ``` public static void Refresh<T>(this ObservableCollection<T> value) { CollectionViewSource.GetDefaultView(value).Refresh(); } ``` Usage: ``` myCollection.Refresh(); ```
10,505,561
I have a listbox with items bound to an ObservableCollection. Now, from within the viewModel, I need to cause an update to the UI. I dont have a refernce to the listbox from my view model. If I remove or add an item from my ObservableCollection, the ui gets updated. Based on some other logic I need to update the UI...but the ObservableCollection is the same. How can I update the UI WITHOUT either adding or removing items from my ObservableCollection? Thanks
2012/05/08
[ "https://Stackoverflow.com/questions/10505561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1202434/" ]
I've had a similar issue where I wanted to change the background on an item, but obviously neither the item nor the collection changed. It was achieved by calling: ``` CollectionViewSource.GetDefaultView(your_collection_name).Refresh(); ``` This refreshed the view from the view model without altering the collections
This is a good case for an extension method. It hides away the implementation in case it changes in future versions, can be modified in one place, and the calling code looks simpler and less confusing. ``` public static void Refresh<T>(this ObservableCollection<T> value) { CollectionViewSource.GetDefaultView(value).Refresh(); } ``` Usage: ``` myCollection.Refresh(); ```
52,592
I want to use the following code ``` the_time('d. F Y', '<p class="article-date">', '</p>'); ``` to show the date of an article (post) wrapped within `<p></p>`. I also tried ``` echo '<p class="article-date">' . the_time('d. F Y') . '</p>'; ``` but again the date isn't placed in those tags. What I'm doing wrong? I have a normal `foreach` and no `endforeach` and so on.
2012/05/18
[ "https://wordpress.stackexchange.com/questions/52592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13921/" ]
``` <p> <?php the_time() ?> </p> ``` It helps with separation of concerns and increases readability of code as well as being consistent with WordPress coding standards and the default coding style. The first method you attempted is completely invalid, `the_time()` only accepts 1 parameter, the date format. The second method has roots in validity, but `the_time()` itself is already doing an `echo`, so by calling it in the middle of the string, you're preempting the outer `echo` and probably getting the time and an empty `p`. If you want to use that method you can go with this: ``` echo '<p>' . get_the_time() . '</p>'; ``` Since `get_the_time()` `return`s its value whereas `the_time()` `echo`s it. ### Edit To use the `$format` parameter correctly: ``` <?php the_time( 'd. F Y' ) ?> ``` Note: for a publicly released Theme, it is recommended to use the user-defined date/time format: ``` <?php the_time( get_option( 'time_format' ) ); ?> ``` You can also pass the date format to `the_time()` if you need to output the date for each post in the loop. The `the_date()` function only outputs the date upon the first occurrence. So, if multiple posts have the same date, the date will only be output once. To get around this limitation, use `the_time( $date_format )` instead: ``` <?php the_time( get_option( 'date_format' ) ); ?> ```
about your first line of code: [`the_time()`](http://codex.wordpress.org/Function_Reference/the_time) only uses one parameter. about your second line of code: if you want to use 'the\_time' in a string concatenation, use [`get_the_time()`](http://codex.wordpress.org/Function_Reference/get_the_time) : example: ``` echo '<p class="article-date">' . get_the_time('d. F Y') . '</p>'; ```
11,226
Many individuals believe they can make significant quantities of money by stock trading. Much of the financial services industry wants the public to believe that it can take our savings and, by the application of investing skill, make better returns than the market average. Much of the advertising for mutual fund investment vehicles in the UK touts superior past performance despite the (legally mandated) small print asserting that past performance is no guide to the future. For example, a UK mutual fund house, Jupiter, describes it mission thus: > > We are an active fund manager seeking to add value for our clients through the delivery of investment outperformance over the medium to long term. > > > There are even two major schools of thought about *how* to achieve good returns: * [technical analysis](http://en.wikipedia.org/wiki/Technical_analysis) which focuses on historic patterns of price movement, and * [fundamental analysis](http://en.wikipedia.org/wiki/Fundamental_analysis) which focuses on analysing the underlying economic performance of the firm. The problem is this: there is a solid body of financial theory that asserts that long term outperformance based on any form of market analysis is impossible. The [Efficient Market Hypothesis](http://en.wikipedia.org/wiki/Efficient_market_hypothesis) asserts: > > one cannot consistently achieve returns in excess of average market returns on a risk-adjusted basis, given the information available at the time the investment is made > > > (unless, it is worth adding, you have inside information on which it is illegal to trade in most markets). [Burton Malkiel's](http://en.wikipedia.org/wiki/Burton_Malkiel) famous book on the topic, [A Random Walk Down Wall Street](http://books.google.co.uk/books/about/A_Random_Walk_Down_Wall_Street.html?id=O8x1YpBp6WYC&redir_esc=y), is a very readable introduction. As a test of investing skill more than one experiment has been conducted pitting the professional stock pickers against random choices (often vividly illustrated by having a monkey throw darts at the Wall Street Journal to select a portfolio). Experts often don't do significantly better than random. As a [Forbes article reports](http://www.forbes.com/sites/rickferri/2012/03/12/why-smart-people-fail-to-beat-the-market/2/), when the Wall Street Journal did the random-selection experiment: > > On average, investors following the experts’ recommendations lost 3.8% on a risk‐adjusted basis over a 6‐month holding period. > > > Both the theory and this experiment seem to defy common sense. How can people who a skilled and well paid for their skill not actually consistently beat a random number generator? How can such a large industry exist when the skill they assert is impossible to demonstrate? So the question here is: **is there evidence that experts can consistently beat the market? Are there demonstrable strategies to make returns ahead of the market average?**
2012/10/11
[ "https://skeptics.stackexchange.com/questions/11226", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/3943/" ]
> > is there evidence that experts can consistently beat the market? > > > Yes, there is. It's quoted in [the Forbes article](http://www.forbes.com/sites/rickferri/2012/03/12/why-smart-people-fail-to-beat-the-market/) you provide as a source. > > To answer this question, Fama and French compared the distribution of > fund returns to a distribution of simulated portfolio returns formed > with randomly selected stocks. Using a bootstrapping technique, they > created thousands of simulated U.S. equity portfolios that selected > stocks randomly. The range of actual mutual fund returns was then > compared to the range of bootstrapped returns. The overlay was very > close, which means most actual fund returns were a result of random > stock selection and not skill. > > > **There were, however, a handful of funds whose managers outperformed the bootstrapping method after adjusting for costs and risks. These > so-called outliers may possess skill, if only they could be > identified.** > > > Above references a research paper ["Luck Versus Skill in the Cross Section of Mutual Fund Returns](http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1356021)".
There is a problem with Mutual Funds. When the market declines, some people unload the funds and the manager has to liquidate to give them their money, i.e. sell into a declining market. Conversely when markets are climbing, the managers have to invest the incoming cash into the climbing stock prices. This is a structural disadvantage to MFs, in addition to the drag from fees. There are 1000s of references to this problem. Here is one: <http://www.bogleheads.org/wiki/Mutual_funds:_additional_costs> Sorry I am new here and just adjusting to your rules.
59,481,865
Could you please take a look at my code and give me some advice how I might improve my code so it takes less time to process? Main purpose is to look at each row (ID) at test table and find same ID at list table, if it's match then look at time difference between the two identical ID and label them as if it takes less than 1 hours (3600s) or not. Thanks in advance test.csv has two col (ID, time) and 100K rows list.csv has tow col (ID, time) and 40k rows sample data: ID Time 83d-36615fa05fb0 2019-12-11 10:41:48 ``` a = -1 for row_index,row in test.iterrows(): a = a + 1 for row_index2,row2 in list.iterrows(): if row['ID'] == row2['ID']: time_difference = row['Time'] - row2['Time'] time_difference = time_difference.total_seconds() if time_difference < 3601 and time_difference > 0: test.loc[a, 'result'] = "short waiting time" ```
2019/12/25
[ "https://Stackoverflow.com/questions/59481865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11986289/" ]
You can easily generate the indexing array with `r_`. ``` In [165]: np.r_[0,3:15] Out[165]: array([ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` under the covers it's just doing ``` In [166]: np.concatenate([[0],np.arange(3,15)]) Out[166]: array([ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` `np.delete`, while convenient, ends up with a similar amount of work. Depending on the deletion index it will either concatenate pieces, or construct a selection mask. Regardless of the method, the result is a new array, with a copy of the required data (not a view). `loadtxt` accepts as `usecols` parameter that takes a similar column index array.
You can use [**`np.delete`** [numpy-doc]](https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html) for that, and use a `slice` object as parameter to remove: ``` >>> np.delete(data, slice(1, 3), 1) array([[61. , 15.04, 14.96, 13.17, 9.29, 13.96, 9.87, 13.67, 10.25, 10.83, 12.58, 18.5 , 15.04], [61. , 14.71, 16.88, 10.83, 6.5 , 12.62, 7.67, 11.5 , 10.04, 9.79, 9.67, 17.54, 13.83], [61. , 18.5 , 16.88, 12.33, 10.13, 11.17, 6.17, 11.25, 8.04, 8.5 , 7.67, 12.75, 12.71]]) ``` When you use slicing notation, under the hood you basically pass a `slice` object. Indeed `a[1:3]` is equivalent to `a[slice(1,3)]`. Furthermore the `1` here specifies the dimension over which we want to remove. Since we wish to remove data for the second dimension, we thus write `1` as third parameter.
59,481,865
Could you please take a look at my code and give me some advice how I might improve my code so it takes less time to process? Main purpose is to look at each row (ID) at test table and find same ID at list table, if it's match then look at time difference between the two identical ID and label them as if it takes less than 1 hours (3600s) or not. Thanks in advance test.csv has two col (ID, time) and 100K rows list.csv has tow col (ID, time) and 40k rows sample data: ID Time 83d-36615fa05fb0 2019-12-11 10:41:48 ``` a = -1 for row_index,row in test.iterrows(): a = a + 1 for row_index2,row2 in list.iterrows(): if row['ID'] == row2['ID']: time_difference = row['Time'] - row2['Time'] time_difference = time_difference.total_seconds() if time_difference < 3601 and time_difference > 0: test.loc[a, 'result'] = "short waiting time" ```
2019/12/25
[ "https://Stackoverflow.com/questions/59481865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11986289/" ]
You can use [**`np.delete`** [numpy-doc]](https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html) for that, and use a `slice` object as parameter to remove: ``` >>> np.delete(data, slice(1, 3), 1) array([[61. , 15.04, 14.96, 13.17, 9.29, 13.96, 9.87, 13.67, 10.25, 10.83, 12.58, 18.5 , 15.04], [61. , 14.71, 16.88, 10.83, 6.5 , 12.62, 7.67, 11.5 , 10.04, 9.79, 9.67, 17.54, 13.83], [61. , 18.5 , 16.88, 12.33, 10.13, 11.17, 6.17, 11.25, 8.04, 8.5 , 7.67, 12.75, 12.71]]) ``` When you use slicing notation, under the hood you basically pass a `slice` object. Indeed `a[1:3]` is equivalent to `a[slice(1,3)]`. Furthermore the `1` here specifies the dimension over which we want to remove. Since we wish to remove data for the second dimension, we thus write `1` as third parameter.
If `a` is your `numpy` array and you want to drop the columns: `1,2`, you could do that using the following in a single line. ```py import numpy as np delete_cols = [1,2] # list of column numbers to delete a[:,list(set(np.arange(a.shape[-1])) - set(delete_cols))] ``` ### Some Explanation What you need here is proper indexing of the array `a`. ```py # list_of_column_numbers = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] a[:, list_of_column_numbers] ``` > > You can make the `list_of_column_numbers` in one of the following ways: > > > ```py # Method-1: Direct Declaration list_of_column_numbers = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # Method-2A: Using Set and Dropping Columns not Needed # a.shape[-1] = 15 delete_cols = [1,2] # list of column numbers to delete list_of_column_numbers = list(set(np.arange(a.shape[-1])) - set(delete_cols)) # Method-2B: Make list of column numbers # a.shape[-1] = 15 list_of_column_numbers = [0] + np.arange(3,a.shape[-1]).tolist() ```
59,481,865
Could you please take a look at my code and give me some advice how I might improve my code so it takes less time to process? Main purpose is to look at each row (ID) at test table and find same ID at list table, if it's match then look at time difference between the two identical ID and label them as if it takes less than 1 hours (3600s) or not. Thanks in advance test.csv has two col (ID, time) and 100K rows list.csv has tow col (ID, time) and 40k rows sample data: ID Time 83d-36615fa05fb0 2019-12-11 10:41:48 ``` a = -1 for row_index,row in test.iterrows(): a = a + 1 for row_index2,row2 in list.iterrows(): if row['ID'] == row2['ID']: time_difference = row['Time'] - row2['Time'] time_difference = time_difference.total_seconds() if time_difference < 3601 and time_difference > 0: test.loc[a, 'result'] = "short waiting time" ```
2019/12/25
[ "https://Stackoverflow.com/questions/59481865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11986289/" ]
You can easily generate the indexing array with `r_`. ``` In [165]: np.r_[0,3:15] Out[165]: array([ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` under the covers it's just doing ``` In [166]: np.concatenate([[0],np.arange(3,15)]) Out[166]: array([ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` `np.delete`, while convenient, ends up with a similar amount of work. Depending on the deletion index it will either concatenate pieces, or construct a selection mask. Regardless of the method, the result is a new array, with a copy of the required data (not a view). `loadtxt` accepts as `usecols` parameter that takes a similar column index array.
If `a` is your `numpy` array and you want to drop the columns: `1,2`, you could do that using the following in a single line. ```py import numpy as np delete_cols = [1,2] # list of column numbers to delete a[:,list(set(np.arange(a.shape[-1])) - set(delete_cols))] ``` ### Some Explanation What you need here is proper indexing of the array `a`. ```py # list_of_column_numbers = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] a[:, list_of_column_numbers] ``` > > You can make the `list_of_column_numbers` in one of the following ways: > > > ```py # Method-1: Direct Declaration list_of_column_numbers = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # Method-2A: Using Set and Dropping Columns not Needed # a.shape[-1] = 15 delete_cols = [1,2] # list of column numbers to delete list_of_column_numbers = list(set(np.arange(a.shape[-1])) - set(delete_cols)) # Method-2B: Make list of column numbers # a.shape[-1] = 15 list_of_column_numbers = [0] + np.arange(3,a.shape[-1]).tolist() ```
59,481,865
Could you please take a look at my code and give me some advice how I might improve my code so it takes less time to process? Main purpose is to look at each row (ID) at test table and find same ID at list table, if it's match then look at time difference between the two identical ID and label them as if it takes less than 1 hours (3600s) or not. Thanks in advance test.csv has two col (ID, time) and 100K rows list.csv has tow col (ID, time) and 40k rows sample data: ID Time 83d-36615fa05fb0 2019-12-11 10:41:48 ``` a = -1 for row_index,row in test.iterrows(): a = a + 1 for row_index2,row2 in list.iterrows(): if row['ID'] == row2['ID']: time_difference = row['Time'] - row2['Time'] time_difference = time_difference.total_seconds() if time_difference < 3601 and time_difference > 0: test.loc[a, 'result'] = "short waiting time" ```
2019/12/25
[ "https://Stackoverflow.com/questions/59481865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11986289/" ]
You can easily generate the indexing array with `r_`. ``` In [165]: np.r_[0,3:15] Out[165]: array([ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` under the covers it's just doing ``` In [166]: np.concatenate([[0],np.arange(3,15)]) Out[166]: array([ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` `np.delete`, while convenient, ends up with a similar amount of work. Depending on the deletion index it will either concatenate pieces, or construct a selection mask. Regardless of the method, the result is a new array, with a copy of the required data (not a view). `loadtxt` accepts as `usecols` parameter that takes a similar column index array.
This should work: ``` import numpy as np data = np.loadtxt('wind.data') data_nomonth_noday = np.zeros((data.shape[0],data.shape[1]-2)) data_nomonth_noday[:,0] = data[:,0] data_nomonth_noday[:,1:] = data[:,3:] ``` In my opinion this is more readable,flexible and intuitive than some of the other possible ways of doing this
59,481,865
Could you please take a look at my code and give me some advice how I might improve my code so it takes less time to process? Main purpose is to look at each row (ID) at test table and find same ID at list table, if it's match then look at time difference between the two identical ID and label them as if it takes less than 1 hours (3600s) or not. Thanks in advance test.csv has two col (ID, time) and 100K rows list.csv has tow col (ID, time) and 40k rows sample data: ID Time 83d-36615fa05fb0 2019-12-11 10:41:48 ``` a = -1 for row_index,row in test.iterrows(): a = a + 1 for row_index2,row2 in list.iterrows(): if row['ID'] == row2['ID']: time_difference = row['Time'] - row2['Time'] time_difference = time_difference.total_seconds() if time_difference < 3601 and time_difference > 0: test.loc[a, 'result'] = "short waiting time" ```
2019/12/25
[ "https://Stackoverflow.com/questions/59481865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11986289/" ]
This should work: ``` import numpy as np data = np.loadtxt('wind.data') data_nomonth_noday = np.zeros((data.shape[0],data.shape[1]-2)) data_nomonth_noday[:,0] = data[:,0] data_nomonth_noday[:,1:] = data[:,3:] ``` In my opinion this is more readable,flexible and intuitive than some of the other possible ways of doing this
If `a` is your `numpy` array and you want to drop the columns: `1,2`, you could do that using the following in a single line. ```py import numpy as np delete_cols = [1,2] # list of column numbers to delete a[:,list(set(np.arange(a.shape[-1])) - set(delete_cols))] ``` ### Some Explanation What you need here is proper indexing of the array `a`. ```py # list_of_column_numbers = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] a[:, list_of_column_numbers] ``` > > You can make the `list_of_column_numbers` in one of the following ways: > > > ```py # Method-1: Direct Declaration list_of_column_numbers = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # Method-2A: Using Set and Dropping Columns not Needed # a.shape[-1] = 15 delete_cols = [1,2] # list of column numbers to delete list_of_column_numbers = list(set(np.arange(a.shape[-1])) - set(delete_cols)) # Method-2B: Make list of column numbers # a.shape[-1] = 15 list_of_column_numbers = [0] + np.arange(3,a.shape[-1]).tolist() ```
18,046,942
I've got some client code, in this example `MyModule`, that defines some custom Exceptions in a sub module called `Exception`. In `MyModule` there is a `rescue` block that references `Exception`. The problem is, ruby is resolving the name `Exception` to be `MyModule::Exception` (a module) when it needs to be the base Exception class from core ruby. Here's a code illustration to show what I mean: ``` puts Exception puts Exception.class module MyModule module Exception class CustomError < StandardError end end end module MyModule puts Exception puts Exception.class end ``` The resulting output is: ``` Exception Class MyModule::Exception Module ``` How can I force the second `Exception` reference to resolve to the core ruby `Exception` class when there is no module to distinguish it? I've tried Kernel::Exception and investigating whether there is a method to get the module its in, but there seems to only be `#name`, which produces the fully qualified name of the class.
2013/08/04
[ "https://Stackoverflow.com/questions/18046942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483247/" ]
When in doubt, you need to specify fully qualified name (FQN) for a class. Your exception has this FQN: ``` MyModule::Exception ``` but Exception from core is on top level (not nested in anything), so its FQN is just ``` ::Exception ``` And yes, you probably **don't want** to rescue core `Exception`. It's bad practice, because this handler will catch more things than you can handle (signals, load errors, etc)
Figured it out. On a lark, I tried `::Exception`, which makes a weird sort of sense.
66,950
I'm currently working on a short story in which the main character has received a device from an anonymous individual. This device *appears* to function like a regular phone. Until he realizes that he can send text messages up to 1 hour back into the past. My question being... How would such a device (theoretically) function? Note: Handwaving is allowed but do NOT make your entire answer one big handwave
2017/01/05
[ "https://worldbuilding.stackexchange.com/questions/66950", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/31755/" ]
Such a device is called a tachyonic antitelephone. <https://en.wikipedia.org/wiki/Tachyonic_antitelephone> It relies on the existence of tachyons - particles that always go faster than light. This Worldbuilding idea has a fine answer walking through why FTL implies time travel. [Are there any ways to allow some form of FTL travel without allowing time travel?](https://worldbuilding.stackexchange.com/questions/46873/are-there-any-ways-to-allow-some-form-of-ftl-travel-without-allowing-time-travel)
It's not possible ================= Imagine this: A phone (let's call it phone A) gets destroyed. 30 minutes later, the *device* sends a message to phone A 1 hour in the past. There is *no* way that phone A could receive that message since it already got destroyed. It can no longer receive any message ever since it got destroyed, even if that message was sent before it got destroyed. This is the same problem with time travel. You cannot bring a dead person back to life in the real world.
66,950
I'm currently working on a short story in which the main character has received a device from an anonymous individual. This device *appears* to function like a regular phone. Until he realizes that he can send text messages up to 1 hour back into the past. My question being... How would such a device (theoretically) function? Note: Handwaving is allowed but do NOT make your entire answer one big handwave
2017/01/05
[ "https://worldbuilding.stackexchange.com/questions/66950", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/31755/" ]
Wormholes. ---------- Wormholes are hypothetical "connected black holes". In essence you have two points in spacetime which are always connected to each other, and matter and information could *potentially* pass from one to the other very quickly (apparently faster than lightspeed) without violating relativity. In real life we don't know if these actually exist, and even if we had one we don't know any way to put something through without it being obliterated. (After all, you just threw something into *a black hole*.) But since you're writing fiction you can ignore both of those points. More importantly, it hasn't been proven impossible; it's conceivable that in the future we'll discover stable wormholes and find a way to send something through. So suppose the creator of this telephone (a mad theoretical physicist on the Space Station who's a big fan of *Steins;Gate*) discovers a tiny, stable, traversable wormhole. He doesn't want to publish this absolutely phenomenal discovery until he's sure he really has found a wormhole. So, being mad, he decides to try a dramatic demonstration. The wormhole mouths have happened to move relative to each other in very contrived and convenient ways in the past. Now they're just over an hour apart in time. (Relativity can do this; see the "Twin Paradox".) So our mad physicist builds small "relays" which orbits the mouths, somehow not being destroyed by the gravitational forces. This special phone is capable of sending very short messages to the relays. When it does so, the first relay sends a signal through the wormhole in the present. The signal leaves the other mouth one hour in the past, from the sender's perspective; the second relay records it and transmits it back to the phone on Earth. And when the phone receives a message back from the relay, it sends it as a standard text message to the specified number. The physicist tests this...and it works! He can send causality-violating messages (within the confines of [Novikov's Principle](https://en.wikipedia.org/wiki/Novikov_self-consistency_principle))! This is certain to win him that Nobel he deserved twenty years earlier! But then, being as absent-minded as he is mad, he accidentally loses the phone. To anyone else picking it up, the phone seems magical. Send a text message and it arrives one hour in the past. Simple as that. This is the best method I can think of for not *blatantly* violating current physics.
It's not possible ================= Imagine this: A phone (let's call it phone A) gets destroyed. 30 minutes later, the *device* sends a message to phone A 1 hour in the past. There is *no* way that phone A could receive that message since it already got destroyed. It can no longer receive any message ever since it got destroyed, even if that message was sent before it got destroyed. This is the same problem with time travel. You cannot bring a dead person back to life in the real world.
66,950
I'm currently working on a short story in which the main character has received a device from an anonymous individual. This device *appears* to function like a regular phone. Until he realizes that he can send text messages up to 1 hour back into the past. My question being... How would such a device (theoretically) function? Note: Handwaving is allowed but do NOT make your entire answer one big handwave
2017/01/05
[ "https://worldbuilding.stackexchange.com/questions/66950", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/31755/" ]
Such a device is called a tachyonic antitelephone. <https://en.wikipedia.org/wiki/Tachyonic_antitelephone> It relies on the existence of tachyons - particles that always go faster than light. This Worldbuilding idea has a fine answer walking through why FTL implies time travel. [Are there any ways to allow some form of FTL travel without allowing time travel?](https://worldbuilding.stackexchange.com/questions/46873/are-there-any-ways-to-allow-some-form-of-ftl-travel-without-allowing-time-travel)
Wormholes. ---------- Wormholes are hypothetical "connected black holes". In essence you have two points in spacetime which are always connected to each other, and matter and information could *potentially* pass from one to the other very quickly (apparently faster than lightspeed) without violating relativity. In real life we don't know if these actually exist, and even if we had one we don't know any way to put something through without it being obliterated. (After all, you just threw something into *a black hole*.) But since you're writing fiction you can ignore both of those points. More importantly, it hasn't been proven impossible; it's conceivable that in the future we'll discover stable wormholes and find a way to send something through. So suppose the creator of this telephone (a mad theoretical physicist on the Space Station who's a big fan of *Steins;Gate*) discovers a tiny, stable, traversable wormhole. He doesn't want to publish this absolutely phenomenal discovery until he's sure he really has found a wormhole. So, being mad, he decides to try a dramatic demonstration. The wormhole mouths have happened to move relative to each other in very contrived and convenient ways in the past. Now they're just over an hour apart in time. (Relativity can do this; see the "Twin Paradox".) So our mad physicist builds small "relays" which orbits the mouths, somehow not being destroyed by the gravitational forces. This special phone is capable of sending very short messages to the relays. When it does so, the first relay sends a signal through the wormhole in the present. The signal leaves the other mouth one hour in the past, from the sender's perspective; the second relay records it and transmits it back to the phone on Earth. And when the phone receives a message back from the relay, it sends it as a standard text message to the specified number. The physicist tests this...and it works! He can send causality-violating messages (within the confines of [Novikov's Principle](https://en.wikipedia.org/wiki/Novikov_self-consistency_principle))! This is certain to win him that Nobel he deserved twenty years earlier! But then, being as absent-minded as he is mad, he accidentally loses the phone. To anyone else picking it up, the phone seems magical. Send a text message and it arrives one hour in the past. Simple as that. This is the best method I can think of for not *blatantly* violating current physics.
3,220,176
I set a Date with 'DateFromComponents" and when I read it out... its wrong. I have to set the DAY to the 2nd or anything later so I get the right Year?!? I set year 2011 and when I read it out i get Year 2010 !! --- ``` day = 1; month = 1; year = 2011; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; [components setDay:day]; [components setMonth:month]; [components setYear:year]; NSDate *date = [gregorian dateFromComponents:components]; [gregorian release]; NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"DD MMMM YYYY"]; NSLog (@"hmm: %@",[dateFormatter stringFromDate:actDate]); ``` ------- Here I get `1 January 2010 /// 2010 not 2011` !?!? how to fix that. thx chris
2010/07/10
[ "https://Stackoverflow.com/questions/3220176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355372/" ]
I ran this code: ``` NSInteger day = 1; NSInteger month = 1; NSInteger year =0; NSCalendar *gregorian; NSDateComponents *components; NSDate *theDate; NSDateFormatter *dateFormatter; for (int i=2005; i<2015; i++) { year= i; gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; components = [[NSDateComponents alloc] init]; [components setDay:day]; [components setMonth:month]; [components setYear:year]; theDate = [gregorian dateFromComponents:components]; [gregorian release]; dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"DD MMMM YYYY"]; NSLog(@"year=%d",year); NSLog (@"hmm: %@",[dateFormatter stringFromDate:theDate]); NSLog(@"theDate=%@\n\n",theDate); } ``` ... and got this output: ``` year=2005 hmm: 01 January 2004 theDate=2005-01-01 00:00:00 -0600 year=2006 hmm: 01 January 2006 theDate=2006-01-01 00:00:00 -0600 year=2007 hmm: 01 January 2007 theDate=2007-01-01 00:00:00 -0600 year=2008 hmm: 01 January 2008 theDate=2008-01-01 00:00:00 -0600 year=2009 hmm: 01 January 2008 theDate=2009-01-01 00:00:00 -0600 year=2010 hmm: 01 January 2009 theDate=2010-01-01 00:00:00 -0600 year=2011 hmm: 01 January 2010 theDate=2011-01-01 00:00:00 -0600 year=2012 hmm: 01 January 2012 theDate=2012-01-01 00:00:00 -0600 year=2013 hmm: 01 January 2013 theDate=2013-01-01 00:00:00 -0600 year=2014 hmm: 01 January 2014 theDate=2014-01-01 00:00:00 -0600 ``` Clearly the problem is in the formatter and not the date. However, I don't see what could be wrong with the formatter. . **Edit:** Shifting: ``` [dateFormatter setDateFormat:@"DD MMMM YYYY"]; ``` ... to: ``` [dateFormatter setDateFormat:@"DD MMMM yyyy"]; ``` ... solves the problem although I don't know why.
As stated in <http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns>, YYYY can differ from the calendar year. January 1st can belong to the last week of the year before. YYYY will display the year used when mentioning weeks of year (ie week 52 of 2009). If January 1st 2010 belong to the week 52 of 2009, then YYYY will display 2009. That's why you should use yyyy.
15,882
Let's take some old popular at a time but abandoned game: WorldRacing/HiOctane/Constructor/any other. Say I with a team want to revitalize said game and bring it to year 2011 without major changes and then work on improving it (e.g. add multiplayer). Also it is important to keep the game's spirit, assets, story, music, so basically the game remains the same, but gets better (e.g. adapting DOS game to Win7). My questions are from "How is it usually made?" area: * How do I purchase rights to the title and the game's assets (graphics, sounds, music, storyline). Whom to contact and what purchase options are possible? Is it possible to obtain source codes, design documents. * How to deal with various platforms, is it terms of contract saying which platforms are allowed to be used if there are several? * How to deal with localizations in other languages, are they to obtain from other companies or do they belong to master publisher? * What could be the reasonable price for said games in example? * Is it possible to pursue owners to release the game as open source? Remember Heroes of Might and Magic was owned by New World Computing, but later changed its owner to Nival. I'm interested in that sort of process.
2011/08/12
[ "https://gamedev.stackexchange.com/questions/15882", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/3644/" ]
[Byte published a high-level summary of the "abandonware" situation in 2001, which answers many of these questions.](http://www.savetz.com/articles/byte-abandonware.php) However, it's dealing with the case where you simply want the company to re-release the software or release it into the public domain. If you intend to license it and resell it, you will definitely need a lawyer to draft up a contract to protect *your* commercial rights, at some point in the process. > > How To Do It > > > You don't need to be an attorney or work at a software publisher to bring new life to old software anyone can help make it happen. The hardest part is often finding the right person to ask. If the company that published the software has been sold, you'll have to find out who bought it: A little Web research goes a long way here. > > > Once you find the company, it's time to approach their attorneys. Call the company's main office and ask for the legal department, or write to the company. The person you talk to may not have heard of the software you're referring to, so be ready to provide as many details as possible, including who published it, in what year, and for what platforms. > > > Also, know what you want: Asking for a license to distribute the software for free on your web site may be reasonable to many publishers. Or perhaps you'd like the publisher to release the software into the public domain an option that will be distasteful to many publishers who are unwilling to completely give up rights to their work, no matter how old. Don't expect an answer right away even once you find a helpful individual, it may take months for them to give you an answer. > > > To answer your specific queries: > > Whom to contact and what purchase options are possible? > > > You contact whoever owns the copyrights. This can actually be very tricky to track down in the case of some old games, and unfortunately, there is no general way to handle it. In some cases the paper trail may just be buried too deep, and you're SOL. For example, as described in the Byte article, the legal records needed to transfer the rights to MECC's game catalog are apparently gone forever. > > Is it possible to obtain source codes, design documents. > How to deal with localizations in other languages, are they to obtain from other companies or do they belong to master publisher? > > > They're assets like any other. These may have been owned by a different party to begin with; they may have been sold to a different party during liquidation; they may be lost forever. Some things, like trademarks, may now be owned by entirely unrelated entities. If they're actually using them for their unrelated business, you probably can't get them at all. > > How to deal with various platforms, is it terms of contract saying which platforms are allowed to be used if there are several? > What could be the reasonable price for said games in example? > > > This depends entirely on your negotiating skill. You want to convince the current holders it's worth $0 to them, and that even $1 would be a great move on their part to let you remake the game on all platforms. > > Is it possible to pursue owners to release the game as open-source? > > > Sure. Open source licensing is licensing like any other. If you have the rights, you can do what you want.
You've asked a lot of questions here - let me cherry pick one of them. > > How to deal with localizations in other languages, are they to obtain > from other companies or do they belong to master publisher? > > > Localization is also one of those areas where it could be managed on a case-by-case basis. Most companies I have worked with treat any localization work provided by the republisher (the localizing local publisher) as a slightly limited work for hire, meaning, the republisher probably has exclusive rights for the localized version while the republishing agreement is in effect. That said, if you acquire the rights to a product, you need to do proper due diligence and have your expectations incorporated into the agreement.
45,348
I have a [LoRa Click](https://learn.mikroe.com/lora-rf-click-solution-for-iot-developers/) Module and [Adafruit Ultimate GPS](https://www.adafruit.com/product/746) which both use Serial Communication. I wish to just check the initial tests with all the components in on the Serial Console. Hence I have declared : * `SoftwareSerial GPSSerial(10,11);` * `SoftwareSerial LoRaSerial(5,6);` Apparently when I declare them and upload the code on the board I do not obtain any information. ### observations 1. However when I comment out the `LoRaSerial` declaration I obtain the GPS coordinates. 2. When I set the `SoftwareSerial LoRaSerial(10,11)` I retrieve the information. 3. I thought `5,6` pins won't be the right choice and hence went on the set `SoftwareSerial(8,9)` but I retreive no information. ### inference Nano cannot take into consideration more than 1 SoftwareSerial Component. However the Official Documentation states that all Digital pins can be used for Software Serial. Is it too much for a Nano to have overall **3** Serial ports (including `Serial` itself)? ### sketch ``` #include <SoftwareSerial.h> #include <TheThingsNetwork.h> SoftwareSerial GPSSerial(10, 11); //RX , TX SoftwareSerial LoRaSerial(8,9); // RX, TX (tried with 5,6 too) #define freqPlan TTN_FP_EU868 TheThingsNetwork ttn(LoRaSerial, Serial, freqPlan); void setup() { Serial.begin(115200); GPSSerial.begin(9600); LoRaSerial.begin(57600); } void loop() { delay(2000); while (GPSSerial.available()) { char c = GPSSerial.read(); Serial.write(c); } delay(2000); while (LoRaSerial.available()) { ttn.showStatus(); } delay(2000); } ```
2017/10/06
[ "https://arduino.stackexchange.com/questions/45348", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/37223/" ]
You cannot use two SoftwareSerial instances at the same time - or not for receiving anyway. SoftwareSerial is a "last resort" system - only to be used if there is absolutely no other option. And then you need to be aware of certain information and rules: * Only one device can *listen* at any time, switchable using the `SoftwareSerial::listen()` method * When a byte is being received nothing else can happen - it takes over the entire CPU for the duration of reception * When a byte is being transmitted nothing else can happen - it takes over the entire CPU for the duration of transmission * There is a minimum required time between successive bytes when receiving that causes problems at higher baud rates These limitations mean that, when using multiple devices, you have to know before hand which device will be sending you data so you can be ready to receive it. It also means that SoftwareSerial is effectively half duplex - it only really works properly when you are either only receiving, only transmitting, or using a "call-response" scenario like sending "AT" commands and looking for a response afterwards. So the general recommendation is: use hardware UARTs whenever possible (and if you don't have enough, then consider using a different, more suitable, board with multiple UARTs), and if you *must* use SoftwareSerial then limit yourself to only *one* instance of it. As a last resort you can always use multiple boards and connect them using a different system, such as I2C.
Sometimes, with some devices, SoftwareSerial can struggle at higher baud rates, there are quite a few posts on here about it. Would it be possible to set the LoRaSerial to 9600 too? Can you try just the LoRaSerial on its own? Do you have a second device, could you wire the SoftwareSerials on you Nano to two Software Serial ports on your second device and then squirt anything it receives to the hardware serial port (and then to the console). Then send some test messages from the Nano and see if the device picks them up? ESP8266 have 2 and a half serial ports (Serial1 is Tx only), but unless you were going to hook the ESP to the Nano via I2C or use the ESP instead of the Nano, that's probably not going to help you in the case.
1,851,292
I've gone through [this SO question](https://stackoverflow.com/questions/246058/system-invalidoperationexception-the-object-is-currently-in-use-elsewhere-ho) but it didn't help. The case here is different. I'm using Backgroundworkers. 1st backgroundworker starts operating on the image input of user and inside firstbackgroundworker\_runworkercompleted() I'm using calling 3 other backgroundworkers ``` algo1backgroundworker.RunWorkerAsync(); algo2backgroundworker.RunWorkerAsync(); algo3backgroundworker.RunWorkerAsync(); ``` this is the code for each: ``` algo1backgroundworker_DoWork() { Image img = this.picturebox.Image; imgclone = img.clone(); //operate on imgclone and output it } algo2backgroundworker_DoWork() { Image img = this.picturebox.Image; imgclone = img.clone(); //operate on imgclone and output it } ``` similar operations are done in other algo\*backgrougrondworker\_doWork(). Now SOMETIMES I'm getting "InvalidOperationException - object is currently in use elsewhere". Its very arbitrary. I somtimes get this in algo1backgroundworker\_DoWork and sometimes in algo2backgroundworker\_DoWork and sometimes in Application.Run(new myWindowsForm()); I've no clue about whats happening.
2009/12/05
[ "https://Stackoverflow.com/questions/1851292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193653/" ]
So it looks like your BackgroundWorkers are trying to access the same Windows Forms components at the same time. This would explain why the failure is random. You'll need to make sure this doesn't happen by using a `lock`, perhaps like so: ``` private object lockObject = new object(); algo1backgroundworker_DoWork() { Image imgclone; lock (lockObject) { Image img = this.picturebox.Image; imgclone = img.clone(); } //operate on imgclone and output it } ``` Note that I make sure that imgclone is local to this method - you definitely don't want to share it across all the methods! On the other hand the same lockObject instance is used by all the methods. When a BackgroundWorker method enters its `lock{}` section, others that come to that point will be blocked. So it's important to make sure that the code in the locked section is fast. When you come to "output" your processed image, be careful too to make sure that you don't do a cross-thread update to the UI. Check [this post](https://stackoverflow.com/questions/711408/best-way-to-invoke-any-cross-threaded-code) for a neat way to avoid that.
In windows forms not only should you only access the controls from a single thread but that thread should be the main application thread, the thread that created the control. This means that in DoWork you should not access any controls (without using Control.Invoke). So here you would call RunWorkerAsync passing in your image clone. Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs.Argument. Only the ProgressChanged and RunWorkerCompleted event handlers should interact with the GUI.
1,851,292
I've gone through [this SO question](https://stackoverflow.com/questions/246058/system-invalidoperationexception-the-object-is-currently-in-use-elsewhere-ho) but it didn't help. The case here is different. I'm using Backgroundworkers. 1st backgroundworker starts operating on the image input of user and inside firstbackgroundworker\_runworkercompleted() I'm using calling 3 other backgroundworkers ``` algo1backgroundworker.RunWorkerAsync(); algo2backgroundworker.RunWorkerAsync(); algo3backgroundworker.RunWorkerAsync(); ``` this is the code for each: ``` algo1backgroundworker_DoWork() { Image img = this.picturebox.Image; imgclone = img.clone(); //operate on imgclone and output it } algo2backgroundworker_DoWork() { Image img = this.picturebox.Image; imgclone = img.clone(); //operate on imgclone and output it } ``` similar operations are done in other algo\*backgrougrondworker\_doWork(). Now SOMETIMES I'm getting "InvalidOperationException - object is currently in use elsewhere". Its very arbitrary. I somtimes get this in algo1backgroundworker\_DoWork and sometimes in algo2backgroundworker\_DoWork and sometimes in Application.Run(new myWindowsForm()); I've no clue about whats happening.
2009/12/05
[ "https://Stackoverflow.com/questions/1851292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193653/" ]
There's a lock inside GDI+ that prevents two threads from accessing a bitmap at the same time. This is not a blocking kind of lock, it is a "programmer did something wrong, I'll throw an exception" kind of lock. Your threads are bombing because you are cloning the image (== accessing a bitmap) in all threads. Your UI thread is bombing because it is trying to draw the bitmap (== accessing a bitmap) at the same time a thread is cloning it. You'll need to restrict access to the bitmap to only one thread. Clone the images in the UI thread before you start the BGWs, each BGW needs its own copy of the image. Update the PB's Image property in the RunWorkerCompleted event. You'll lose some concurrency this way but that's unavoidable.
So it looks like your BackgroundWorkers are trying to access the same Windows Forms components at the same time. This would explain why the failure is random. You'll need to make sure this doesn't happen by using a `lock`, perhaps like so: ``` private object lockObject = new object(); algo1backgroundworker_DoWork() { Image imgclone; lock (lockObject) { Image img = this.picturebox.Image; imgclone = img.clone(); } //operate on imgclone and output it } ``` Note that I make sure that imgclone is local to this method - you definitely don't want to share it across all the methods! On the other hand the same lockObject instance is used by all the methods. When a BackgroundWorker method enters its `lock{}` section, others that come to that point will be blocked. So it's important to make sure that the code in the locked section is fast. When you come to "output" your processed image, be careful too to make sure that you don't do a cross-thread update to the UI. Check [this post](https://stackoverflow.com/questions/711408/best-way-to-invoke-any-cross-threaded-code) for a neat way to avoid that.
1,851,292
I've gone through [this SO question](https://stackoverflow.com/questions/246058/system-invalidoperationexception-the-object-is-currently-in-use-elsewhere-ho) but it didn't help. The case here is different. I'm using Backgroundworkers. 1st backgroundworker starts operating on the image input of user and inside firstbackgroundworker\_runworkercompleted() I'm using calling 3 other backgroundworkers ``` algo1backgroundworker.RunWorkerAsync(); algo2backgroundworker.RunWorkerAsync(); algo3backgroundworker.RunWorkerAsync(); ``` this is the code for each: ``` algo1backgroundworker_DoWork() { Image img = this.picturebox.Image; imgclone = img.clone(); //operate on imgclone and output it } algo2backgroundworker_DoWork() { Image img = this.picturebox.Image; imgclone = img.clone(); //operate on imgclone and output it } ``` similar operations are done in other algo\*backgrougrondworker\_doWork(). Now SOMETIMES I'm getting "InvalidOperationException - object is currently in use elsewhere". Its very arbitrary. I somtimes get this in algo1backgroundworker\_DoWork and sometimes in algo2backgroundworker\_DoWork and sometimes in Application.Run(new myWindowsForm()); I've no clue about whats happening.
2009/12/05
[ "https://Stackoverflow.com/questions/1851292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193653/" ]
There's a lock inside GDI+ that prevents two threads from accessing a bitmap at the same time. This is not a blocking kind of lock, it is a "programmer did something wrong, I'll throw an exception" kind of lock. Your threads are bombing because you are cloning the image (== accessing a bitmap) in all threads. Your UI thread is bombing because it is trying to draw the bitmap (== accessing a bitmap) at the same time a thread is cloning it. You'll need to restrict access to the bitmap to only one thread. Clone the images in the UI thread before you start the BGWs, each BGW needs its own copy of the image. Update the PB's Image property in the RunWorkerCompleted event. You'll lose some concurrency this way but that's unavoidable.
In windows forms not only should you only access the controls from a single thread but that thread should be the main application thread, the thread that created the control. This means that in DoWork you should not access any controls (without using Control.Invoke). So here you would call RunWorkerAsync passing in your image clone. Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs.Argument. Only the ProgressChanged and RunWorkerCompleted event handlers should interact with the GUI.