Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
| score_j
int64 0
14
| score_k
int64 -1
10
|
---|---|---|---|---|---|---|---|
41,983,979 | Configuring multiple sources for an agent throwing me lock error using FILE channel. Below is my config file.
```
a1.sources = r1 r2
a1.sinks = k1 k2
a1.channels = c1 c3
#sources
a1.sources.r1.type=netcat
a1.sources.r1.bind=localhost
a1.sources.r1.port=4444
a1.sources.r2.type=exec
a1.sources.r2.command=tail -f /opt/gen_logs/logs/access.log
#sinks
a1.sinks.k1.type=hdfs
a1.sinks.k1.hdfs.path=/flume201
a1.sinks.k1.hdfs.filePrefix=netcat-
a1.sinks.k1.rollInterval=100
a1.sinks.k1.hdfs.fileType=DataStream
a1.sinks.k1.hdfs.callTimeout=100000
a1.sinks.k2.type=hdfs
a1.sinks.k2.hdfs.path=/flume202
a1.sinks.k2.hdfs.filePefix=execCommand-
a1.sinks.k2.rollInterval=100
a1.sinks.k2.hdfs.fileType=DataStream
a1.sinks.k2.hdfs.callTimeOut=100000
#channels
a1.channels.c1.type=file
a1.channels.c1.checkpointDir=/home/cloudera/alpha/001
a1.channels.c3.type=file
a1.channels.c3.checkpointDir=/home/cloudera/beta/001
#bind r1 c1 k1
a1.sources.r1.channels=c1
a1.sinks.k1.channel=c1
a1.sources.r2.channels=c3
a1.sinks.k2.channel=c3
```
I am getting below error
```
Channel closed [channel=c3]. Due to java.io.IOException: Cannot lock /home/cloudera/.flume/file-channel/data. The directory is already locked. [channel=c3]
```
But when i am using memory channel. Its working fine. | 2017/02/01 | [
"https://Stackoverflow.com/questions/41983979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4029265/"
] | Change `.env` file in your app root
```
SESSION_LIFETIME=120
```
And value is in minutes. | Please modify true to false for Expire on close as:
```
'expire_on_close' => false,
``` | 4 | 1 |
41,983,979 | Configuring multiple sources for an agent throwing me lock error using FILE channel. Below is my config file.
```
a1.sources = r1 r2
a1.sinks = k1 k2
a1.channels = c1 c3
#sources
a1.sources.r1.type=netcat
a1.sources.r1.bind=localhost
a1.sources.r1.port=4444
a1.sources.r2.type=exec
a1.sources.r2.command=tail -f /opt/gen_logs/logs/access.log
#sinks
a1.sinks.k1.type=hdfs
a1.sinks.k1.hdfs.path=/flume201
a1.sinks.k1.hdfs.filePrefix=netcat-
a1.sinks.k1.rollInterval=100
a1.sinks.k1.hdfs.fileType=DataStream
a1.sinks.k1.hdfs.callTimeout=100000
a1.sinks.k2.type=hdfs
a1.sinks.k2.hdfs.path=/flume202
a1.sinks.k2.hdfs.filePefix=execCommand-
a1.sinks.k2.rollInterval=100
a1.sinks.k2.hdfs.fileType=DataStream
a1.sinks.k2.hdfs.callTimeOut=100000
#channels
a1.channels.c1.type=file
a1.channels.c1.checkpointDir=/home/cloudera/alpha/001
a1.channels.c3.type=file
a1.channels.c3.checkpointDir=/home/cloudera/beta/001
#bind r1 c1 k1
a1.sources.r1.channels=c1
a1.sinks.k1.channel=c1
a1.sources.r2.channels=c3
a1.sinks.k2.channel=c3
```
I am getting below error
```
Channel closed [channel=c3]. Due to java.io.IOException: Cannot lock /home/cloudera/.flume/file-channel/data. The directory is already locked. [channel=c3]
```
But when i am using memory channel. Its working fine. | 2017/02/01 | [
"https://Stackoverflow.com/questions/41983979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4029265/"
] | Check your php.ini for:
**session.gc\_maxlifetime** - Default 1440 secs - 24 mins
> **session.gc\_maxlifetime** specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc\_probability and session.gc\_divisor).
**session.cookie\_lifetime** - Default 0
>**session.cookie\_lifetime** specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session\_get\_cookie\_params() and session\_set\_cookie\_params().
In case it is less time than the Laravel configuration, the cookie will be removed because the local php.ini have **preference** over Laravel configuration.
You can just increase it or comment/delete.
In case is not solved something on your App is destroying the session.
**UPDATE**
After release [v5.5.22](https://github.com/laravel/laravel/releases/tag/v5.5.22) session lifetime is loaded from `.env` and is not hardcoded anymore at `config/session.php`, changes [there](https://github.com/laravel/laravel/commit/084f10004582299ef3897f6ec14315209d5c1df1#diff-cbfd64a28982a1818f2b5f16e7f9d634).
Now you can modify the session lifetime using:
```
SESSION_LIFETIME=90 //minutes
```
In your `.env` file. | Please modify true to false for Expire on close as:
```
'expire_on_close' => false,
``` | 5 | 1 |
22,153,836 | I am curious as to why Start-Job increments in twos. My worry is that I am doing something wrong that makes the ID of a new job jump by 2.
```
Start-Job -ScriptBlock {Get-WinEvent -LogName system -MaxEvents 1000}
```
Results as shown by Get-Job
```
Id Name State HasMoreData Command
-- ---- ----- ----------- -------
2 Job2 Completed False Get-WinEvent -LogName system -MaxEvents 1000
4 Job4 Completed False Get-WinEvent -LogName system -MaxEvents 1000
6 Job6 Completed True Get-WinEvent -LogName system -MaxEvents 1000
```
Question: Can you control the Start-Job Id increments, or force them to be just 1? | 2014/03/03 | [
"https://Stackoverflow.com/questions/22153836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200586/"
] | Each time you start a job, it consists of a parent job and one or more child jobs. If you run `get-job | fl` you'll see the child jobs, and you'll see that their names are the "missing" odd numbered names. | @1.618 give the right answer, here are some more details :
```
Start-Job -ScriptBlock {Get-Process}
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
2 Job2 BackgroundJob Running True localhost Get-Process
Get-Job | fl *
State : Completed
HasMoreData : True
StatusMessage :
Location : localhost
Command : Get-Process
JobStateInfo : Completed
Finished : System.Threading.ManualResetEvent
InstanceId : 49a67ca4-840b-49ec-b293-efa9303e38bb
Id : 2
Name : Job2
ChildJobs : {Job3}
PSBeginTime : 03/03/2014 20:43:54
PSEndTime : 03/03/2014 20:44:00
PSJobTypeName : BackgroundJob
Output : {}
Error : {}
Progress : {}
Verbose : {}
Debug : {}
Warning : {}
get-job -IncludeChildJob
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
2 Job2 BackgroundJob Completed True localhost Get-Process
3 Job3 Completed True localhost Get-Process
```
Here is why, when you start a job, powershell create two jobs ?
Windows PowerShell jobs created through `Start-Job` always consist of a parent job and a child job. The child job does the actual work. If you were running the job against a number of remote machines by using `Invoke-Command` and its `–AsJob` parameter, you would get one child job per remote machine.
When you manage jobs, anything you do to the parent job is automatically applied to any child jobs. Removing or stopping the parent job performs the same action on the child jobs. Getting the results of the parent job means you get the results of all the child jobs.
You can access the child jobs directly to retrieve their data, n a simple job, as in the example, you can access the data through the parent or child jobs :
```
Receive-Job -Id 2 -Keep
Receive-Job -Id 3 -Keep
```
When you have multiple child jobs, its usually easier to access the child jobs in turn:
```
$jobs = Get-Job -Name Job2 | select -ExpandProperty ChildJobs
foreach ($job in $jobs){Receive-Job -Job $job -Keep}
``` | 4 | 3 |
4,554,498 | I am creating a Chart (DataVisualization.Charting.Chart) programmatically, which is a Stacked Bar chart.
I am also adding Legend entries programmatically to it. I want to show the Legend at the bottom of the chart.
But, while doing so, the Legend overlapps with the X-axis of the chart.
Here is the code I am using:
```
Private Function GetLegend(ByVal legendName As String, ByVal s As Single) As System.Windows.Forms.DataVisualization.Charting.Legend
Dim objLegend As System.Windows.Forms.DataVisualization.Charting.Legend = New System.Windows.Forms.DataVisualization.Charting.Legend()
objLegend.Name = legendName
objLegend.Font = New System.Drawing.Font("Verdana", s)
objLegend.IsDockedInsideChartArea = False
objLegend.Docking = Docking.Bottom
Return objLegend
End Function
```
Below statement adds that Legend to the chart
```
_msChart.Legends.Add(GetLegend("SomeValue1", 10.0F))
```
Any idea, what is missing? I want to show the legend at the bottom only, but it should not overlapp with the X-axis. | 2010/12/29 | [
"https://Stackoverflow.com/questions/4554498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557172/"
] | I had the same problem today. Try adding:
```
objLegend.Position.Auto = true
objLegend.DockedToChartArea = "yourChartAreaName"
```
That did not help me but I found on the net that this might be helpful (and clean solution).
What actually worked for me was moving chart area to make space for legend so it no longer overlaps. My legend was on top so this code worked for me:
```
chart.ChartAreas[0].Position.Y = 15
```
You can try resizing it instead, forcing it to be for example 20 pixels shorter than `chart.Size`.
Hope this helps. | I had an overlapping legend/chart area problem as well but none of the other suggestions here seemed to make any difference. I think the problem stems from legend text wrapping to two lines and the sizing algorithms not taking account of this.
The ideas here got me thinking more clearly about the problem though, and I was able control the size and position of the chart area using the following.
```
Chart1.ChartAreas[0].InnerPlotPosition = new ElementPosition(15, 5, 90, 75);
```
There's not much intellisense on those parameters, but as well as I could deduce, the parameters are all percentages of the total chart area (I initially thought they might be pixel values and got some *very* odd results). So what I've written above would set the plot area to start at 15% in from the left edge of the chart image and 5% down from the top, and have a width of 90% and a height of 75%. | 2 | 0 |
35,854,555 | We will be developing a new web site for a client who already has a Kentico 8.2 license. I am trying to make a case for developing the site using Kentico 9. Some key features I have found so far include:
* faster performance (how much in real-world terms?)
* better integration with .Net MVC
* content staging tasks can be synchronized per user account
* better rollback functionality: previously we had to make full database backups, content staging in Kentico 8.2 causes issues for restoring previous versions of a page.
* built in source control support for GIT
It looks like Kentico integration with the client's existing database may be possible. Has anyone done this? What are the limitations or caveats?
Is there a discount for upgrading the license from 8.2 to 9?
Thanks in advance for your feedback! | 2016/03/07 | [
"https://Stackoverflow.com/questions/35854555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5971415/"
] | ### Preserving and Restoring State
Feature you are looking for is called State Restoration. From the [docs](http://State%20preservation%20records%20the%20configuration%20of%20your%20app%20before%20it%20is%20suspended%20so%20that%20the%20configuration%20can%20be%20restored%20on%20a%20subsequent%20app%20launch.):
> State preservation records the configuration of your app before it is
> suspended so that the configuration can be restored on a subsequent
> app launch.
How to tackle it:
1. Tag your view controllers for preservation. Assign restoration identifiers.
2. Restore view controllers at launch time. Encode and decode their state.
Topic is very broad but the [docs](https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/PreservingandRestoringState.html) explain it very well. | What you're trying to do is keep persistent data between launches of your application, right?
For that you should use core data, there are many useful recourses on the web to help you with that, heres a few helpful ones.
<https://developer.apple.com/library/watchos/documentation/Cocoa/Conceptual/CoreData/index.html>
<https://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started> | 0 | -1 |
35,854,555 | We will be developing a new web site for a client who already has a Kentico 8.2 license. I am trying to make a case for developing the site using Kentico 9. Some key features I have found so far include:
* faster performance (how much in real-world terms?)
* better integration with .Net MVC
* content staging tasks can be synchronized per user account
* better rollback functionality: previously we had to make full database backups, content staging in Kentico 8.2 causes issues for restoring previous versions of a page.
* built in source control support for GIT
It looks like Kentico integration with the client's existing database may be possible. Has anyone done this? What are the limitations or caveats?
Is there a discount for upgrading the license from 8.2 to 9?
Thanks in advance for your feedback! | 2016/03/07 | [
"https://Stackoverflow.com/questions/35854555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5971415/"
] | There are many tools available to you to persist data from an app. Choosing an appropriate one requires some understanding of your needs, or at least making a guess. Here's where I would start but keep an eye out in case my assumptions don't match your needs.
*What type of data do you want to persist?*
Presumably you want to store the array of Strings seen in `var name = Array<String>()` but maybe you have some other data type in mind.
*When do you need to read/write it (do you need to worry about multiple systems trying to write at the same time, is loading the data going to be very expensive because it is very large, do you only need to load a small piece at a time, ...)?*
Sounds like you're fine reading/writing all the data at once and only on app launch/termination. There could be a reasonable maximum size to this calculation history to total storage size is probably fairly small.
*How long does it need to be persisted?*
Calculation histories are usually nice to have but not a catastrophic loss if they go missing. It would be nice to keep this data around but the app will work without it. Depending on use it may or may not cost the user time and frustration if the data is deleted unexpectedly.
*Who needs access to it (is it also show on a web site, should it sync to all of a user's devices, ...)?*
It's probably enough to keep this history just on the local device.
**So what should we do?**
For a small amount of data loaded all at once and only used locally I would write this data to a file.
Since you're just working with an array of strings we can use a plist (<https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html>)
NSArray (note: not a Swift array) has `arrayWithContentsOfURL:` and `writeToURL:atomically:` which can be a convenient way to read and write plist compatible data.
Using a file means we need to decide where to store this file. Take a look at [Where You Should Put Your App’s Files](https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW28). In this case it seems reasonable to write this data to either `Documents` or `Library/Caches` depending on how you plan to use it.
With all that covered we could save this stack something like:
`let array = names as NSArray
guard let cachesURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first else {
print("Unable to find Caches directory, cannot save file.")
return
}
let fileURL = cachesURL.URLByAppendingPathComponent("history.plist")
array.writeToURL(fileURL, atomically: false)`
Reading the file is similar. You'll need the same URL so decide which component is responsible for deciding where to save/load this data and let it supply the URL to use. You'll also need to check if any saved history exists or not (note that `arrayWithContentsOfURL:` can return nil).
At some point you might find it useful to model this data as a more specific data type, perhaps defining your own struct to capture these operations. A custom type can't be automatically written to or read from a file so you'll need to do a little more work. Apple has a nice example of how you might use NSCoding to do that in their tutorials: <https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html> | What you're trying to do is keep persistent data between launches of your application, right?
For that you should use core data, there are many useful recourses on the web to help you with that, heres a few helpful ones.
<https://developer.apple.com/library/watchos/documentation/Cocoa/Conceptual/CoreData/index.html>
<https://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started> | 1 | -1 |
35,854,555 | We will be developing a new web site for a client who already has a Kentico 8.2 license. I am trying to make a case for developing the site using Kentico 9. Some key features I have found so far include:
* faster performance (how much in real-world terms?)
* better integration with .Net MVC
* content staging tasks can be synchronized per user account
* better rollback functionality: previously we had to make full database backups, content staging in Kentico 8.2 causes issues for restoring previous versions of a page.
* built in source control support for GIT
It looks like Kentico integration with the client's existing database may be possible. Has anyone done this? What are the limitations or caveats?
Is there a discount for upgrading the license from 8.2 to 9?
Thanks in advance for your feedback! | 2016/03/07 | [
"https://Stackoverflow.com/questions/35854555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5971415/"
] | There are many tools available to you to persist data from an app. Choosing an appropriate one requires some understanding of your needs, or at least making a guess. Here's where I would start but keep an eye out in case my assumptions don't match your needs.
*What type of data do you want to persist?*
Presumably you want to store the array of Strings seen in `var name = Array<String>()` but maybe you have some other data type in mind.
*When do you need to read/write it (do you need to worry about multiple systems trying to write at the same time, is loading the data going to be very expensive because it is very large, do you only need to load a small piece at a time, ...)?*
Sounds like you're fine reading/writing all the data at once and only on app launch/termination. There could be a reasonable maximum size to this calculation history to total storage size is probably fairly small.
*How long does it need to be persisted?*
Calculation histories are usually nice to have but not a catastrophic loss if they go missing. It would be nice to keep this data around but the app will work without it. Depending on use it may or may not cost the user time and frustration if the data is deleted unexpectedly.
*Who needs access to it (is it also show on a web site, should it sync to all of a user's devices, ...)?*
It's probably enough to keep this history just on the local device.
**So what should we do?**
For a small amount of data loaded all at once and only used locally I would write this data to a file.
Since you're just working with an array of strings we can use a plist (<https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html>)
NSArray (note: not a Swift array) has `arrayWithContentsOfURL:` and `writeToURL:atomically:` which can be a convenient way to read and write plist compatible data.
Using a file means we need to decide where to store this file. Take a look at [Where You Should Put Your App’s Files](https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW28). In this case it seems reasonable to write this data to either `Documents` or `Library/Caches` depending on how you plan to use it.
With all that covered we could save this stack something like:
`let array = names as NSArray
guard let cachesURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first else {
print("Unable to find Caches directory, cannot save file.")
return
}
let fileURL = cachesURL.URLByAppendingPathComponent("history.plist")
array.writeToURL(fileURL, atomically: false)`
Reading the file is similar. You'll need the same URL so decide which component is responsible for deciding where to save/load this data and let it supply the URL to use. You'll also need to check if any saved history exists or not (note that `arrayWithContentsOfURL:` can return nil).
At some point you might find it useful to model this data as a more specific data type, perhaps defining your own struct to capture these operations. A custom type can't be automatically written to or read from a file so you'll need to do a little more work. Apple has a nice example of how you might use NSCoding to do that in their tutorials: <https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html> | ### Preserving and Restoring State
Feature you are looking for is called State Restoration. From the [docs](http://State%20preservation%20records%20the%20configuration%20of%20your%20app%20before%20it%20is%20suspended%20so%20that%20the%20configuration%20can%20be%20restored%20on%20a%20subsequent%20app%20launch.):
> State preservation records the configuration of your app before it is
> suspended so that the configuration can be restored on a subsequent
> app launch.
How to tackle it:
1. Tag your view controllers for preservation. Assign restoration identifiers.
2. Restore view controllers at launch time. Encode and decode their state.
Topic is very broad but the [docs](https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/PreservingandRestoringState.html) explain it very well. | 1 | 0 |
9,415 | What does テラス means in the context of declining an invitation, like below?
> うううううう!!いきたい!けどその時間帯もろに仕事だ:::またやって!!テラスーーーーー
I guess it is slang?
I am familiar with テラワロス but it seems different in both spelling and context.
More context: Public comment sent on a night-time birthday event page on a social network. テラス is not her nickname. | 2012/11/13 | [
"https://japanese.stackexchange.com/questions/9415",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/107/"
] | So far the only viable explanation I can think of is that テラス is a contracted form of テラワロス.
* [ニコニコ[百科]{ひゃっか} entry for テラス](http://dic.nicovideo.jp/a/%E3%83%86%E3%83%A9%E3%82%B9) defines it as: `3. テラワロスの略`
+ 3rd sense: Contraction of "terawarosu"
* [a 2ch.net post](http://2chnull.info/r/train/1273323743/901-1000) says:`「法テラス」(テラワロスじゃないぞw)`
+ "Law-terrace" (and no, it's not "terawarosu" lol)
* [a blog post](http://blog.kanjosen.com/?eid=1006137) writes: `「針テラス(テラワロスではない。2ちゃんの見過ぎ)」`
+ "[Hari Tea-time Resort Station](http://hari-trs.com/haritrs.html) (to 2ch addicts: it's not "terawarosu")"
As to why you'd want to "roll on the floor laughing" in the context of declining an invitation, I don't have a definitive answer, but maybe one of these:
* She's laughing at the unexpected coincidence of the event and her work.
* She's laughing at herself for having to work when everyone else is able to attend the event. Perhaps the time of the event is normally considered overtime?
* She's softening the request to hold another event for her by adding a laugh. | I'm Japanese, but I've never heard Japanese people using テラス. That's not even slang. I don't understand its meaning. | 4 | 2 |
471,151 | $(l^2,\|\cdot\|\_2)$ is a Hilbert space with scalar product $\langle x,y\rangle=\sum^{\infty}\_{k=1}x\_ky\_k$.
How can I show that every vector $x\in l^2$ can be written in a form $\sum^{\infty}\_{k=1}x\_ke^k$ where $e^k,k\in N$ are unit vectors? | 2013/08/19 | [
"https://math.stackexchange.com/questions/471151",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/20885/"
] | By definition equality
$$
x=\sum\limits\_{k=1}^\infty x\_k e^k
$$
means that
$$
x=\lim\limits\_{n\to\infty}\sum\limits\_{k=1}^n x\_k e^k
$$
which by definition means that
$$
\lim\limits\_{n\to\infty}\left\Vert x-\sum\limits\_{k=1}^n x\_k e^k\right\Vert\_2=0\tag{1}
$$
Now use the fact that $\Vert z\Vert\_2^2=\langle z,z\rangle$ to reduce $(1)$ to
$$
\lim\limits\_{n\to\infty}\sum\limits\_{k=n+1}^\infty |x\_k|^2=0\tag{2}
$$
Note that I used here the fact that $\Vert e^k\Vert\_2=1$. I suggest you to recall that $x\in \ell\_2$, to understand why $(2)$ holds. | Let's take $x$ and define $x\_k:=\langle x,e\_k\rangle$. Now we need to prove that the vector
$$y=\sum\_k x\_ke\_k$$
exists and equal to $x$.
First, we show that it exists: the series converges by [pythagorean identity](http://en.wikipedia.org/wiki/Hilbert_space#Pythagorean_identity) ); moreover, it converges to the norm of $x$, because of [Parseval's identity](http://en.wikipedia.org/wiki/Parseval_identity).
$$\|y\|^2=\left\|\sum\_k x\_ke\_k\right\|=\sum\_k x\_k^2 = \|x\|^2.$$
Now clearly the difference $y-x$ is orthogonal to the $E$ - the basis of $H$, hence $y-x\in Cl(E)=H$ (because our space is complete), thus $y-x=0$. | 3 | 1 |
177,933 | Harry Potter chose to come back from the dead because he was the master of death. But how could he be the master of death as he never had the Elder Wand?
If Harry could come back does that mean that Dumbledore could come back from the dead too? Why/why not?
After all, Dumbledore did have the three Deathly Hallows. He owned the Elder Wand and the Resurrection Stone and the Cloak of Invisibility. He passes the Cloak to Harry, but he still owned it: you can give something to someone but you are still the owner of it.
So when you die as the master of death you have a choice to come back. Dumbledore died as master of death but he never came back.
Does that means that Dumbledore did not choose to come back or that he cannot and the Deathly Hallows don't work like this? | 2018/01/02 | [
"https://scifi.stackexchange.com/questions/177933",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/93971/"
] | There are many fundamental errors in your question itself. I really suggest you go back and read the books because your understanding of both the Hallows and Harry's resurrection is wrong.
Firstly, Harry was the owner of Elder Wand having won it from Draco Malfoy when he escaped from Malfoy Manor. Draco became the owner of Elder wand when he disarmed Dumbledore at the end of Half-blood Prince. Both these points are explained in the book.
Next, Dumbledore never owned the invisibility cloak, it belonged to James Potter. Dumbledore merely borrowed it to examine suspecting that it was one of the Hallows. After the death of the Potters he simply kept it till the time Harry came to Hogwarts and then passed it to Harry during his first year telling him that the cloak had once belonged to his father.
And most important, Harry did not come back from the dead because he was able to unite the Hallows. He came back from the dead because when Voldemort cast the killing curse on Harry, he killed a part of his own soul which was living inside Harry (as Harry was the Horcrux which he never intended to make).
Even if a person can unite all the Hallows I don't think they gain the ability to come back from the dead. As it is explained in the books, Hallows were just very powerful magical objects created by Wizards and the whole lore about possessor of Hallows being "Master of Death" was just a fairytale which was based on these powerful magical objects.
> “So it’s true?” asked Harry. “All of it? The Peverell brothers—”
>
>
> “—were the three brothers of the tale,” said Dumbledore, nodding. “Oh
> yes, I think so. Whether they met Death on a lonely road . . . I think
> it more likely that the Peverell brothers were simply gifted,
> dangerous wizards who succeeded in creating those powerful objects.
> The story of them being Death’s own Hallows seems to me the sort of
> legend that might have sprung up around such creations.
>
>
> “You. You have guessed, I know, why the Cloak was in my possession on
> the night your parents died. James had showed it to me just a few days
> previously. It explained so much of his undetected wrong-doing at
> school! I could hardly believe what I was seeing. I asked to borrow
> it, to examine it.”
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross*
The reason why Harry didn't die was also explained by Dumbledore. The reason for it wasn't the Hallows, even though Harry was the owner of all three Hallows by the time he went to the forest to face Voldemort.
> “But you’re dead.” said Harry.
>
>
> “Oh yes,” said Dumbledore matter-of-factly.
>
>
> “Then . . . I’m dead too?”
>
>
> “Ah,” said Dumbledore, smiling still more broadly. “That is the question,
> isn’t it? On the whole, dear boy, I think not.”
>
>
> “But . . . ” Harry raised his hand
> instinctively towards the lightning scar. It did not seem to be there.
> “But I should have died—I didn’t defend myself! I meant to let him
> kill me!”
>
>
> “And that,” said Dumbledore, “will, I think, have made all
> the difference.”
>
>
> “I let him kill me,” said Harry. “Didn’t I?”
>
>
> “You did,” said Dumbledore, nodding. “Go on!”
>
>
> “So the part of his soul that
> was in me . . . ”
>
>
> Dumbledore nodded still more enthusiastically,
> urging Harry onward, a broad smile of encouragement on his face.
>
>
> “. . . has it gone?”
>
>
> “Oh yes!” said Dumbledore. “Yes, he destroyed it. Your
> soul is whole, and completely your own, Harry.”
>
>
> “But if Voldemort used
> the Killing Curse,” Harry started again “and nobody died for me this
> time—how can I be alive?”
>
>
> “I think you know,” said Dumbledore. “Think
> back. Remember what he did, in his ignorance, in his greed and his
> cruelty.”
>
>
> “He took my blood.” said Harry.
>
>
> “Precisely!” said
> Dumbledore. “He took your blood and rebuilt his living body with it!
> Your blood in his veins, Harry, Lily’s protection inside both of you!
> He tethered you to life while he lives!”
>
>
> “I live . . . while he lives!
> But I thought . . . I thought it was the other way round! I thought we
> both had to die? Or is it the same thing?”
>
>
> “You were the seventh
> Horcrux, Harry, the Horcrux he never meant to make. He had rendered
> his soul so unstable that it broke apart when he committed those acts of unspeakable evil, the murder of your parents, the at- tempted killing of a child. But what escaped from that room was even less than he knew. He left more than his body behind.
> He left part of himself latched to you, the would-be victim who had survived.
>
>
> “He took your blood believing it would strengthen him. He took into
> his body a tiny part of the enchantment your mother laid upon you when
> she died for you. His body keeps her sacrifice alive, and while that
> enchantment survives, so do you and so does Voldemort’s one last hope
> for himself.”
>
>
> “Without meaning to, as you now know, Lord Voldemort
> doubled the bond between you when he returned to a human form. A part
> of his soul was still attached to yours, and, thinking to strengthen
> himself, he took a part of your mother’s sacrifice into himself.”
>
>
> Harry sat in thought for a long time, or perhaps seconds. It was very hard
> to be sure of things like time, here.
>
>
> “He killed me with your wand.”
>
>
> “He *failed* to kill you with my wand,” Dumbledore corrected Harry. “I
> think we can agree you are not dead.
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross* | Dumbledore was never the master of death.
At the time he was in possession of the Elder Wand and the Resurrection Stone, Harry was in possession of the Cloak of Invisibility.
Harry was not the master of death when he 'died', as he did not possess the Elder Wand. There is no concrete answer as to why Harry survived. Most theories center around either the Horcrux inside Harry being killed instead of him, or Harry having the *allegiance* of the Elder Wand when it struck him down. | 8 | 2 |
177,933 | Harry Potter chose to come back from the dead because he was the master of death. But how could he be the master of death as he never had the Elder Wand?
If Harry could come back does that mean that Dumbledore could come back from the dead too? Why/why not?
After all, Dumbledore did have the three Deathly Hallows. He owned the Elder Wand and the Resurrection Stone and the Cloak of Invisibility. He passes the Cloak to Harry, but he still owned it: you can give something to someone but you are still the owner of it.
So when you die as the master of death you have a choice to come back. Dumbledore died as master of death but he never came back.
Does that means that Dumbledore did not choose to come back or that he cannot and the Deathly Hallows don't work like this? | 2018/01/02 | [
"https://scifi.stackexchange.com/questions/177933",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/93971/"
] | There are many fundamental errors in your question itself. I really suggest you go back and read the books because your understanding of both the Hallows and Harry's resurrection is wrong.
Firstly, Harry was the owner of Elder Wand having won it from Draco Malfoy when he escaped from Malfoy Manor. Draco became the owner of Elder wand when he disarmed Dumbledore at the end of Half-blood Prince. Both these points are explained in the book.
Next, Dumbledore never owned the invisibility cloak, it belonged to James Potter. Dumbledore merely borrowed it to examine suspecting that it was one of the Hallows. After the death of the Potters he simply kept it till the time Harry came to Hogwarts and then passed it to Harry during his first year telling him that the cloak had once belonged to his father.
And most important, Harry did not come back from the dead because he was able to unite the Hallows. He came back from the dead because when Voldemort cast the killing curse on Harry, he killed a part of his own soul which was living inside Harry (as Harry was the Horcrux which he never intended to make).
Even if a person can unite all the Hallows I don't think they gain the ability to come back from the dead. As it is explained in the books, Hallows were just very powerful magical objects created by Wizards and the whole lore about possessor of Hallows being "Master of Death" was just a fairytale which was based on these powerful magical objects.
> “So it’s true?” asked Harry. “All of it? The Peverell brothers—”
>
>
> “—were the three brothers of the tale,” said Dumbledore, nodding. “Oh
> yes, I think so. Whether they met Death on a lonely road . . . I think
> it more likely that the Peverell brothers were simply gifted,
> dangerous wizards who succeeded in creating those powerful objects.
> The story of them being Death’s own Hallows seems to me the sort of
> legend that might have sprung up around such creations.
>
>
> “You. You have guessed, I know, why the Cloak was in my possession on
> the night your parents died. James had showed it to me just a few days
> previously. It explained so much of his undetected wrong-doing at
> school! I could hardly believe what I was seeing. I asked to borrow
> it, to examine it.”
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross*
The reason why Harry didn't die was also explained by Dumbledore. The reason for it wasn't the Hallows, even though Harry was the owner of all three Hallows by the time he went to the forest to face Voldemort.
> “But you’re dead.” said Harry.
>
>
> “Oh yes,” said Dumbledore matter-of-factly.
>
>
> “Then . . . I’m dead too?”
>
>
> “Ah,” said Dumbledore, smiling still more broadly. “That is the question,
> isn’t it? On the whole, dear boy, I think not.”
>
>
> “But . . . ” Harry raised his hand
> instinctively towards the lightning scar. It did not seem to be there.
> “But I should have died—I didn’t defend myself! I meant to let him
> kill me!”
>
>
> “And that,” said Dumbledore, “will, I think, have made all
> the difference.”
>
>
> “I let him kill me,” said Harry. “Didn’t I?”
>
>
> “You did,” said Dumbledore, nodding. “Go on!”
>
>
> “So the part of his soul that
> was in me . . . ”
>
>
> Dumbledore nodded still more enthusiastically,
> urging Harry onward, a broad smile of encouragement on his face.
>
>
> “. . . has it gone?”
>
>
> “Oh yes!” said Dumbledore. “Yes, he destroyed it. Your
> soul is whole, and completely your own, Harry.”
>
>
> “But if Voldemort used
> the Killing Curse,” Harry started again “and nobody died for me this
> time—how can I be alive?”
>
>
> “I think you know,” said Dumbledore. “Think
> back. Remember what he did, in his ignorance, in his greed and his
> cruelty.”
>
>
> “He took my blood.” said Harry.
>
>
> “Precisely!” said
> Dumbledore. “He took your blood and rebuilt his living body with it!
> Your blood in his veins, Harry, Lily’s protection inside both of you!
> He tethered you to life while he lives!”
>
>
> “I live . . . while he lives!
> But I thought . . . I thought it was the other way round! I thought we
> both had to die? Or is it the same thing?”
>
>
> “You were the seventh
> Horcrux, Harry, the Horcrux he never meant to make. He had rendered
> his soul so unstable that it broke apart when he committed those acts of unspeakable evil, the murder of your parents, the at- tempted killing of a child. But what escaped from that room was even less than he knew. He left more than his body behind.
> He left part of himself latched to you, the would-be victim who had survived.
>
>
> “He took your blood believing it would strengthen him. He took into
> his body a tiny part of the enchantment your mother laid upon you when
> she died for you. His body keeps her sacrifice alive, and while that
> enchantment survives, so do you and so does Voldemort’s one last hope
> for himself.”
>
>
> “Without meaning to, as you now know, Lord Voldemort
> doubled the bond between you when he returned to a human form. A part
> of his soul was still attached to yours, and, thinking to strengthen
> himself, he took a part of your mother’s sacrifice into himself.”
>
>
> Harry sat in thought for a long time, or perhaps seconds. It was very hard
> to be sure of things like time, here.
>
>
> “He killed me with your wand.”
>
>
> “He *failed* to kill you with my wand,” Dumbledore corrected Harry. “I
> think we can agree you are not dead.
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross* | Dumbledore *was* dead. Harry wasn't. That's established by the text itself:
> “But you’re dead.” said Harry. “Oh yes,” said Dumbledore matter-of-factly. “Then . . . I’m dead too?” “Ah,” said Dumbledore, smiling still more broadly. “That is the question, isn’t it? On the whole, dear boy, I think not.”
Harry came back from "King's Cross", not the dead. Dumbledore, who was, in fact, dead could not return from "King's Cross" because he was only present in Harry's mind's version of King's Cross.
The book is also clear that it's all going on in Harry's head.
> Of course it is happening inside your head, Harry, but why on earth should that mean that it is not real?
Like so many other times in the books Dumbledore was clever and made very well educated guesses. He was pretty sure that Harry was a horcrux that would have to be destroyed. He also knew Harry would chose death over allowing his friends to be hurt. When he said that the experience was "real" but still all in his head I always assumed he meant that Dumbledore was present in some real, but magical way.
He was after all the most powerful wizard in the world and spells *can* behave and converse like real humans (see Tom Riddle's horcrux/memory in CoS, the portraits around Hogwarts, howlers etc.). While 100% theoretical I see two possibilities:
1. It's not at all unreasonable to guess that he cast a spell to cause Harry's experience 'upon destruction'.
2. Memories are powerful in real life and especially in the HP series. Memories of the most powerful wizard in the world occurring during a near-death experience where your soul/body is being separated from the *second-most-powerful* wizard the world might have side effects like we see in the book.
Basically: Dumbledore can't come back because he's present, but not really there. | 8 | 2 |
177,933 | Harry Potter chose to come back from the dead because he was the master of death. But how could he be the master of death as he never had the Elder Wand?
If Harry could come back does that mean that Dumbledore could come back from the dead too? Why/why not?
After all, Dumbledore did have the three Deathly Hallows. He owned the Elder Wand and the Resurrection Stone and the Cloak of Invisibility. He passes the Cloak to Harry, but he still owned it: you can give something to someone but you are still the owner of it.
So when you die as the master of death you have a choice to come back. Dumbledore died as master of death but he never came back.
Does that means that Dumbledore did not choose to come back or that he cannot and the Deathly Hallows don't work like this? | 2018/01/02 | [
"https://scifi.stackexchange.com/questions/177933",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/93971/"
] | There are many fundamental errors in your question itself. I really suggest you go back and read the books because your understanding of both the Hallows and Harry's resurrection is wrong.
Firstly, Harry was the owner of Elder Wand having won it from Draco Malfoy when he escaped from Malfoy Manor. Draco became the owner of Elder wand when he disarmed Dumbledore at the end of Half-blood Prince. Both these points are explained in the book.
Next, Dumbledore never owned the invisibility cloak, it belonged to James Potter. Dumbledore merely borrowed it to examine suspecting that it was one of the Hallows. After the death of the Potters he simply kept it till the time Harry came to Hogwarts and then passed it to Harry during his first year telling him that the cloak had once belonged to his father.
And most important, Harry did not come back from the dead because he was able to unite the Hallows. He came back from the dead because when Voldemort cast the killing curse on Harry, he killed a part of his own soul which was living inside Harry (as Harry was the Horcrux which he never intended to make).
Even if a person can unite all the Hallows I don't think they gain the ability to come back from the dead. As it is explained in the books, Hallows were just very powerful magical objects created by Wizards and the whole lore about possessor of Hallows being "Master of Death" was just a fairytale which was based on these powerful magical objects.
> “So it’s true?” asked Harry. “All of it? The Peverell brothers—”
>
>
> “—were the three brothers of the tale,” said Dumbledore, nodding. “Oh
> yes, I think so. Whether they met Death on a lonely road . . . I think
> it more likely that the Peverell brothers were simply gifted,
> dangerous wizards who succeeded in creating those powerful objects.
> The story of them being Death’s own Hallows seems to me the sort of
> legend that might have sprung up around such creations.
>
>
> “You. You have guessed, I know, why the Cloak was in my possession on
> the night your parents died. James had showed it to me just a few days
> previously. It explained so much of his undetected wrong-doing at
> school! I could hardly believe what I was seeing. I asked to borrow
> it, to examine it.”
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross*
The reason why Harry didn't die was also explained by Dumbledore. The reason for it wasn't the Hallows, even though Harry was the owner of all three Hallows by the time he went to the forest to face Voldemort.
> “But you’re dead.” said Harry.
>
>
> “Oh yes,” said Dumbledore matter-of-factly.
>
>
> “Then . . . I’m dead too?”
>
>
> “Ah,” said Dumbledore, smiling still more broadly. “That is the question,
> isn’t it? On the whole, dear boy, I think not.”
>
>
> “But . . . ” Harry raised his hand
> instinctively towards the lightning scar. It did not seem to be there.
> “But I should have died—I didn’t defend myself! I meant to let him
> kill me!”
>
>
> “And that,” said Dumbledore, “will, I think, have made all
> the difference.”
>
>
> “I let him kill me,” said Harry. “Didn’t I?”
>
>
> “You did,” said Dumbledore, nodding. “Go on!”
>
>
> “So the part of his soul that
> was in me . . . ”
>
>
> Dumbledore nodded still more enthusiastically,
> urging Harry onward, a broad smile of encouragement on his face.
>
>
> “. . . has it gone?”
>
>
> “Oh yes!” said Dumbledore. “Yes, he destroyed it. Your
> soul is whole, and completely your own, Harry.”
>
>
> “But if Voldemort used
> the Killing Curse,” Harry started again “and nobody died for me this
> time—how can I be alive?”
>
>
> “I think you know,” said Dumbledore. “Think
> back. Remember what he did, in his ignorance, in his greed and his
> cruelty.”
>
>
> “He took my blood.” said Harry.
>
>
> “Precisely!” said
> Dumbledore. “He took your blood and rebuilt his living body with it!
> Your blood in his veins, Harry, Lily’s protection inside both of you!
> He tethered you to life while he lives!”
>
>
> “I live . . . while he lives!
> But I thought . . . I thought it was the other way round! I thought we
> both had to die? Or is it the same thing?”
>
>
> “You were the seventh
> Horcrux, Harry, the Horcrux he never meant to make. He had rendered
> his soul so unstable that it broke apart when he committed those acts of unspeakable evil, the murder of your parents, the at- tempted killing of a child. But what escaped from that room was even less than he knew. He left more than his body behind.
> He left part of himself latched to you, the would-be victim who had survived.
>
>
> “He took your blood believing it would strengthen him. He took into
> his body a tiny part of the enchantment your mother laid upon you when
> she died for you. His body keeps her sacrifice alive, and while that
> enchantment survives, so do you and so does Voldemort’s one last hope
> for himself.”
>
>
> “Without meaning to, as you now know, Lord Voldemort
> doubled the bond between you when he returned to a human form. A part
> of his soul was still attached to yours, and, thinking to strengthen
> himself, he took a part of your mother’s sacrifice into himself.”
>
>
> Harry sat in thought for a long time, or perhaps seconds. It was very hard
> to be sure of things like time, here.
>
>
> “He killed me with your wand.”
>
>
> “He *failed* to kill you with my wand,” Dumbledore corrected Harry. “I
> think we can agree you are not dead.
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross* | > he passes the cloak to harry but he still own it
No, Dumbledore never **owned** it. Harry's father owned it, and and passed it along with everything else to Harry. Dumbledore was simply in possession of it because he had **borrowed** it before Harry's parents were killed.
I don't have the exact quote, but in another part of the book Dumbledore mentioned that the cloak would never have worked as well for Dumbledore as it did for Harry/James, because the cloak belonged to Potters.
> he is the master of death but he is never have the elder wand.
He wasn't in direct possession of it, but via some convoluted stuff Harry was the 'owner/master' of the wand since Draco defeated Dumbledore, and Harry defeated Draco.
There is also the bit in the Platform 9 3/4 where Dumbledore mentioned that a big part of Harry's ability to not die from the curse was related to Harry's willingness to sacrifice himself for others. Harry chose to walk out to the forest, knowing that he would probably be killed. Dumbledore was never in a position where he **owned** all three items at the same time and had that choice to make. | 8 | 4 |
177,933 | Harry Potter chose to come back from the dead because he was the master of death. But how could he be the master of death as he never had the Elder Wand?
If Harry could come back does that mean that Dumbledore could come back from the dead too? Why/why not?
After all, Dumbledore did have the three Deathly Hallows. He owned the Elder Wand and the Resurrection Stone and the Cloak of Invisibility. He passes the Cloak to Harry, but he still owned it: you can give something to someone but you are still the owner of it.
So when you die as the master of death you have a choice to come back. Dumbledore died as master of death but he never came back.
Does that means that Dumbledore did not choose to come back or that he cannot and the Deathly Hallows don't work like this? | 2018/01/02 | [
"https://scifi.stackexchange.com/questions/177933",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/93971/"
] | > he passes the cloak to harry but he still own it
No, Dumbledore never **owned** it. Harry's father owned it, and and passed it along with everything else to Harry. Dumbledore was simply in possession of it because he had **borrowed** it before Harry's parents were killed.
I don't have the exact quote, but in another part of the book Dumbledore mentioned that the cloak would never have worked as well for Dumbledore as it did for Harry/James, because the cloak belonged to Potters.
> he is the master of death but he is never have the elder wand.
He wasn't in direct possession of it, but via some convoluted stuff Harry was the 'owner/master' of the wand since Draco defeated Dumbledore, and Harry defeated Draco.
There is also the bit in the Platform 9 3/4 where Dumbledore mentioned that a big part of Harry's ability to not die from the curse was related to Harry's willingness to sacrifice himself for others. Harry chose to walk out to the forest, knowing that he would probably be killed. Dumbledore was never in a position where he **owned** all three items at the same time and had that choice to make. | Even if Dumbledore would be able to come back, he wouldn't. This is one of the primary points of the books.
-----------------------------------------------------------------------------------------------------------
Although I agree with the other answers that the questioner seems to have misunderstood the Hallows, I want to point out that even if Dumbledore would have been able to come back, he wouldn't.
The primary theme of Harry Potter is about overcoming the fear of death:
> Death is an extremely important theme throughout all seven books. **I would say possibly the most important theme.** ([Accio-quote](http://www.accio-quote.org/articles/2001/1201-bbc-hpandme.htm))
Voldemort's main personality trait, and the one that defines him the most, is his fear of death.
> Voldemort's fear is death, ignominious death. I mean, he regards death itself as ignominious. He thinks that it's a shameful human weakness, as you know. His worst fear is death, but how would a boggart show that? I'm not too sure. I did think about that because I knew you were going to ask me that.
>
>
> “There is nothing worse than death, Dumbledore!” snarled
> Voldemort.
This is also his greatest weakness:
> “Your failure to understand that there are things much worse than death has always been your greatest weakness—”
In fact all the bad guys primary traits seem to be based on fear of death
> Death Eaters
And
> Only innocent lives, Peter!”
> “You don’t understand!” whined Pettigrew. “He would have
> killed me, Sirius!”
However, the defining characteristic of the good guys is their willingness to embrace death. This is evident from the first book:
> "To one as young as you, I'm sure it seems incredible, but to Nicolas
> and Perenelle, it really is like going to bed after a very, very long
> day. **After all, to the well-organized mind, death is but the next great
> adventure**. You know, the Stone was really not such a wonderful thing. As
> much money and life as you could want! The two things most human beings
> would choose above all -- the trouble is, humans do have a knack of
> choosing precisely those things that are worst for them."
This is expressed in many other places in the books as well, but here's one of my favorite quotes:
> “THEN YOU SHOULD HAVE DIED!” roared Black. “DIED
> RATHER THAN BETRAY YOUR FRIENDS, AS WE WOULD
> HAVE DONE FOR YOU!”
And Snape becomes good only when he seems to embrace death:
> “DON’T!” bellowed Snape. “Gone . . . dead . . .”
> “Is this remorse, Severus?”
> “I wish . . . I wish I were dead. . . .”
Dumbledore, although never clearly seeming to have fear of death, definitely viewed himself as selfish and wanted to overcome death, and believes that his selfishness may caused him caused him to avoid sacrificing himself to Ariana (in his view):
> “I know how you are feeling, Harry,” said Dumbledore very
> quietly.
That in my mind, is one of the most important overlooked quotes in the book (and
one that will be of utmost importance in the Fantastic Beasts movies.)
That quote comes right after Harry blames himself for Sirius's death:
> It was his fault Sirius had died; it was all his fault.
This means that, Like Harry, Dumbledore as well blamed himself for someone's death, and in the later books, we find out it was Arianna.
> “Don’t hurt them,
> don’t hurt them, please, please, it’s my fault, hurt me instead . . .”
>
>
> “He thought he was back there with you and Grindelwald, I
> know he did,” said Harry, remembering Dumbledore whimpering,
> pleading. “He thought he was watching Grindelwald hurting you
> and Ariana. . . . It was torture to him, if you’d seen him then, you
> wouldn’t say he was free.”
>
>
> All those closest to Albus — and I count myself
> one of that lucky number — agree that Ariana’s
> death, and Albus’s feeling of personal responsibility
> for it (though, of course, he was guiltless), left their
> mark upon him forevermore.
And we know we why he felt guilty - because he ignored his sister while he tried to overcome death:
> “And at the heart of our schemes, the Deathly Hallows! How
> they fascinated him, how they fascinated both of us! The unbeatable
> wand, the weapon that would lead us to power! The Resurrection
> Stone — to him, though I pretended not to know it, it meant an
> army of Inferi! To me, I confess, it meant the return of my parents,
> and the lifting of all responsibility from my shoulders.
> “And the Cloak . . . somehow, we never discussed the Cloak much,
> Harry. Both of us could conceal ourselves well enough without the
> Cloak, the true magic of which, of course, is that it can be used to
> protect and shield others as well as its owner. I thought that, if we
> ever found it, it might be useful in hiding Ariana, but our interest
> in the Cloak was mainly that it completed the trio, for the legend
> said that the man who united all three objects would then be truly
> master of death, which we took to mean ‘invincible.’
> “Invincible masters of death, Grindelwald and Dumbledore!
> Two months of insanity, of cruel dreams, and neglect of the only
> two members of my family left to me.
> “And then . . . you know what happened. Reality returned in
> the form of my rough, unlettered, and infinitely more admirable
> brother. I did not want to hear the truths he shouted at me. I did
> not want to hear that I could not set forth to seek Hallows with a
> fragile and unstable sister in tow.
> “The argument became a fight. Grindelwald lost control. That
> which I had always sensed in him, though I pretended not to, now
> sprang into terrible being. And Ariana . . . after all my mother’s care
> and caution . . . lay dead upon the floor.”
Harry on the other hand, is always portrayed as selfless:
> “Do not misunderstand me,” he said, and pain crossed the face
> so that he looked ancient again. “I loved them. I loved my parents,
> I loved my brother and my sister, but I was selfish, Harry, more
> selfish than you, who are a remarkably selfless person, could possibly
> imagine.
Thus, only Harry, who is selfless and pure and has zero fear of death, was able to choose selflessly to live.
But Dumbledore, even if his possession of the Hallows allowed him to choose life, would not have, because he knew inherently that his choice would include some selfishness and desire to live, and thus was not purely selfless. He would have feared making this choice, as he knew himself to be undeserving. Thus he went to the opposite extreme and chose death - by his own hand - through a hallow, to overcome his selfishness.
This is also implied in the tale of Beatle the Bard, that only the brother who made the selfless choice (the cloak) was allowed to survie death, or more so, embrace him like a brother. | 4 | 1 |
177,933 | Harry Potter chose to come back from the dead because he was the master of death. But how could he be the master of death as he never had the Elder Wand?
If Harry could come back does that mean that Dumbledore could come back from the dead too? Why/why not?
After all, Dumbledore did have the three Deathly Hallows. He owned the Elder Wand and the Resurrection Stone and the Cloak of Invisibility. He passes the Cloak to Harry, but he still owned it: you can give something to someone but you are still the owner of it.
So when you die as the master of death you have a choice to come back. Dumbledore died as master of death but he never came back.
Does that means that Dumbledore did not choose to come back or that he cannot and the Deathly Hallows don't work like this? | 2018/01/02 | [
"https://scifi.stackexchange.com/questions/177933",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/93971/"
] | There are many fundamental errors in your question itself. I really suggest you go back and read the books because your understanding of both the Hallows and Harry's resurrection is wrong.
Firstly, Harry was the owner of Elder Wand having won it from Draco Malfoy when he escaped from Malfoy Manor. Draco became the owner of Elder wand when he disarmed Dumbledore at the end of Half-blood Prince. Both these points are explained in the book.
Next, Dumbledore never owned the invisibility cloak, it belonged to James Potter. Dumbledore merely borrowed it to examine suspecting that it was one of the Hallows. After the death of the Potters he simply kept it till the time Harry came to Hogwarts and then passed it to Harry during his first year telling him that the cloak had once belonged to his father.
And most important, Harry did not come back from the dead because he was able to unite the Hallows. He came back from the dead because when Voldemort cast the killing curse on Harry, he killed a part of his own soul which was living inside Harry (as Harry was the Horcrux which he never intended to make).
Even if a person can unite all the Hallows I don't think they gain the ability to come back from the dead. As it is explained in the books, Hallows were just very powerful magical objects created by Wizards and the whole lore about possessor of Hallows being "Master of Death" was just a fairytale which was based on these powerful magical objects.
> “So it’s true?” asked Harry. “All of it? The Peverell brothers—”
>
>
> “—were the three brothers of the tale,” said Dumbledore, nodding. “Oh
> yes, I think so. Whether they met Death on a lonely road . . . I think
> it more likely that the Peverell brothers were simply gifted,
> dangerous wizards who succeeded in creating those powerful objects.
> The story of them being Death’s own Hallows seems to me the sort of
> legend that might have sprung up around such creations.
>
>
> “You. You have guessed, I know, why the Cloak was in my possession on
> the night your parents died. James had showed it to me just a few days
> previously. It explained so much of his undetected wrong-doing at
> school! I could hardly believe what I was seeing. I asked to borrow
> it, to examine it.”
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross*
The reason why Harry didn't die was also explained by Dumbledore. The reason for it wasn't the Hallows, even though Harry was the owner of all three Hallows by the time he went to the forest to face Voldemort.
> “But you’re dead.” said Harry.
>
>
> “Oh yes,” said Dumbledore matter-of-factly.
>
>
> “Then . . . I’m dead too?”
>
>
> “Ah,” said Dumbledore, smiling still more broadly. “That is the question,
> isn’t it? On the whole, dear boy, I think not.”
>
>
> “But . . . ” Harry raised his hand
> instinctively towards the lightning scar. It did not seem to be there.
> “But I should have died—I didn’t defend myself! I meant to let him
> kill me!”
>
>
> “And that,” said Dumbledore, “will, I think, have made all
> the difference.”
>
>
> “I let him kill me,” said Harry. “Didn’t I?”
>
>
> “You did,” said Dumbledore, nodding. “Go on!”
>
>
> “So the part of his soul that
> was in me . . . ”
>
>
> Dumbledore nodded still more enthusiastically,
> urging Harry onward, a broad smile of encouragement on his face.
>
>
> “. . . has it gone?”
>
>
> “Oh yes!” said Dumbledore. “Yes, he destroyed it. Your
> soul is whole, and completely your own, Harry.”
>
>
> “But if Voldemort used
> the Killing Curse,” Harry started again “and nobody died for me this
> time—how can I be alive?”
>
>
> “I think you know,” said Dumbledore. “Think
> back. Remember what he did, in his ignorance, in his greed and his
> cruelty.”
>
>
> “He took my blood.” said Harry.
>
>
> “Precisely!” said
> Dumbledore. “He took your blood and rebuilt his living body with it!
> Your blood in his veins, Harry, Lily’s protection inside both of you!
> He tethered you to life while he lives!”
>
>
> “I live . . . while he lives!
> But I thought . . . I thought it was the other way round! I thought we
> both had to die? Or is it the same thing?”
>
>
> “You were the seventh
> Horcrux, Harry, the Horcrux he never meant to make. He had rendered
> his soul so unstable that it broke apart when he committed those acts of unspeakable evil, the murder of your parents, the at- tempted killing of a child. But what escaped from that room was even less than he knew. He left more than his body behind.
> He left part of himself latched to you, the would-be victim who had survived.
>
>
> “He took your blood believing it would strengthen him. He took into
> his body a tiny part of the enchantment your mother laid upon you when
> she died for you. His body keeps her sacrifice alive, and while that
> enchantment survives, so do you and so does Voldemort’s one last hope
> for himself.”
>
>
> “Without meaning to, as you now know, Lord Voldemort
> doubled the bond between you when he returned to a human form. A part
> of his soul was still attached to yours, and, thinking to strengthen
> himself, he took a part of your mother’s sacrifice into himself.”
>
>
> Harry sat in thought for a long time, or perhaps seconds. It was very hard
> to be sure of things like time, here.
>
>
> “He killed me with your wand.”
>
>
> “He *failed* to kill you with my wand,” Dumbledore corrected Harry. “I
> think we can agree you are not dead.
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross* | Even if Dumbledore would be able to come back, he wouldn't. This is one of the primary points of the books.
-----------------------------------------------------------------------------------------------------------
Although I agree with the other answers that the questioner seems to have misunderstood the Hallows, I want to point out that even if Dumbledore would have been able to come back, he wouldn't.
The primary theme of Harry Potter is about overcoming the fear of death:
> Death is an extremely important theme throughout all seven books. **I would say possibly the most important theme.** ([Accio-quote](http://www.accio-quote.org/articles/2001/1201-bbc-hpandme.htm))
Voldemort's main personality trait, and the one that defines him the most, is his fear of death.
> Voldemort's fear is death, ignominious death. I mean, he regards death itself as ignominious. He thinks that it's a shameful human weakness, as you know. His worst fear is death, but how would a boggart show that? I'm not too sure. I did think about that because I knew you were going to ask me that.
>
>
> “There is nothing worse than death, Dumbledore!” snarled
> Voldemort.
This is also his greatest weakness:
> “Your failure to understand that there are things much worse than death has always been your greatest weakness—”
In fact all the bad guys primary traits seem to be based on fear of death
> Death Eaters
And
> Only innocent lives, Peter!”
> “You don’t understand!” whined Pettigrew. “He would have
> killed me, Sirius!”
However, the defining characteristic of the good guys is their willingness to embrace death. This is evident from the first book:
> "To one as young as you, I'm sure it seems incredible, but to Nicolas
> and Perenelle, it really is like going to bed after a very, very long
> day. **After all, to the well-organized mind, death is but the next great
> adventure**. You know, the Stone was really not such a wonderful thing. As
> much money and life as you could want! The two things most human beings
> would choose above all -- the trouble is, humans do have a knack of
> choosing precisely those things that are worst for them."
This is expressed in many other places in the books as well, but here's one of my favorite quotes:
> “THEN YOU SHOULD HAVE DIED!” roared Black. “DIED
> RATHER THAN BETRAY YOUR FRIENDS, AS WE WOULD
> HAVE DONE FOR YOU!”
And Snape becomes good only when he seems to embrace death:
> “DON’T!” bellowed Snape. “Gone . . . dead . . .”
> “Is this remorse, Severus?”
> “I wish . . . I wish I were dead. . . .”
Dumbledore, although never clearly seeming to have fear of death, definitely viewed himself as selfish and wanted to overcome death, and believes that his selfishness may caused him caused him to avoid sacrificing himself to Ariana (in his view):
> “I know how you are feeling, Harry,” said Dumbledore very
> quietly.
That in my mind, is one of the most important overlooked quotes in the book (and
one that will be of utmost importance in the Fantastic Beasts movies.)
That quote comes right after Harry blames himself for Sirius's death:
> It was his fault Sirius had died; it was all his fault.
This means that, Like Harry, Dumbledore as well blamed himself for someone's death, and in the later books, we find out it was Arianna.
> “Don’t hurt them,
> don’t hurt them, please, please, it’s my fault, hurt me instead . . .”
>
>
> “He thought he was back there with you and Grindelwald, I
> know he did,” said Harry, remembering Dumbledore whimpering,
> pleading. “He thought he was watching Grindelwald hurting you
> and Ariana. . . . It was torture to him, if you’d seen him then, you
> wouldn’t say he was free.”
>
>
> All those closest to Albus — and I count myself
> one of that lucky number — agree that Ariana’s
> death, and Albus’s feeling of personal responsibility
> for it (though, of course, he was guiltless), left their
> mark upon him forevermore.
And we know we why he felt guilty - because he ignored his sister while he tried to overcome death:
> “And at the heart of our schemes, the Deathly Hallows! How
> they fascinated him, how they fascinated both of us! The unbeatable
> wand, the weapon that would lead us to power! The Resurrection
> Stone — to him, though I pretended not to know it, it meant an
> army of Inferi! To me, I confess, it meant the return of my parents,
> and the lifting of all responsibility from my shoulders.
> “And the Cloak . . . somehow, we never discussed the Cloak much,
> Harry. Both of us could conceal ourselves well enough without the
> Cloak, the true magic of which, of course, is that it can be used to
> protect and shield others as well as its owner. I thought that, if we
> ever found it, it might be useful in hiding Ariana, but our interest
> in the Cloak was mainly that it completed the trio, for the legend
> said that the man who united all three objects would then be truly
> master of death, which we took to mean ‘invincible.’
> “Invincible masters of death, Grindelwald and Dumbledore!
> Two months of insanity, of cruel dreams, and neglect of the only
> two members of my family left to me.
> “And then . . . you know what happened. Reality returned in
> the form of my rough, unlettered, and infinitely more admirable
> brother. I did not want to hear the truths he shouted at me. I did
> not want to hear that I could not set forth to seek Hallows with a
> fragile and unstable sister in tow.
> “The argument became a fight. Grindelwald lost control. That
> which I had always sensed in him, though I pretended not to, now
> sprang into terrible being. And Ariana . . . after all my mother’s care
> and caution . . . lay dead upon the floor.”
Harry on the other hand, is always portrayed as selfless:
> “Do not misunderstand me,” he said, and pain crossed the face
> so that he looked ancient again. “I loved them. I loved my parents,
> I loved my brother and my sister, but I was selfish, Harry, more
> selfish than you, who are a remarkably selfless person, could possibly
> imagine.
Thus, only Harry, who is selfless and pure and has zero fear of death, was able to choose selflessly to live.
But Dumbledore, even if his possession of the Hallows allowed him to choose life, would not have, because he knew inherently that his choice would include some selfishness and desire to live, and thus was not purely selfless. He would have feared making this choice, as he knew himself to be undeserving. Thus he went to the opposite extreme and chose death - by his own hand - through a hallow, to overcome his selfishness.
This is also implied in the tale of Beatle the Bard, that only the brother who made the selfless choice (the cloak) was allowed to survie death, or more so, embrace him like a brother. | 8 | 1 |
95,207 | How does a Stack Overflow moderator know about sock puppet accounts?
How do they trap the user? | 2011/06/15 | [
"https://meta.stackexchange.com/questions/95207",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/161645/"
] | I am not going to answer this directly, for reasons that should be obvious.
However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable.
If you want the vote of the masses; write good questions and answers. | They have ways of finding pretty much any kind of sock puppets using their sites...
![sock puppet](https://i.stack.imgur.com/UISly.jpg) | 6 | 5 |
95,207 | How does a Stack Overflow moderator know about sock puppet accounts?
How do they trap the user? | 2011/06/15 | [
"https://meta.stackexchange.com/questions/95207",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/161645/"
] | I am not going to answer this directly, for reasons that should be obvious.
However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable.
If you want the vote of the masses; write good questions and answers. | Actions speak louder than IP address… Possibly even a “view” of a question is an action. | 6 | 2 |
95,207 | How does a Stack Overflow moderator know about sock puppet accounts?
How do they trap the user? | 2011/06/15 | [
"https://meta.stackexchange.com/questions/95207",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/161645/"
] | I am not going to answer this directly, for reasons that should be obvious.
However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable.
If you want the vote of the masses; write good questions and answers. | You know, throughout your posts here, you keep referring to this as a "bug" or a "trap". It's not a bug at all; it's a *feature* designed to prevent people from abusing the site. **Which is exactly what you were doing.**
In your comments on Marc's answer, you complain that your friend "Nahid" got her account merged due to suspicious behavior. If that's true, and Nahid actually exists and was playing by the rules, then what happened to her was because *your behavior* made her look like another one of your sock puppets.
Why did this happen? Not because of "bugs" in Stack Overflow, or the malice of the evil moderators. It happened because you abused this site *so badly* that everyone around you was thrown into suspicion. If you hadn't tried so hard to make your fake accounts look like real ones, your friend's real account wouldn't have looked like another of your fakes. If "Nahid" is upset that her account got merged, she should be blaming you for that. If you're upset that you lost reputation, you should blame yourself. **You cheated. You got caught cheating. That's your fault, not Stack Overflow's.**
You've suggested that SO might lose users due to features like this, but I think it'll *gain* users when they see that their reputation means something. People don't like being taken advantage of by others who don't play by the rules, and they don't like cheaters filling up their community space with garbage. Even in your imaginary "99 lost professional users" scenario, I suspect the number we'll gain far outweighs the number we'll lose due to accidental merges.
To sum up, the solution isn't to ask how to cheat more effectively, and it's also not to blame others for noticing. The solution is to improve your behavior, start playing by the rules, and try to be valuable to the rest of this community. | 6 | 5 |
95,207 | How does a Stack Overflow moderator know about sock puppet accounts?
How do they trap the user? | 2011/06/15 | [
"https://meta.stackexchange.com/questions/95207",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/161645/"
] | They have ways of finding pretty much any kind of sock puppets using their sites...
![sock puppet](https://i.stack.imgur.com/UISly.jpg) | Actions speak louder than IP address… Possibly even a “view” of a question is an action. | 5 | 2 |
95,207 | How does a Stack Overflow moderator know about sock puppet accounts?
How do they trap the user? | 2011/06/15 | [
"https://meta.stackexchange.com/questions/95207",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/161645/"
] | You know, throughout your posts here, you keep referring to this as a "bug" or a "trap". It's not a bug at all; it's a *feature* designed to prevent people from abusing the site. **Which is exactly what you were doing.**
In your comments on Marc's answer, you complain that your friend "Nahid" got her account merged due to suspicious behavior. If that's true, and Nahid actually exists and was playing by the rules, then what happened to her was because *your behavior* made her look like another one of your sock puppets.
Why did this happen? Not because of "bugs" in Stack Overflow, or the malice of the evil moderators. It happened because you abused this site *so badly* that everyone around you was thrown into suspicion. If you hadn't tried so hard to make your fake accounts look like real ones, your friend's real account wouldn't have looked like another of your fakes. If "Nahid" is upset that her account got merged, she should be blaming you for that. If you're upset that you lost reputation, you should blame yourself. **You cheated. You got caught cheating. That's your fault, not Stack Overflow's.**
You've suggested that SO might lose users due to features like this, but I think it'll *gain* users when they see that their reputation means something. People don't like being taken advantage of by others who don't play by the rules, and they don't like cheaters filling up their community space with garbage. Even in your imaginary "99 lost professional users" scenario, I suspect the number we'll gain far outweighs the number we'll lose due to accidental merges.
To sum up, the solution isn't to ask how to cheat more effectively, and it's also not to blame others for noticing. The solution is to improve your behavior, start playing by the rules, and try to be valuable to the rest of this community. | Actions speak louder than IP address… Possibly even a “view” of a question is an action. | 5 | 2 |
71,288,129 | I am trying to extend the symbols available to me for plotting in 3D. In 2D, I use:
```
x1 <- sort(rnorm(10))
y1 <- rnorm(10)
z1 <- rnorm(10) + atan2(x1, y1)
x2 <- sort(rnorm(10))
y2 <- rnorm(10)
z2 <- rnorm(10) + atan2(x2, y2)
x3 <- sort(rnorm(10))
y3 <- rnorm(10)
z3 <- rnorm(10) + atan2(x3, y3)
new.styles <- -1*c(9818:9824, 9829, 9830, 9831)
```
In 2D, my plot works and gives the appropriate symbol:
```
plot(x1, y1, col="red", bg="red", pch=new.styles, cex = 2)
```
and the plot is here:[![example 2D plot with appropriate symbols](https://i.stack.imgur.com/S9mlN.png)](https://i.stack.imgur.com/S9mlN.png)
In 3D, however, the symbols do not get translated correctly.
```
rgl::plot3d(x1, y1, z1, col="red", bg="red", pch=new.styles, size = 10)
```
this yields: [![enter image description here](https://i.stack.imgur.com/THPIm.png)](https://i.stack.imgur.com/THPIm.png)
The symbols are getting replaced with (one) circle.
I also tried with pch3d and got blank plots. However, pch3d does work with the "standard" plotting symbols.
```
rgl::pch3d(x1, y1, z1, col="red", bg="red", pch=10:19, size = 10)
```
I get the plot: [![3D plot with standard symbols](https://i.stack.imgur.com/ReAGn.png)](https://i.stack.imgur.com/ReAGn.png)
So, it appears to be that at least the symbols are not displaying in 3D. How can I display the preferred symbols? | 2022/02/27 | [
"https://Stackoverflow.com/questions/71288129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3236841/"
] | I was able to only get a solution using `text3d()` -- hopefully there exists a better solution.
```
x1 <- sort(rnorm(12))
y1 <- rnorm(12)
z1 <- rnorm(12) + atan2(x1, y1)
x2 <- sort(rnorm(12))
y2 <- rnorm(12)
z2 <- rnorm(12) + atan2(x2, y2)
x3 <- sort(rnorm(12))
y3 <- rnorm(12)
z3 <- rnorm(12) + atan2(x3, y3)
new.styles <- c(9818:9824, 9829, 9830, 9831, 9832, 9827)
rgl::open3d()
pal.col <- RColorBrewer::brewer.pal(name = "Paired", n = 12)
for (i in 1:12)
rgl::text3d(x1[i], y1[i], z1[i], col=pal.col[i], text = intToUtf8(new.styles[i]), cex = 2, usePlotmath = TRUE)
rgl::box3d()
```
This yields the figure:
[![Using text3d](https://i.stack.imgur.com/uBgCd.png)](https://i.stack.imgur.com/uBgCd.png)
This may well be too complicated, hopefully there are better solutions out there. | This is the best I could do:
[![3d picture with crowns](https://i.stack.imgur.com/GNqv4.png)](https://i.stack.imgur.com/GNqv4.png)
Set up file for texture/shape:
```r
crown <- tempfile(pattern = "crown", fileext = ".png")
png(filename = crown)
plot(1,1, ann=FALSE, axes=FALSE, pch=-9818, cex = 40, col = 2)
dev.off()
```
Load package, define a function to plot the texture at a random point:
```r
library(rgl)
xyz <- cbind(c(0,1,1,0), 0, c(0,0,1,1))
add_quad_point <- function(shape = crown, sd = 3) {
pos <- rnorm(3, sd = sd)
m <- sweep(xyz, MARGIN=2, STATS = pos, FUN = "+")
quads3d(m,
texture = shape,
texcoords = xyz[,c(1,3)],
col = "white",
specular = "black")
}
```
```r
open3d()
replicate(10, add_quad_point())
axes3d()
## close3d()
``` | 3 | 1 |
1,336,337 | I've got my first RoR app deployed to Dreamhost and it's using Passenger. The one note on Dreamhost's wiki about slow response mentioned changing a RewriteRules line in the public/.htaccess file to use FastCGI. But I assume this will have no effect if I'm using Passenger, is that right?
I've looked at the logs and compared them to my local logs, and it looks like there is a wider range on Dreamhost. Some responses are comparable to the quick local ones, others can take a few seconds.
I'm using a Flex front end with HTTPServices to the rails backend, and I think I also need to add logging around my services to see what kind of network delay I'm getting and try to isolate where the delays are.
I should also add that there is probably plenty of room for improvement in the area of eager loading associations. I think I did that a little early on, but haven't done it thoroughly through all the associations. I have the local logs set to the default where I can see all the queries, and there are a lot of them. | 2009/08/26 | [
"https://Stackoverflow.com/questions/1336337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26270/"
] | You must be running in Development mode. Try running in Production mode to see if it is still slow.
Post below may help:
[Ruby On Rails is slow...?](https://stackoverflow.com/questions/566401/ruby-on-rails-is-slow) | [New Relic](http://www.newrelic.com/) is a Rails performance monitoring app. I haven't personally used it, but I hear their name a lot and it looks like they have a free lite version that you could try. From my experience profiling other applications, a tool like this is worth using because the slow parts of your application are often in areas where you didn't expect. | 3 | 0 |
205,706 | I can't find a way to toggle mc internal editor in hex mode. [Here](http://www.tldp.org/LDP/LG/issue23/wkndmech_dec97/mc_article.html) it says to use F4 however it suggest to replace. How to do it? | 2015/05/26 | [
"https://unix.stackexchange.com/questions/205706",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/50426/"
] | You can open file with `F3`.
Hex view - `F4`.
Start edit - `F2`. | `F4` toggles hex mode in the Midnight Commander **viewer** (accessed using `F3`), not in the editor. Once in hex mode in the viewer, `F2` allows you to make changes to the file being viewed.
As you discovered, `F4` in the editor starts a search. | 4 | 3 |
6,061,310 | I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document.
For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this:
```
CGPDFStringRef uriStringRef;
if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) {
break;
}
```
In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? | 2011/05/19 | [
"https://Stackoverflow.com/questions/6061310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287454/"
] | The [Adobe PDF Reference](http://www.adobe.com/devnet/pdf/pdf_reference_archive.html) describes all of the keys. | The keys in a dictionary depend on the actual object the dictionary represents (a page dictionary has other keys than an annotation dictionary). The Adobe PDF reference describes all these objects and their keys. | 2 | 1 |
6,061,310 | I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document.
For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this:
```
CGPDFStringRef uriStringRef;
if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) {
break;
}
```
In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? | 2011/05/19 | [
"https://Stackoverflow.com/questions/6061310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287454/"
] | It's absurd that you would have to go read 1300 page long specs just to find what keys a dictionary contains, a dictionary that could contain anything depending on what kind of annotation it is.
To get a list of keys in a `CGPDFDictionaryRef` you do:
```
// temporary C function to print out keys
void printPDFKeys(const char *key, CGPDFObjectRef ob, void *info) {
NSLog(@"key = %s", key);
}
```
In the place where you're trying to see the contents:
```
CGPDFDictionaryRef mysteriousDictionary; // this is your dictionary with keys
CGPDFDictionaryApplyFunction(mysteriousDictionary, printPDFKeys, NULL);
// break on or right after above, and you will have the list of keys NSLogged
``` | The [Adobe PDF Reference](http://www.adobe.com/devnet/pdf/pdf_reference_archive.html) describes all of the keys. | 5 | 2 |
6,061,310 | I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document.
For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this:
```
CGPDFStringRef uriStringRef;
if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) {
break;
}
```
In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? | 2011/05/19 | [
"https://Stackoverflow.com/questions/6061310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287454/"
] | It's absurd that you would have to go read 1300 page long specs just to find what keys a dictionary contains, a dictionary that could contain anything depending on what kind of annotation it is.
To get a list of keys in a `CGPDFDictionaryRef` you do:
```
// temporary C function to print out keys
void printPDFKeys(const char *key, CGPDFObjectRef ob, void *info) {
NSLog(@"key = %s", key);
}
```
In the place where you're trying to see the contents:
```
CGPDFDictionaryRef mysteriousDictionary; // this is your dictionary with keys
CGPDFDictionaryApplyFunction(mysteriousDictionary, printPDFKeys, NULL);
// break on or right after above, and you will have the list of keys NSLogged
``` | The keys in a dictionary depend on the actual object the dictionary represents (a page dictionary has other keys than an annotation dictionary). The Adobe PDF reference describes all these objects and their keys. | 5 | 1 |
36,711,776 | This is the HTML I want to extract from.
```
<input type="hidden" id="continueTo" name="continueTo" value="/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb" />
```
I need a Xpath to extract only state value i.e `72a37ba7-2033-47f4-8e7e-69a207406dfb` | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5850305/"
] | The XPATH:
```
//input[@id="continueTo"]/@value
```
It will get the value of the node `input` with id `continueTo`. Then it will need to be processed with a Regex first to get a final result.
The Regex:
```
`[^=]+$`
```
`$` means the end of the string. It will get everything on the end of the string which is not `=`. | Use below code:-
```
String val = driver.findElement(By.xpath("//input[@id='continueTo']/@value")).getText();
String [] myValue = val.split("&state=");
System.out.println(myValue[1]);
```
Hope it will help you :) | 2 | 1 |
36,711,776 | This is the HTML I want to extract from.
```
<input type="hidden" id="continueTo" name="continueTo" value="/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb" />
```
I need a Xpath to extract only state value i.e `72a37ba7-2033-47f4-8e7e-69a207406dfb` | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5850305/"
] | Hi you can only get value of a attribute using xpath not its sub-string but if you want to get sub-string then please do it like below
```
String AttributeValue = driver.findElement(By.id("continueTo")).getAttribute("value");
System.out.println("Value of the attribute value is : " + AttributeValue);
// now as you want 72a37ba7-2033-47f4-8e7e-69a207406dfb this substring of the vale attribute
// then plz apply java split as below
String value = "/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb";
String [] myValue = value.split("=");
System.out.println(myValue[0]); // will print /oauth2/authz/?response_type
System.out.println(myValue[1]); // will print code&client_id
System.out.println(myValue[2]); // will print localoauth20&redirect_uri
System.out.println(myValue[3]); // will print http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state
System.out.println(myValue[4]); // will print 72a37ba7-2033-47f4-8e7e-69a207406dfb
```
Hope this helps your query | Use below code:-
```
String val = driver.findElement(By.xpath("//input[@id='continueTo']/@value")).getText();
String [] myValue = val.split("&state=");
System.out.println(myValue[1]);
```
Hope it will help you :) | 2 | 1 |
25,242,580 | I am working on node.js where forever is installed. I am not sure where is intalled . when i go to project directory then type command `forever list` then it will display no forever
Can any body tell me how to check and how to resart processes.
My website is running. it means forever may be running | 2014/08/11 | [
"https://Stackoverflow.com/questions/25242580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3883164/"
] | If `forever list` is empty, your nodeJS app is not running.
You have to start it first by doing `forever start yourApp.js` | You have to install forever with sudo. | 1 | 0 |
60,784 | I'm starting a VPN connection using Network Manager.
Once the connection is established I have to change [MTU](http://en.wikipedia.org/wiki/Maximum_transmission_unit) in order it to work properly.
For example:
```
sudo ifconfig ppp0 mtu 777
```
It is very annoying to execute this command every time I open a VPN connection. Is there any idea to create a script that would execute this command automatically once the connection is established (ppp0 interface is up)? | 2011/09/10 | [
"https://askubuntu.com/questions/60784",
"https://askubuntu.com",
"https://askubuntu.com/users/24741/"
] | Create a script in `/etc/network/if-up.d`, containing
```
#!/bin/sh
if [ "$IFACE" = "ppp0" ]; then
ifconfig ppp0 mtu 777
fi
```
and [make it executable](https://askubuntu.com/questions/122428/how-to-run-sh-file). | Here's a modernized (using `ip` instead of `ifconfig`) and generic (`openconnect` on the command-line uses `tun0`, Network Manager uses `vpn0` through the network applet; the numbers may vary if another network is already active) variant of @enzotib's excellent answer, tested on Ubuntu 20.04:
```
#!/bin/bash
if [[ "$IFACE" =~ ^(tun|vpn)[0-9] ]]; then
ip link set "$IFACE" mtu 777
fi
``` | 5 | 2 |
9,479,819 | Sorry for the very noob question.
Let's suppose I have an enum like so
```
public enum MyElementType {
TYPE_ONE,
TYPE_TWO,
TYPE_THREE;
}
```
When I want to loop over this enum, I always see this solution:
```
for(MyElementType type: MyElementType.values())
{
//do things
}
```
I wonder if there exist a viable solution with the while loop.
Seraching around I see that Enumeration interface exposes the method
hasMoreElements()
but I don't know how to link the things together.
Any advice? | 2012/02/28 | [
"https://Stackoverflow.com/questions/9479819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/740480/"
] | Why do you want to use a while loop rather than the for-each you more typically see?
In any case, it's pretty simple
```
Set<MyElementType> elements = EnumSet.allOf(MyElementType.class);
Iterator<MyElementType> it = elements.iterator();
while (it.hasNext()) {
MyElementType el = it.next();
// etc
}
// or
Iterator<MyElementType> it = Arrays.asList(MyElementType.values()).iterator();
``` | Take a look @ <http://www.javaspecialists.eu/archive/Issue107.html> | 3 | 1 |
2,855 | Consider an application that currently uses a combination of license file and/or subscription to verify which features to activate. I can use a smart contract instead of the license file, and potentially the subscription. But today, the subscription check requires an online validation and associated credential check.
With the Ethereum blockchain, is it possible to check state while offline? I'd like to implement a system where people are not required to be online to use the software. I can imagine having contracts that return themselves as valid while offline, but will nodes provide access to data if they are not sync'd up? I'd be ok using out of date data for up to a month or more, but I'd need the local client to respond.
Alternatively, I could create local license files from the node when the node is online, but I could almost as easily email license files. But by using the blockchain, the licenses and other assets could be traded and available should the company fold. | 2016/04/10 | [
"https://ethereum.stackexchange.com/questions/2855",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/1161/"
] | When your app is able to sync with the blockchain (network connection available), the check the blockchain and update your app settings file to allow use for up to e.g. 1 week after the blockchain subscription check. Just tell the user that they have to sync before the period is up.
One extra feature you can add:
* Your app has a unique public and private Ethereum key embedded in it and has to send a small amount of ethers back to your account on a periodic basis.
* If you get sent more ether transactions from your app than expected, your customer is running more than one copy of your app. | If you want to get up-to-date information from the Ethereum blockchain then you'll need a node somewhere that's synced up. However, in theory you could do this with either a trusted server or a more lightweight proof so you wouldn't necessarily need the whole chain to be downloaded to the client.
If you can tolerate partially out-of-date licensing information then you could certainly cache it locally as you suggest.
> Alternatively, I could create local license files from the node when the node is online, but I could almost as easily email license files.
Right, if the goal is just that you want to be able to issue license files based on some information you already have then the Ethereum blockchain probably isn't suitable. Just issue that information on a server of your own and have the client software contact that server.
However, there are a couple of interesting things you get from using Ethereum for something like this. For example, you can make software licenses tradeable by arbitrary exchanges that you don't have to create yourself, and licenses bought in this way will work even if you go out of business. | 3 | 2 |
4,347,995 | I ask this as someone who loves maths but has no ability. So 2 axioms & a question.
Axiom 1 - a digital processor exists that can find the n'th prime number of any size instantly.
Axiom 2 - all natural numbers can be expressed as the sum of 2 primes.
Would it take more/less/same amount of bits to define a natural number exactly as the sum of primes or as traditional POW2 digital format and will that fact apply to all natural numbers whatever their size? I presume a +/- wouldn't be needed because if it's a - then the larger prime is given first. I'm also interested to know if it's ALWAYS more/less efficient or is their a numerical point at which the optimal solution alters.
Maybe it's a very badly written question. If so, I can only apologise. I have wondered this for 20 years but never had anywhere to ask. Thanks. | 2022/01/03 | [
"https://math.stackexchange.com/questions/4347995",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/603487/"
] | The ordinary way of storing natural numbers by means of bits is already optimal. This can easily be seen: Each of the $2^n$ combinations of assignments of $n$ bits represents exactly one distinct natural number between $0$ and $2^n-1$. If there was a way of storing more numbers with the same amount of bits, and we would try to create the mapping between the combination of bits and the actual numbers, we would necessarily end up with a combination of bits that maps to more than one natural number, see [pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle). This obviously does not make sense, because we want each number to be unambiguously represented as a certain "bit pattern" in the memory.
But it is even worse: We know for sure, that there are infinitely many numbers that can be represented as sum of two primes in more than one way (see [Infinitely many even numbers that can be expressed as the sum of $m$ primes in $n$ different ways](https://math.stackexchange.com/q/1443667/407833)). This means, that there will be definitely fewer natural numbers than unique combinations of two primes. Even if your axioms were true, you would have to represent the pairs of primes in such way that each sum appears only once, i.e. you need some magic that skips the combinations that map to natural numbers that are already covered by other prime pairs. | In this reference, <https://en.m.wikipedia.org/wiki/Goldbach%27s_conjecture>
they give a nineteen digit number whose lower prime must be at least 9781.
The $n$th prime is about $n\ln n$ so you save a factor of 42, or about six bits, by storing the index of the larger prime. But 9781 is about the 1000th prime, so you need ten bits to store that one.
That was a worst case. There will be best cases where the second prime is small. But for the first $2^{50}$ numbers you need at least $2^{50}$ different ways to store them which would mean an average of 50 bits, regardless. | 1 | 0 |
4,568,514 | I'm working through Example 2.22 in Steward and Tall's Algebraic Number Theory book. The goal is to determine the ring of integers of $\mathbb Q(\sqrt[3]5)$. Let $\theta\in\mathbb R$ such that $\theta^3=5$. Let $\omega=e^{2\pi i/3}$. I'm at the point where I need to check whether
$$
\alpha=\frac 13(1+\theta+\theta^2)
$$
or
$$
\beta=\frac 13(2+2\theta+2\theta^2)
$$
are algebraic integers (I've checked the other cases). Let's start with $\alpha$. I can think of two ways to do this. The first would be to consider the norm
$$
N(\alpha)=\frac 1{27}(1+\theta+\theta^2)(1+\omega\theta+\omega^2\theta^2)(1+\omega^2\theta+\omega\theta^2).
$$
If $\alpha$ is an algebaric integer, then $N(\alpha)\in\mathbb Z$. However, the expression of $N(\alpha)$ is a bit complicated (unless I'm overlooking something). The second would be to determine the minimum polynomial $\mu$ of $\alpha$ over $\mathbb Q$, and then invoke that $\alpha$ is an algebraic integer iff $\mu\in\mathbb Z[X]$.
In both cases I'm not too hopeful. Should I still proceed in this way, or is there something obvious I'm missing? | 2022/11/03 | [
"https://math.stackexchange.com/questions/4568514",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/405827/"
] | [![enter image description here](https://i.stack.imgur.com/7hWo2.png)](https://i.stack.imgur.com/7hWo2.png)
As pointed out by dezdichado, the problem can be done by two applications of Cosine Formula.
Refer to the figure,
One such formula is:
$$\cos \alpha=\frac{(c-x)^2+y^2-a^2}{2(c-x)y}$$
Applying Cosine Formula to the other triangle and combining the $2$ equations would yield the required answer. | I have an idea to start :
In $\Bbb C, A=0, B=1, C=\xi +i\eta, D=x$
Unfortunately, none of my calculations succeed, although simplifications appear: I suspect that there is a sign error in the proposed equality. | 2 | 1 |
4,605,482 | I want my marker to appear not in the center of the screen, but 25% of the way up to give extra room for the popup box. Although sticking an offset in is easy, the offset depends on the zoom level as if you're zoomed far out, you'll want to center the map quite far up (such as 50km). If you're really zoomed in, then you'll want to center it just a tiny amount like 10 meters.
I'm not sure how to accomplish this. Any ideas? | 2011/01/05 | [
"https://Stackoverflow.com/questions/4605482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174375/"
] | Try this:
Take the height of the plugin and get 25% of that.
Then you need to multiply that by the degrees or kilometres per pixel scale at that height (if you can't get it straight from the plugin then I guess do the math), then centre the screen at that point on the globe. | I am not sure as it has been a while since I messed around with the API, but I think you can create a custom marker object with its own pixel based offset, and display that instead of the default marker.
EDIT: Whoops read it again and realized you probably just wanted to move the whole map and not the marker. | 2 | 0 |
44,487,654 | I know this is a very classical question which might be answered many times in this forum, however I could not find any clear answer which explains this clearly from scratch.
Firstly, imgine that my dataset called my\_data has 4 variables such as
my\_data = variable1, variable2, variable3, target\_variable
So, let's come to my problem. I'll explain all my steps and ask your help for where I've been stuck:
```
# STEP1 : split my_data into [predictors] and [targets]
predictors = my_data[[
'variable1',
'variable2',
'variable3'
]]
targets = my_data.target_variable
# STEP2 : import the required libraries
from sklearn import cross_validation
from sklearn.ensemble import RandomForestRegressor
#STEP3 : define a simple Random Forest model attirbutes
model = RandomForestClassifier(n_estimators=100)
#STEP4 : Simple K-Fold cross validation. 3 folds.
cv = cross_validation.KFold(len(my_data), n_folds=3, random_state=30)
# STEP 5
```
At this step, I want to fit my model based on the training dataset, and then
use that model on test dataset and predict test targets. I also want to calculate the required statistics such as MSE, r2 etc. for understanding the performance of my model.
I'd appreciate if someone helps me woth some basic codelines for Step5. | 2017/06/11 | [
"https://Stackoverflow.com/questions/44487654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8010314/"
] | First off, you are using the deprecated package `cross-validation` of scikit library. New package is named `model_selection`. So I am using that in this answer.
Second, you are importing `RandomForestRegressor`, but defining `RandomForestClassifier` in the code. I am taking `RandomForestRegressor` here, because the metrics you want (MSE, R2 etc) are only defined for regression problems, not classification.
There are multiple ways to do what you want. I assume that since you are trying to use the KFold cross-validation here, you want to use the left-out data of each fold as test fold. To accomplish this, we can do:
```
predictors = my_data[[
'variable1',
'variable2',
'variable3'
]]
targets = my_data.target_variable
from sklearn import model_selection
from sklearn.ensemble import RandomForestRegressor
from sklearn import metrics
model = RandomForestRegressor(n_estimators=100)
cv = model_selection.KFold(n_splits=3)
for train_index, test_index in kf.split(predictors):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = predictors[train_index], predictors[test_index]
y_train, y_test = targets[train_index], targets[test_index]
# For training, fit() is used
model.fit(X_train, y_train)
# Default metric is R2 for regression, which can be accessed by score()
model.score(X_test, y_test)
# For other metrics, we need the predictions of the model
y_pred = model.predict(X_test)
metrics.mean_squared_error(y_test, y_pred)
metrics.r2_score(y_test, y_pred)
```
For all this, documentation is your best friend. And scikit-learn documentation are one of the best I have ever seen. Following links may help you know more about them:
* <http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-evaluating-estimator-performance>
* <http://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics>
* <http://scikit-learn.org/stable/user_guide.html> | Also in the for loop it should be:
```
model = RandomForestRegressor(n_estimators=100)
for train_index, test_index in cv.split(X):
``` | 3 | 0 |
10,248,776 | Requirements for a TextBox control were to accept the following as valid inputs:
1. A sequence of numbers.
2. Literal string 'Number of rooms'.
3. No value at all (left blank). Not specifying a value at all should allow for the RegularExpressionValidator to pass.
Following RegEx yielded the desired results (successfully validated the 3 types of inputs):
```
"Number of rooms|[0-9]*"
```
However, I couldn't come up with an explanation when a colleague asked why the following fails to validate when the string 'Number of rooms' is specified (requirement #2):
```
"[0-9]*|Number of rooms"
```
An explanation as to why the ordering of alternation matters in this case would be very insightful indeed.
UPDATE:
The second regex successfully matches the target string "Number of rooms" in console app as shown [here](http://pastebin.com/yzr6Bqcd). However, using the identical expression in aspx markup doesn't match when the input is "Number of rooms". Here's the relevant aspx markup:
```
<asp:TextBox runat="server" ID="textbox1" >
</asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
EnableClientScript="false" runat="server" ControlToValidate="textbox1"
ValidationExpression="[0-9]*|Number of rooms"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
``` | 2012/04/20 | [
"https://Stackoverflow.com/questions/10248776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/988951/"
] | The order matters since that is the order which the Regex engine will try to match.
Case 1: `Number of rooms|[0-9]*`
In this case the regex engine will first try to match the text "Number of room". If this fails will then try to match numbers or nothing.
Case 2: `[0-9]*|Number of rooms`:
In this case the engine will first try to match number or nothing. But nothing will *always* match. In this case it never needs to try "Number of rooms"
This is kind of like the || operator in C#. Once the left side matches the right side is ignored.
**Update:**
To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match.
```
// .....
Match m = Regex.Match(controlValue, ValidationExpression);
return(m.Success && m.Index == 0 && m.Length == controlValue.Length);
// .....
```
It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches. | The point is that the `[0-9]*` at the beginning is matching empty strings if you specify that first.
If you specify that *the whole string* should be digits, then it should work:
```
^[0-9]*$|Number of rooms
```
Unless you specify `^` and `$`, to indicate that *the whole string* must be a match, an empty string will be matched at the beginning of "Number of rooms", and at that point the second alternative will not be tried out.
I hope this answers your question in the comment, I'm not sure if it's clear... | 3 | 2 |
10,248,776 | Requirements for a TextBox control were to accept the following as valid inputs:
1. A sequence of numbers.
2. Literal string 'Number of rooms'.
3. No value at all (left blank). Not specifying a value at all should allow for the RegularExpressionValidator to pass.
Following RegEx yielded the desired results (successfully validated the 3 types of inputs):
```
"Number of rooms|[0-9]*"
```
However, I couldn't come up with an explanation when a colleague asked why the following fails to validate when the string 'Number of rooms' is specified (requirement #2):
```
"[0-9]*|Number of rooms"
```
An explanation as to why the ordering of alternation matters in this case would be very insightful indeed.
UPDATE:
The second regex successfully matches the target string "Number of rooms" in console app as shown [here](http://pastebin.com/yzr6Bqcd). However, using the identical expression in aspx markup doesn't match when the input is "Number of rooms". Here's the relevant aspx markup:
```
<asp:TextBox runat="server" ID="textbox1" >
</asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
EnableClientScript="false" runat="server" ControlToValidate="textbox1"
ValidationExpression="[0-9]*|Number of rooms"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
``` | 2012/04/20 | [
"https://Stackoverflow.com/questions/10248776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/988951/"
] | The order matters since that is the order which the Regex engine will try to match.
Case 1: `Number of rooms|[0-9]*`
In this case the regex engine will first try to match the text "Number of room". If this fails will then try to match numbers or nothing.
Case 2: `[0-9]*|Number of rooms`:
In this case the engine will first try to match number or nothing. But nothing will *always* match. In this case it never needs to try "Number of rooms"
This is kind of like the || operator in C#. Once the left side matches the right side is ignored.
**Update:**
To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match.
```
// .....
Match m = Regex.Match(controlValue, ValidationExpression);
return(m.Success && m.Index == 0 && m.Length == controlValue.Length);
// .....
```
It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches. | You probably wanted to use regex `Number of rooms|[0-9]+` or `[0-9]+|Number of rooms`, because pattern `[0-9]*` (with star) will always match at least empty string (`*` means `{0,}`, so "zero or more..."). | 3 | 2 |
83,623 | I am trying to round the corners of a custom shape, but it is just straightening the original curves out.
*Note: This is in Illustrator CS5*
**Here is the shape before the effect:**
[![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png)
The 3 "corners should be rounded".
**Here is what happens when I use the effect:**
[![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png)
**How can I preserve the curves, and just round the actual corners?** | 2017/01/20 | [
"https://graphicdesign.stackexchange.com/questions/83623",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/84489/"
] | I don't have CS5, but this should work:
Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following:
[![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png)
With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point):
[![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png)
You should end up with something similar to this:
[![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png)
With the white arrow tool, drag each of the bulging corner points inward until they look appropriate:
[![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png)
Here's the new path overlaying your original shape.
[![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png)
If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points. | My way is easier if you have good experience with the pen tool.
First, make your triangle. In my case, I just made a box, deleted 1 anchor point, joined the two points creating a segment opposite to the middle point and rotated about 45 degrees (please correct me if I'm wrong).
[![enter image description here](https://i.stack.imgur.com/sXe3V.png)](https://i.stack.imgur.com/sXe3V.png)
Next, hit the convert path to rounded corner button. I'm pretty sure this feature is already in CS5. Make sure you have the point selected when doing this.
[![enter image description here](https://i.stack.imgur.com/ZjWmA.png)](https://i.stack.imgur.com/ZjWmA.png)
Do this one by one for each of your points. The one in the middle should be the easiest one to convert. The one at the top and the bottom are a bit tricky but nothing a pen tool can't fix :)
As you go each of the top and the bottom points, with your Direct Selection Tool active, grab the furthest to the left angle for the point being selected and while holding Shift, bring it to the center creating a nice straight side but still rounded corners.
[![enter image description here](https://i.stack.imgur.com/Z6DvZ.png)](https://i.stack.imgur.com/Z6DvZ.png)
It should look something like this:
[![enter image description here](https://i.stack.imgur.com/Jj8Te.png)](https://i.stack.imgur.com/Jj8Te.png)
Again, do the same thing for the bottom and you will get this:
[![enter image description here](https://i.stack.imgur.com/WQiBV.png)](https://i.stack.imgur.com/WQiBV.png)
I hope this helps! Please let me know if I confuse you. I'll be glad to clarify myself some more. | 3 | 0 |
83,623 | I am trying to round the corners of a custom shape, but it is just straightening the original curves out.
*Note: This is in Illustrator CS5*
**Here is the shape before the effect:**
[![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png)
The 3 "corners should be rounded".
**Here is what happens when I use the effect:**
[![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png)
**How can I preserve the curves, and just round the actual corners?** | 2017/01/20 | [
"https://graphicdesign.stackexchange.com/questions/83623",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/84489/"
] | I don't have CS5, but this should work:
Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following:
[![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png)
With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point):
[![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png)
You should end up with something similar to this:
[![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png)
With the white arrow tool, drag each of the bulging corner points inward until they look appropriate:
[![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png)
Here's the new path overlaying your original shape.
[![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png)
If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points. | The simple way:
Create additional anchor points around cornes (as it was mentioned at first answer), then apply Round Corner effect as usual. | 3 | 0 |
83,623 | I am trying to round the corners of a custom shape, but it is just straightening the original curves out.
*Note: This is in Illustrator CS5*
**Here is the shape before the effect:**
[![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png)
The 3 "corners should be rounded".
**Here is what happens when I use the effect:**
[![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png)
**How can I preserve the curves, and just round the actual corners?** | 2017/01/20 | [
"https://graphicdesign.stackexchange.com/questions/83623",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/84489/"
] | I don't have CS5, but this should work:
Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following:
[![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png)
With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point):
[![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png)
You should end up with something similar to this:
[![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png)
With the white arrow tool, drag each of the bulging corner points inward until they look appropriate:
[![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png)
Here's the new path overlaying your original shape.
[![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png)
If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points. | **Purely for comparison’s sake**, I thought it would be good to show what Adobe Illustrator CC (in this case, I am using v2017) can do:
[![enter image description here](https://i.stack.imgur.com/8d2hQ.gif)](https://i.stack.imgur.com/8d2hQ.gif)
1. With the selection tool, select your entire path
2. On a Mac, hold down `COMMAND` key (`CONTROL` on Win).
3. Click and drag on the corner radius circle icons that appear
4. You can optionally select a specific point and just round the corner for that part of your shape
Double click one of the circles for corner options:
[![](https://i.stack.imgur.com/3ci1E.png)](https://i.stack.imgur.com/3ci1E.png) | 3 | 1 |
83,623 | I am trying to round the corners of a custom shape, but it is just straightening the original curves out.
*Note: This is in Illustrator CS5*
**Here is the shape before the effect:**
[![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png)
The 3 "corners should be rounded".
**Here is what happens when I use the effect:**
[![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png)
**How can I preserve the curves, and just round the actual corners?** | 2017/01/20 | [
"https://graphicdesign.stackexchange.com/questions/83623",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/84489/"
] | **Purely for comparison’s sake**, I thought it would be good to show what Adobe Illustrator CC (in this case, I am using v2017) can do:
[![enter image description here](https://i.stack.imgur.com/8d2hQ.gif)](https://i.stack.imgur.com/8d2hQ.gif)
1. With the selection tool, select your entire path
2. On a Mac, hold down `COMMAND` key (`CONTROL` on Win).
3. Click and drag on the corner radius circle icons that appear
4. You can optionally select a specific point and just round the corner for that part of your shape
Double click one of the circles for corner options:
[![](https://i.stack.imgur.com/3ci1E.png)](https://i.stack.imgur.com/3ci1E.png) | My way is easier if you have good experience with the pen tool.
First, make your triangle. In my case, I just made a box, deleted 1 anchor point, joined the two points creating a segment opposite to the middle point and rotated about 45 degrees (please correct me if I'm wrong).
[![enter image description here](https://i.stack.imgur.com/sXe3V.png)](https://i.stack.imgur.com/sXe3V.png)
Next, hit the convert path to rounded corner button. I'm pretty sure this feature is already in CS5. Make sure you have the point selected when doing this.
[![enter image description here](https://i.stack.imgur.com/ZjWmA.png)](https://i.stack.imgur.com/ZjWmA.png)
Do this one by one for each of your points. The one in the middle should be the easiest one to convert. The one at the top and the bottom are a bit tricky but nothing a pen tool can't fix :)
As you go each of the top and the bottom points, with your Direct Selection Tool active, grab the furthest to the left angle for the point being selected and while holding Shift, bring it to the center creating a nice straight side but still rounded corners.
[![enter image description here](https://i.stack.imgur.com/Z6DvZ.png)](https://i.stack.imgur.com/Z6DvZ.png)
It should look something like this:
[![enter image description here](https://i.stack.imgur.com/Jj8Te.png)](https://i.stack.imgur.com/Jj8Te.png)
Again, do the same thing for the bottom and you will get this:
[![enter image description here](https://i.stack.imgur.com/WQiBV.png)](https://i.stack.imgur.com/WQiBV.png)
I hope this helps! Please let me know if I confuse you. I'll be glad to clarify myself some more. | 1 | 0 |
83,623 | I am trying to round the corners of a custom shape, but it is just straightening the original curves out.
*Note: This is in Illustrator CS5*
**Here is the shape before the effect:**
[![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png)
The 3 "corners should be rounded".
**Here is what happens when I use the effect:**
[![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png)
**How can I preserve the curves, and just round the actual corners?** | 2017/01/20 | [
"https://graphicdesign.stackexchange.com/questions/83623",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/84489/"
] | **Purely for comparison’s sake**, I thought it would be good to show what Adobe Illustrator CC (in this case, I am using v2017) can do:
[![enter image description here](https://i.stack.imgur.com/8d2hQ.gif)](https://i.stack.imgur.com/8d2hQ.gif)
1. With the selection tool, select your entire path
2. On a Mac, hold down `COMMAND` key (`CONTROL` on Win).
3. Click and drag on the corner radius circle icons that appear
4. You can optionally select a specific point and just round the corner for that part of your shape
Double click one of the circles for corner options:
[![](https://i.stack.imgur.com/3ci1E.png)](https://i.stack.imgur.com/3ci1E.png) | The simple way:
Create additional anchor points around cornes (as it was mentioned at first answer), then apply Round Corner effect as usual. | 1 | 0 |
66,920,844 | I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this:
```js
const TailwindProvider: React.FC = ({ children }) => {
const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme());
console.log("CurrentColorScheme:", currentColorScheme);
const isDarkMode = currentColorScheme == "dark";
const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode))
return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}
```
as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode.
How can I fix this? | 2021/04/02 | [
"https://Stackoverflow.com/questions/66920844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10183816/"
] | Use `systimestamp` since that includes a time zone.
```
select systimestamp at time zone 'US/Eastern'
from dual;
```
should return a timestamp in the Eastern time zone (assuming your database time zone files are up to date).
Note that if you ask for a timestamp in EST, that should be an hour earlier than the current time in the Eastern time zone of the United States because the US is in Daylight Savings Time. So the Eastern time zone is in EDT currently not EST. | Use `systimestamp` rather than `sysdate`, because it is already timezone-aware; then `at time zone` to translate:
```
select systimestamp at time zone 'America/New_York' from dual
```
Using a region is better/safer than an abbreviation like 'EST", which might not be unique; and [gives you the wrong answer](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=8792c9f5fb967821b6c1406e8baca6d3) - this shows mine, Justin's alternative (and maybe better!) region, what you get with EST, and all the things EST is an abbreviation of. (You could use `EST5EDT`, but a region is still clearer.)
You could also set your session to an East-coat region (if it isn't already) and then use `current_timestamp` instead of `systimestamp`:
```
alter session set time_zone = 'America/New_York';
select current_timestamp from dual;
```
[db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=f3f5b5a55fe5f1f5a1ff50d1ad3213ab)
Either way, how it is displayed is down to your client/application - e.g. the session `nls_timestamp_tz_format` - unless you convert it to a string with `to_char()`, supplying the format you want. | 3 | 2 |
66,920,844 | I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this:
```js
const TailwindProvider: React.FC = ({ children }) => {
const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme());
console.log("CurrentColorScheme:", currentColorScheme);
const isDarkMode = currentColorScheme == "dark";
const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode))
return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}
```
as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode.
How can I fix this? | 2021/04/02 | [
"https://Stackoverflow.com/questions/66920844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10183816/"
] | Use `systimestamp` rather than `sysdate`, because it is already timezone-aware; then `at time zone` to translate:
```
select systimestamp at time zone 'America/New_York' from dual
```
Using a region is better/safer than an abbreviation like 'EST", which might not be unique; and [gives you the wrong answer](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=8792c9f5fb967821b6c1406e8baca6d3) - this shows mine, Justin's alternative (and maybe better!) region, what you get with EST, and all the things EST is an abbreviation of. (You could use `EST5EDT`, but a region is still clearer.)
You could also set your session to an East-coat region (if it isn't already) and then use `current_timestamp` instead of `systimestamp`:
```
alter session set time_zone = 'America/New_York';
select current_timestamp from dual;
```
[db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=f3f5b5a55fe5f1f5a1ff50d1ad3213ab)
Either way, how it is displayed is down to your client/application - e.g. the session `nls_timestamp_tz_format` - unless you convert it to a string with `to_char()`, supplying the format you want. | If you really want to use `SYSDATE` then you can use:
```sql
SELECT from_tz(CAST(sysdate AS TIMESTAMP),'PST') AT TIME ZONE 'EST5EDT' FROM DUAL;
```
Which outputs:
> ```
>
> | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'PST')ATTIMEZONE'EST5EDT' |
> | :--------------------------------------------------------- |
> | 02-APR-21 11.07.33.000000 PM EST5EDT |
>
> ```
or:
```sql
SELECT from_tz(CAST(sysdate AS TIMESTAMP),'US/Pacific') AT TIME ZONE 'US/Eastern' FROM DUAL;
```
Which outputs:
> ```
>
> | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'US/PACIFIC')ATTIMEZONE'US/EASTERN' |
> | :------------------------------------------------------------------- |
> | 02-APR-21 11.07.33.000000 PM US/EASTERN |
>
> ```
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d5f2a83874b278412b0596443eb29d4c)* | 2 | 1 |
66,920,844 | I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this:
```js
const TailwindProvider: React.FC = ({ children }) => {
const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme());
console.log("CurrentColorScheme:", currentColorScheme);
const isDarkMode = currentColorScheme == "dark";
const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode))
return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}
```
as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode.
How can I fix this? | 2021/04/02 | [
"https://Stackoverflow.com/questions/66920844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10183816/"
] | Use `systimestamp` since that includes a time zone.
```
select systimestamp at time zone 'US/Eastern'
from dual;
```
should return a timestamp in the Eastern time zone (assuming your database time zone files are up to date).
Note that if you ask for a timestamp in EST, that should be an hour earlier than the current time in the Eastern time zone of the United States because the US is in Daylight Savings Time. So the Eastern time zone is in EDT currently not EST. | If you really want to use `SYSDATE` then you can use:
```sql
SELECT from_tz(CAST(sysdate AS TIMESTAMP),'PST') AT TIME ZONE 'EST5EDT' FROM DUAL;
```
Which outputs:
> ```
>
> | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'PST')ATTIMEZONE'EST5EDT' |
> | :--------------------------------------------------------- |
> | 02-APR-21 11.07.33.000000 PM EST5EDT |
>
> ```
or:
```sql
SELECT from_tz(CAST(sysdate AS TIMESTAMP),'US/Pacific') AT TIME ZONE 'US/Eastern' FROM DUAL;
```
Which outputs:
> ```
>
> | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'US/PACIFIC')ATTIMEZONE'US/EASTERN' |
> | :------------------------------------------------------------------- |
> | 02-APR-21 11.07.33.000000 PM US/EASTERN |
>
> ```
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d5f2a83874b278412b0596443eb29d4c)* | 3 | 1 |
65,536,088 | I have a dataframe which is called "df". It looks like this:
```
a
0 2
1 3
2 0
3 5
4 1
5 3
6 1
7 2
8 2
9 1
```
I would like to produce a cummulative sum column which:
* Sums the contents of column "a" cumulatively;
* Until it gets a sum of "5";
* Resets the cumsum total, to 0, when it reaches a sum of "5", and continues with the summing process;
I would like the dataframe to look like this:
```
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
In the dataframe, the column "a\_cumm\_summ" contains the results of the cumulative sum.
Does anyone know how I can achieve this? I have hunted through the forums. And saw similar questions, for example, [this one](https://stackoverflow.com/questions/41488676/python-data-frame-cumulative-sum-of-column-until-condition-is-reached-and-retur), but they did not meet my exact requirements. | 2021/01/02 | [
"https://Stackoverflow.com/questions/65536088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11622176/"
] | You can get the cumsum, and floor divide by 5. Then subtract the result of the floor division, multiplied by 5, from the below row's cumulative sum:
```
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
df
Out[1]:
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
---
Solution #2 (more robust):
Per Trenton's comment, A good, diverse sample dataset goes a long way to figure out unbreakable logic for these types of problems. I probably would have come up with a better solution first time around with a good sample dataset. Here is a solution that overcomes the sample dataset that Trenton mentioned in the comments. As shown, there are more conditions to handle as you have to deal with carry-over. On a large dataset, this would still be much more performant than a for-loop, but it is much more difficult logic to vectorize:
```
df = pd.DataFrame({'a': {0: 2, 1: 4, 2: 1, 3: 5, 4: 1, 5: 3, 6: 1, 7: 2, 8: 2, 9: 1}})
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
over = (df['a_cumm_sum'].shift(1) - 5)
df['a_cumm_sum'] = df['a_cumm_sum'] - np.where(over > 0, df['a_cumm_sum'] - over, 0).cumsum()
s = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum']*-1, 0).cumsum()
df['a_cumm_sum'] = np.where((df['a_cumm_sum'] > 0) & (s > 0), s + df['a_cumm_sum'],
df['a_cumm_sum'])
df['a_cumm_sum'] = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum'].shift() + df['a'], df['a_cumm_sum'])
df
Out[2]:
a a_cumm_sum
0 2 2.0
1 4 6.0
2 1 1.0
3 5 6.0
4 1 1.0
5 3 4.0
6 1 5.0
7 2 2.0
8 2 4.0
9 1 5.0
``` | The assignment can be combined with a condition. The code is as follows:
```py
import numpy as np
import pandas as pd
a = [2, 3, 0, 5, 1, 3, 1, 2, 2, 1]
df = pd.DataFrame(a, columns=["a"])
df["cumsum"] = df["a"].cumsum()
df["new"] = df["cumsum"]%5
df["new"][((df["cumsum"]/5)==(df["cumsum"]/5).astype(int)) & (df["a"]!=0)] = 5
df
```
The output is as follows:
```
a cumsum new
0 2 2 2
1 3 5 5
2 0 5 0
3 5 10 5
4 1 11 1
5 3 14 4
6 1 15 5
7 2 17 2
8 2 19 4
9 1 20 5
```
**Working:**
Basically, take remainder for the cumulative sum for 5. In cases where the actual sum is 5 also becomes zero. So, for these cases, check if the `value/5 == int(value/5)`. Then, remove cases where the actual value is zero. | 2 | 1 |
65,536,088 | I have a dataframe which is called "df". It looks like this:
```
a
0 2
1 3
2 0
3 5
4 1
5 3
6 1
7 2
8 2
9 1
```
I would like to produce a cummulative sum column which:
* Sums the contents of column "a" cumulatively;
* Until it gets a sum of "5";
* Resets the cumsum total, to 0, when it reaches a sum of "5", and continues with the summing process;
I would like the dataframe to look like this:
```
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
In the dataframe, the column "a\_cumm\_summ" contains the results of the cumulative sum.
Does anyone know how I can achieve this? I have hunted through the forums. And saw similar questions, for example, [this one](https://stackoverflow.com/questions/41488676/python-data-frame-cumulative-sum-of-column-until-condition-is-reached-and-retur), but they did not meet my exact requirements. | 2021/01/02 | [
"https://Stackoverflow.com/questions/65536088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11622176/"
] | You can get the cumsum, and floor divide by 5. Then subtract the result of the floor division, multiplied by 5, from the below row's cumulative sum:
```
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
df
Out[1]:
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
---
Solution #2 (more robust):
Per Trenton's comment, A good, diverse sample dataset goes a long way to figure out unbreakable logic for these types of problems. I probably would have come up with a better solution first time around with a good sample dataset. Here is a solution that overcomes the sample dataset that Trenton mentioned in the comments. As shown, there are more conditions to handle as you have to deal with carry-over. On a large dataset, this would still be much more performant than a for-loop, but it is much more difficult logic to vectorize:
```
df = pd.DataFrame({'a': {0: 2, 1: 4, 2: 1, 3: 5, 4: 1, 5: 3, 6: 1, 7: 2, 8: 2, 9: 1}})
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
over = (df['a_cumm_sum'].shift(1) - 5)
df['a_cumm_sum'] = df['a_cumm_sum'] - np.where(over > 0, df['a_cumm_sum'] - over, 0).cumsum()
s = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum']*-1, 0).cumsum()
df['a_cumm_sum'] = np.where((df['a_cumm_sum'] > 0) & (s > 0), s + df['a_cumm_sum'],
df['a_cumm_sum'])
df['a_cumm_sum'] = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum'].shift() + df['a'], df['a_cumm_sum'])
df
Out[2]:
a a_cumm_sum
0 2 2.0
1 4 6.0
2 1 1.0
3 5 6.0
4 1 1.0
5 3 4.0
6 1 5.0
7 2 2.0
8 2 4.0
9 1 5.0
``` | **EDIT**:
As Trenton McKinney pointed out in the comments, OP likely wanted to reset it to 0 whenever the cumsum exceeded 5. This makes the definition to be a recurrence which is usually difficult to do with pandas/numpy (see David's solution). I'd recommend using `numba` to speed up the for loop in this case
---
Another alternative: using `groupby`
```py
In [78]: df.groupby((df['a'].cumsum()% 5 == 0).shift().fillna(False).cumsum()).cumsum()
Out[78]:
a
0 2
1 5
2 0
3 5
4 1
5 4
6 5
7 2
8 4
9 5
``` | 2 | 1 |
65,536,088 | I have a dataframe which is called "df". It looks like this:
```
a
0 2
1 3
2 0
3 5
4 1
5 3
6 1
7 2
8 2
9 1
```
I would like to produce a cummulative sum column which:
* Sums the contents of column "a" cumulatively;
* Until it gets a sum of "5";
* Resets the cumsum total, to 0, when it reaches a sum of "5", and continues with the summing process;
I would like the dataframe to look like this:
```
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
In the dataframe, the column "a\_cumm\_summ" contains the results of the cumulative sum.
Does anyone know how I can achieve this? I have hunted through the forums. And saw similar questions, for example, [this one](https://stackoverflow.com/questions/41488676/python-data-frame-cumulative-sum-of-column-until-condition-is-reached-and-retur), but they did not meet my exact requirements. | 2021/01/02 | [
"https://Stackoverflow.com/questions/65536088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11622176/"
] | You can get the cumsum, and floor divide by 5. Then subtract the result of the floor division, multiplied by 5, from the below row's cumulative sum:
```
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
df
Out[1]:
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
---
Solution #2 (more robust):
Per Trenton's comment, A good, diverse sample dataset goes a long way to figure out unbreakable logic for these types of problems. I probably would have come up with a better solution first time around with a good sample dataset. Here is a solution that overcomes the sample dataset that Trenton mentioned in the comments. As shown, there are more conditions to handle as you have to deal with carry-over. On a large dataset, this would still be much more performant than a for-loop, but it is much more difficult logic to vectorize:
```
df = pd.DataFrame({'a': {0: 2, 1: 4, 2: 1, 3: 5, 4: 1, 5: 3, 6: 1, 7: 2, 8: 2, 9: 1}})
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
over = (df['a_cumm_sum'].shift(1) - 5)
df['a_cumm_sum'] = df['a_cumm_sum'] - np.where(over > 0, df['a_cumm_sum'] - over, 0).cumsum()
s = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum']*-1, 0).cumsum()
df['a_cumm_sum'] = np.where((df['a_cumm_sum'] > 0) & (s > 0), s + df['a_cumm_sum'],
df['a_cumm_sum'])
df['a_cumm_sum'] = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum'].shift() + df['a'], df['a_cumm_sum'])
df
Out[2]:
a a_cumm_sum
0 2 2.0
1 4 6.0
2 1 1.0
3 5 6.0
4 1 1.0
5 3 4.0
6 1 5.0
7 2 2.0
8 2 4.0
9 1 5.0
``` | You could try using this for loop:
```
lastvalue = 0
newcum = []
for i in df['a']:
if lastvalue >= 5:
lastvalue = i
else:
lastvalue += i
newcum.append(lastvalue)
df['a_cum_sum'] = newcum
print(df)
```
Output:
```
a a_cum_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
The above for loop iterates through the `a` column, and when the cumulative sum is 5 or more, it resets it to `0` then adds the `a` column's value `i`, but if the cumulative sum is lower than 5, it just adds the `a` column's value `i` (the iterator). | 2 | 1 |
325,415 | (<https://webapps.stackexchange.com/review/suggested-edits/111499> shows action by both.) [Edit: At first glance they both looked like special users. Not so.] | 2019/03/18 | [
"https://meta.stackexchange.com/questions/325415",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/218120/"
] | Community♦ is [a special user](https://meta.stackexchange.com/questions/19738/who-is-the-community-user). Community is credited for reviews when they are:
* Done by deleted users
* Improved, in which case Community is shown as having approved the edit
* Rejected and edited, in which case Community is shown as having rejected the edit
[user0](https://webapps.stackexchange.com/users/186471/user0) is a normal user who just happens to have "0" in the username. user0 approved the edit before it was improved by a different user. | A key difference is that their real user numbers, respectively, are -1 for Community♦ and 186471 for user0 (on webapps, and thus *not* 0), as can be seen in the URL (classically displayed in a browser's status bar when mousing over the usernames) that clicking on the name opens.
[Community♦](https://stackexchange.com/users/-1) (/community is tacked on the end of the canonical URL) is [a special user](https://meta.stackexchange.com/questions/19738/who-is-the-community-user).
But [user0](https://webapps.stackexchange.com/users/186471) (/user0 is tacked on the end of the canonical URL) is a normal user who just happens to have "0" in the username. user0 approved the edit before it was improved by a different user.
[I found no true user 0 - no user with ID 0](https://stackexchange.com/users/0/anything) on any SE sites.
[There is also no user with ID 1](https://webapps.stackexchange.com/users/1) on some SE sites, but
[there IS a user with ID 1](https://stackexchange.com/users/1) on other SE sites. | 3 | 1 |
48,751,289 | My project can switch between languages. The items are stored in a database, and using $\_GET['lang'] in the database gives back the correct items. For now, only English and French are in use, so it works with this code :
```
if ($_GET['lang'] == 'fr' OR ($_GET['lang'] == 'en')) {
$header = getTranslation('header', $_GET['lang']);
$footer = getTranslation('footer', $_GET['lang']);
} else {
header('Location: error.php');
}
```
What I'm looking for is some way to be prepared in case a language is added in the db. The code below approaches what I need (and obviously didn't work).
```
while ($translations = $languagesList->fetch()) {
if ($_GET['lang'] == $translations['code']) {
$header = getTranslation('header', $_GET['lang']);
$footer = getTranslation('footer', $_GET['lang']);
} else {
header('Location: language.php');
}
}
```
Is there any way to create a code that would generate multiple if conditions based on the number of languages in the db ? | 2018/02/12 | [
"https://Stackoverflow.com/questions/48751289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9244707/"
] | You should move the else part outside of the loop, as otherwise you will always execute it at some point in the loop iterations. Only when you have iterated through *all* possibilities, and you still have no match, then you can be sure there to have to navigate to the language page:
```
$header = null;
while ($translations = $languagesList->fetch()) {
if ($_GET['lang'] == $translations['code']) {
$header = getTranslation('header', $_GET['lang']);
$footer = getTranslation('footer', $_GET['lang']);
break; // No need to waste time to look further.
}
}
if ($header === null) {
header('Location: language.php');
}
```
But it would be smarter to [prepare an SQL statement](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) that gets you the result for the *particular* language only (with `where code = ?` and bind `$_GET['lang']` to it). Then you don't have to iterate in PHP, which will in general be slower than what the database can provide. Instead you can just see whether you had 0 or 1 records back (Or use `select count(*)` and check whether that is 0 or not). | Easiest is to have a mapping in an array, check if your language is present there, and if so, do stuff. Something like this;
```
$languages = array('en', 'fr', 'de', '...');
$default_language = 'en';
$language = in_array($_GET['lang'], $languages) ? $_GET['lang'] : $default_language;
$header = getTranslation('header', $language);
```
As you can see I've set a default langauge which is used if the language in the query var cannot be found. How to create that array of languages is up to you (a simple query should suffice). | 3 | 0 |
36,937,302 | I have a list of strings (see below) how do I concatenate these strings into one list containing one string.
```
["hello","stack","overflow"]
```
to
```
["hellostackoverflow"]
```
I am just allowed to import Data.Char and Data.List | 2016/04/29 | [
"https://Stackoverflow.com/questions/36937302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6219741/"
] | Consider each string in a list as a list of characters
```
["hello","stack","overflow"] :: [[Char]]
```
Concatenation is a process of connecting several lists into one. It must have a following type:
```
concat :: [[a]] -> [a]
```
If you will have such a function, you'll get a half of job done. You are looking for a way to get
```
["hellostackoverflow"]
```
as a result of concatenation. Once again, look at it's type:
```
["hellostackoverflow"] :: [[Char]]
```
It is the same type as you had at the beginning except that there is only one element in a list. So now you need a function which puts something into a list. It must have a type
```
putToList :: a -> [a]
```
Once you'll have both `concat` and `putToList` functions, your solution will be almost ready. Last thing you need to do is to compose it like that:
```
myConcatenation = putToList . concat
```
---
I suggest you to use [Hoogle](https://www.haskell.org/hoogle/) to search existing function by it's type. | You can also use the list monad to reduce the list to a single string, then re-wrap the result in a list.
```
> [["hello", "stack", "overflow"] >>= id]
["hellostackoverflow"]
```
The preceding avoids explicitly use of `Control.Monad.join`:
```
> import Control.Monad
> [join ["hello", "stack", "overflow"]
["hellostackoverflow"]
``` | 5 | 2 |
36,937,302 | I have a list of strings (see below) how do I concatenate these strings into one list containing one string.
```
["hello","stack","overflow"]
```
to
```
["hellostackoverflow"]
```
I am just allowed to import Data.Char and Data.List | 2016/04/29 | [
"https://Stackoverflow.com/questions/36937302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6219741/"
] | Consider each string in a list as a list of characters
```
["hello","stack","overflow"] :: [[Char]]
```
Concatenation is a process of connecting several lists into one. It must have a following type:
```
concat :: [[a]] -> [a]
```
If you will have such a function, you'll get a half of job done. You are looking for a way to get
```
["hellostackoverflow"]
```
as a result of concatenation. Once again, look at it's type:
```
["hellostackoverflow"] :: [[Char]]
```
It is the same type as you had at the beginning except that there is only one element in a list. So now you need a function which puts something into a list. It must have a type
```
putToList :: a -> [a]
```
Once you'll have both `concat` and `putToList` functions, your solution will be almost ready. Last thing you need to do is to compose it like that:
```
myConcatenation = putToList . concat
```
---
I suggest you to use [Hoogle](https://www.haskell.org/hoogle/) to search existing function by it's type. | ```hs
concat ["hello","stack","overflow"] -- => "hellostackoverflow"
``` | 5 | 3 |
36,937,302 | I have a list of strings (see below) how do I concatenate these strings into one list containing one string.
```
["hello","stack","overflow"]
```
to
```
["hellostackoverflow"]
```
I am just allowed to import Data.Char and Data.List | 2016/04/29 | [
"https://Stackoverflow.com/questions/36937302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6219741/"
] | ```hs
concat ["hello","stack","overflow"] -- => "hellostackoverflow"
``` | You can also use the list monad to reduce the list to a single string, then re-wrap the result in a list.
```
> [["hello", "stack", "overflow"] >>= id]
["hellostackoverflow"]
```
The preceding avoids explicitly use of `Control.Monad.join`:
```
> import Control.Monad
> [join ["hello", "stack", "overflow"]
["hellostackoverflow"]
``` | 3 | 2 |
5,809,104 | Here T could be an array or a single object. How can add the array to an arraylist or add a single object to the same arraylist. This gives me a build-time error that the overloaded match for `AddRange` has invalid arguments.
```
T loadedContent;
if (typeof(T).IsArray)
{
contentArrayList.AddRange(loadedContent);
}
else
{
contentArrayList.Add(loadedContent);
}
``` | 2011/04/27 | [
"https://Stackoverflow.com/questions/5809104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727904/"
] | Make sure you have set the correct editor associations and content types
Go to settings (`Window -> preferences`)
**Content Types**
1. Type in `Content Types` in the search box (should show under `General -> Types`
2. Click on the arrow next to `Text`, select `PHP Content Type`
3. Add `*.ctp` by clicking on the Add button on the right side
**File Association**
1. Type in `File Associations` in the search box on the left
2. Add \*.ctp (click the Add button on the top right side)
3. Associate the proper editor for it by clicking Add (on the bottom right side) and selecting PHP Editor | You can change the extension that CakePHP uses for view files to an extension that Eclipse likes. In the controller (or app\_controller) add the following variable:
```
var $ext = '.tpl';
```
If you change the extension to "PHP" you may have problems because CakePHP will try to load a class that matches the filename. | 7 | 0 |
133,508 | I've tried connecting a camera to my Raspberry Pi and I've enabled it on `raspi-config` but `vcgencmd get_camera` still shows `supported=0` `detected=0`. Also, in my `boot/config.txt`, `start_x=1` is not even commented nor enabled upon enabling camera interface. Another thing to note is my Raspberry Pi constantly shows a low voltage warning but I am unsure whether this is related in any way. What might be the issue? | 2021/11/25 | [
"https://raspberrypi.stackexchange.com/questions/133508",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/141166/"
] | Thanks to the comments, I have rectified the issue. The issue was with the bullseye version of the os. I used a buster version and it worked just fine | 1. [Check first if the camera is supported](http://elinux.org/RPi_VerifiedPeripherals#USB_Webcams)
2. Try a powered USB hub to plug in the camera / maybe it isnt getting enough power
Then you can install this tool to test out the camera `sudo apt-get install luvcview` | 1 | 0 |
21,876,004 | I am having problems while doing some test for a new app.
I have an activity in which I execute an asynctask to communicate with my server and ask for a json file.
I want that this file is downloaded periodically (don't know, 3-4 seconds) so I created a handler in my activity to execute it each time.
It works fine with Logs but whenever I try to execute asynctask, it makes an exception saying:
```
02-19 10:16:41.510: WARN/System.err(9051): java.lang.IllegalStateException: Cannot execute task: the task is already running.
02-19 10:16:41.510: WARN/System.err(9051): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:576)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.AsyncTask.execute(AsyncTask.java:535)
02-19 10:16:41.510: WARN/System.err(9051): at com.mobile.myPacket.mySecondActivity.askForData(mySecondActivity.java:68)
02-19 10:16:41.510: WARN/System.err(9051): at com.mobile.myPacket.mySecondActivity.access$000(mySecondActivity.java:22)
02-19 10:16:41.510: WARN/System.err(9051): at com.mobile.myPacket.mySecondActivity$1.run(mySecondActivity.java:56)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.Handler.handleCallback(Handler.java:733)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.Handler.dispatchMessage(Handler.java:95)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.Looper.loop(Looper.java:136)
02-19 10:16:41.510: WARN/System.err(9051): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-19 10:16:41.510: WARN/System.err(9051): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 10:16:41.510: WARN/System.err(9051): at java.lang.reflect.Method.invoke(Method.java:515)
02-19 10:16:41.510: WARN/System.err(9051): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-19 10:16:41.510: WARN/System.err(9051): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-19 10:16:41.510: WARN/System.err(9051): at dalvik.system.NativeStart.main(Native Method)
```
I think it is because it is another thread and second call is making a problem with the first one. But I don't know how to solve it.
This is my activity:
```
package com.mobile.myPacket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mobile.clases.AsyncResponse;
import com.mobile.clases.MyTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends Activity implements AsyncResponse {
private String urlServer = "url";
MyTask asyncTask =new MyTask();
Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(sendData);
setContentView(R.layout.secondActivity);
asyncTask.delegate = this;
//We ask for data the first time
askForData();
}
@Override
public void processFinish(JSONArray output) { //Executed from asyncTask
//Data received
Log.i("TEST", output.toString());
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
//prepare and send the data here..
askForData();
//Log.i("TEST","aa");
handler.postDelayed(this, 3000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
private void askForData(){
Log.i("TEST","askForData");
asyncTask.execute(urlServer+"test.php");
}
}
```
Without handler, asyncTask works fine just one time. So I guess that class is ok. | 2014/02/19 | [
"https://Stackoverflow.com/questions/21876004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463191/"
] | You cannot execute the same `AsyncTask` multiple times.
Before executing the `AsyncTask`, instantiate a new instance first:
```
private void askForData(){
asyncTask = new MyTask();
asyncTask.delegate = this;
asyncTask.execute(urlServer+"test.php");
}
```
Also remove the instantiation of the `AsyncTask` at the beginning of your class. | Try like this,
```
private void askForData(){
if (task.getStatus() == AsyncTask.Status.FINISHED) {
task = new AsyncTask();
}
if (task.getStatus() != AsyncTask.Status.RUNNING) {
task.execute();
}
}
``` | 3 | 0 |
17,206,523 | I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`?
Here is the code:
```
public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
List<Bike> bikeList = new ArrayList<Bike>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
Statement stm = null;
ResultSet rs = null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
stm=con.createStatement();
String qry="Select * from bike";
rs=stm.executeQuery(qry);
while(rs.next())
{
/* I need to put
* rs.getString("name"),rs.getString("model")
* etc into any of the suitable collection objects
* and then need to add those to the ArrayList - bikeList
*
*/
}
return bikeList;
}
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17206523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930544/"
] | For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list.
```
Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);
``` | ```
while (rs.next()) {
Bike bike = new Bike();
bike.setName(rs.getString("name"));
bike.setModel(rs.getString("model"));
bikeList.add(bike);
}
``` | 3 | 2 |
17,206,523 | I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`?
Here is the code:
```
public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
List<Bike> bikeList = new ArrayList<Bike>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
Statement stm = null;
ResultSet rs = null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
stm=con.createStatement();
String qry="Select * from bike";
rs=stm.executeQuery(qry);
while(rs.next())
{
/* I need to put
* rs.getString("name"),rs.getString("model")
* etc into any of the suitable collection objects
* and then need to add those to the ArrayList - bikeList
*
*/
}
return bikeList;
}
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17206523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930544/"
] | I don't know how Your Bike class look like, but you should do it like this way:
```
while(rs.next())
{
String column1 = rs.getString("column1_name");
.... and the others columns
Bike bike = new Bike();
bike.setColumn1(column1);
.... and others...
bikeList.add(bike)
}
``` | You need to instantiate Bike in while loop and add to `List`.
```
List<Bike> bikes = new ArrayList<>();
while(rs.next())
{
Bike bike = new Bike();
bike.setname( rs.getString("name"));
//other properties
bikes.add(bike);
}
return bikes;
``` | 2 | 0 |
17,206,523 | I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`?
Here is the code:
```
public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
List<Bike> bikeList = new ArrayList<Bike>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
Statement stm = null;
ResultSet rs = null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
stm=con.createStatement();
String qry="Select * from bike";
rs=stm.executeQuery(qry);
while(rs.next())
{
/* I need to put
* rs.getString("name"),rs.getString("model")
* etc into any of the suitable collection objects
* and then need to add those to the ArrayList - bikeList
*
*/
}
return bikeList;
}
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17206523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930544/"
] | For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list.
```
Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);
``` | I don't know how Your Bike class look like, but you should do it like this way:
```
while(rs.next())
{
String column1 = rs.getString("column1_name");
.... and the others columns
Bike bike = new Bike();
bike.setColumn1(column1);
.... and others...
bikeList.add(bike)
}
``` | 3 | 2 |
17,206,523 | I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`?
Here is the code:
```
public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
List<Bike> bikeList = new ArrayList<Bike>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
Statement stm = null;
ResultSet rs = null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
stm=con.createStatement();
String qry="Select * from bike";
rs=stm.executeQuery(qry);
while(rs.next())
{
/* I need to put
* rs.getString("name"),rs.getString("model")
* etc into any of the suitable collection objects
* and then need to add those to the ArrayList - bikeList
*
*/
}
return bikeList;
}
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17206523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930544/"
] | For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list.
```
Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);
``` | you would instantiate a Bike object and set properties that you read from result set, then add the bike object to your arraylist, isnt it what you are looking for? | 3 | 2 |
17,206,523 | I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`?
Here is the code:
```
public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
List<Bike> bikeList = new ArrayList<Bike>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
Statement stm = null;
ResultSet rs = null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
stm=con.createStatement();
String qry="Select * from bike";
rs=stm.executeQuery(qry);
while(rs.next())
{
/* I need to put
* rs.getString("name"),rs.getString("model")
* etc into any of the suitable collection objects
* and then need to add those to the ArrayList - bikeList
*
*/
}
return bikeList;
}
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17206523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930544/"
] | you would instantiate a Bike object and set properties that you read from result set, then add the bike object to your arraylist, isnt it what you are looking for? | You need to instantiate Bike in while loop and add to `List`.
```
List<Bike> bikes = new ArrayList<>();
while(rs.next())
{
Bike bike = new Bike();
bike.setname( rs.getString("name"));
//other properties
bikes.add(bike);
}
return bikes;
``` | 2 | 0 |
4,268,625 | What is the best and/or fastest to learn Java API for consuming XML feeds like this:
```
<body copyright="Company">
<student id="1" fname="Anthony" lname="Hopkins"/>
<student id="2" fname="John" lname="Anderson"/>
<student id="3" fname="Will" lname="Smitherman"/>
</body>
```
As you can see it provides all the data with attributes. Also, XML Feed data will be accessed using URLs with parameters specified in the query string.
Thanks in advance guys. | 2010/11/24 | [
"https://Stackoverflow.com/questions/4268625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311263/"
] | Easiest way is to use JaxB to generate the Java classes for you. If you have a schema you use xjb tool that will create the classes and can let java do all the parsing without you needing to do anything.
Look at <http://www.javaworld.com/javaworld/jw-06-2006/jw-0626-jaxb.html> | It depends on what you want to do with it but XStream might be the easiest way to import data from XML. This can produce a data structure to match your data. | 3 | 1 |
25,656,841 | I'm trying to make a Greasemonkey script to hide a really annoying div, on a website, that pops up after a few seconds. Neither of these works:
```
$("#flyin").hide();
$(document).ready(function(){
$("#flyin").hide();
});
```
I assume it's because the `#flyin` div is not created, yet. How do I tell jQuery to keep on looking for this div, maybe every n seconds, so I can hide it?
When I try to hide a non js, regular old div that is always present on the page, it works. | 2014/09/04 | [
"https://Stackoverflow.com/questions/25656841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1347640/"
] | There's [a utility for that (waitForKeyElements)](https://gist.github.com/2625891).
Your **whole script** would simply be:
```
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("#flyin", hideFlyin);
function hideFlyin (jNode) {
jNode.hide ();
}
```
Or, if the node only appears once per page load and the pages are not wholly changed via AJAX, use:
```
//-- Unload after one run.
waitForKeyElements ("#flyin", hideFlyin, true);
``` | Try
```
(function () {
var $el = $("#flyin").hide();
//the element is not already created
if (!$el.length) {
//create an interval to keep checking for the presents of the element
var timer = setInterval(function () {
var $el = $("#flyin").hide();
//if the element is already created, there is no need to keep running the timer so clear it
if ($el.length) {
clearInterval(timer);
}
}, 500);
}
})();
``` | 3 | 1 |
180,502 | I wrote a selector for several countries. This selector allows the user to choose a country, then a region and then a city. After the user chooses a city, it displays the selected object's country code, region code and area code (in terms of the [VK API](https://vk.com/dev/database.getCities) social network).
The selectors use the [jquery ui](https://api.jqueryui.com/autocomplete/) autocomplete plugin.
### HTML:
```
<div class="outer" id="countryOuter">
<input id="country" placeholder="Страна">
</div>
<div class="outer" id="regionOuter">
<input id="region" placeholder="Регион">
</div>
<div class="outer" id="cityOuter">
<input id="city" placeholder="Город">
</div>
```
### JS:
```
$( document ).ready(function() {
getCountries();
var countriesArr = [],
countriesObj = {};
var regionsArr = [],
regionsObj = {};
var citiesArr = [],
citiesObj = {};
$('#region').attr('disabled', 'disabled');
$('#city').attr('disabled', 'disabled');
function getCountries() {
$.ajax({
url: "http://api.vk.com/method/database.getCountries?v=5.69",
dataType: "jsonp",
success: function( data ) {
var countriesRaw = data['response']['items'];
console.log( countriesRaw );
countriesArr = countriesRaw.map(function(country) {
return country.title;
});
console.log(countriesArr);
countriesRaw.forEach(function(country) {
countriesObj[country.title] = country.id;
});
console.log(countriesObj);
document.getElementById('countryOuter').style.display = 'block';
$( "#country" ).autocomplete({
delay: 0.5,
source: countriesArr,
select: function(event, ui) {
$('#country').attr('disabled', 'disabled');
$('#region').removeAttr('disabled');
console.log(event, countriesObj[ui.item.label]);
getRegions(countriesObj[ui.item.label]);
}
});
}
});
};
function getRegions(countryId) {
$.ajax({
url: "http://api.vk.com/method/database.getRegions?v=5.69&country_id=" + countryId,
dataType: "jsonp",
success: function( data ) {
var regionsRaw = data['response']['items'];
console.log( regionsRaw );
regionsArr = regionsRaw.map(function(region) {
return region.title;
});
console.log(regionsArr);
regionsRaw.forEach(function(region) {
regionsObj[region.title] = region.id;
});
console.log(regionsObj);
console.log('____countryId', countryId);
$( "#region" ).autocomplete({
delay: 0.5,
source: regionsArr,
select: function(event, ui) {
$('#region').attr('disabled', 'disabled');
$('#city').removeAttr('disabled');
console.log(event, ui);
getCitiesOut(countryId, regionsObj[ui.item.label]);
}
});
}
})
};
function getCitiesOut(countryId, regionId) {
console.log('countryId, regionId', countryId, regionId);
getCities();
function getCities( offset, limit ) {
if( ! limit || limit > 1000 ) limit = 1000; //число запрашиваемых городов, максимально 1000, по умолчанию 1000
if( ! offset ) offset = 0; //по умолчанию 0
$.ajax({
url: "http://api.vk.com/method/database.getCities?v=5.69&need_all=0&count="+limit+"&country_id=" + countryId +"®ion_id=" + regionId +"&offset="+(offset*limit),
dataType: "jsonp",
success: function( data ) {
console.log('data', data);
var allCities = data.response.count;
console.log('allCities', allCities);
var citiesRaw = data['response']['items'];
//с помощью concat можно объеденить 2 массива.
citiesArr = citiesArr.concat(citiesRaw.map(function(city) {
return city.title;
}));
//если в текущем ответе не все города то делаем ещё запрос с новым offset
if( allCities > offset*limit + limit)
getCities(offset+1, limit);
console.log('citiesArr', citiesArr);
citiesRaw.forEach(function(cities) {
citiesObj[cities.title] = cities.id;
});
$( "#city" ).autocomplete({
delay: 0.5,
source: citiesArr,
select: function(event, ui) {
$('#city').attr('disabled', 'disabled');
console.log(event, ui);
alert('Код страны' + countryId + ', Код региона' + regionId + ', Код города' + citiesObj[ui.item.label]);
}
});
}
});
};
}
});
```
Unfortunately jsfiddle and similar services do not support JSONP-requests which are used in my code, but [this Plunker example demonstrates the code](http://embed.plnkr.co/fnTVnN0mcYdi5o4xO6XR/). | 2017/11/15 | [
"https://codereview.stackexchange.com/questions/180502",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/91959/"
] | 1. There is too much nesting, which, for me, makes the logic hard to read. A good rule of thumb is to aim for two levels of nesting, by using the Extract Method refactoring.
2. When the user clicks on the input, nothing happens. When the user starts typing a name that isn't in the list, sometimes the list pops up (if the initial matches) and sometimes they just type (if there is no matching string). I expect many users will be confused, and they might feel more comfortable if you re-used an existing paradigm.
3. Your three functions contain a lot of identical code. This means that whenever you want to change the user experience in all three fields, you will need to change it in three places. Yet if you want the experience to be consistent, you probably want to change it in only one place. I suggest extracting the common functionality into a shared function. | [dcorking](https://codereview.stackexchange.com/users/49616/dcorking) has good points in his/her [answer](https://codereview.stackexchange.com/a/180579/120114) - especially about the redundant code (i.e. point #3). Below is my suggestion to improve the code, in addition to his/her advice.
### Cache DOM Lookups
Like I mentioned in [this other answer](https://codereview.stackexchange.com/a/179480/120114) to one of your recent questions, it would be wise to store the DOM element references in variables when the DOM is ready, then use those whenever using the DOM elements instead of querying the DOM each time. While this code is quite small and only looks up DOM elements by ID 7 times, it is a good practice to get in the habit of - especially for working on pages where many DOM references will be needed by the Javascript code.
For example, the code could be updated like below:
```
$( document ).ready(function() {
//could use const instead of var for these, since they shouldn't be re-assigned
var regionInput = $('#region');
var cityInput = $('#city');
//later on, reference those variables instead of querying each time they are needed
regionInput.attr('disabled', 'disabled');
cityInput.attr('disabled', 'disabled');
```
Note the comment about using [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)- it could be used in place of [var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) unless [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Browser_compatibility) is an issue. | 3 | 2 |
83,635 | I'm a complete cooking newb. I saw on youtube the other day that you should cook steak in an oven before frying it. I think it makes it softer (not sure, please let me know).
But anyway, I never used an oven in my entire life. And I looked inside the oven and there are no trays in there. So I went to the store and the only trays I saw in the cooking section were meant for "cookies" that you cook in the oven, and other things like that, muffins etc. But they never mentioned steak.
So can I cook my steak on trays meant for deserts, or do I need to look for a tray meant for steaks? and should I even cook my steak in the oven in the first place? | 2017/08/10 | [
"https://cooking.stackexchange.com/questions/83635",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/60749/"
] | To answer your question directly, if the method of cooking is what I think it is, the pan you use should be fine, even if it has a nonstick coating on it. You can read the second section to see if my assumption about your cooking method is correct.
It's important that you don't use nonstick cookware for extremely high heat cooking. If the nonstick coating gets to the smoking point, it releases gases that are toxic enough (as a friend tragically learned) to kill pets. This includes pans that go in the oven, and on the stovetop.
Since the temperature at which you're cooking the steak isn't that much hotter than you'd use baking cookies, it should be fine. If it does have a nonstick coating, you should not use it under a broiler, which is much hotter than just sitting in the oven while it bakes.
---
Even though it's not exactly what you asked, since you don't seem to be super confident in what you're doing, I'll give you a little more info on what I believe is the technique you're trying to pull off.
I think what you're referring to is the method of cooking where you cook a steak slowly in the oven until the internal doneness (rare, medium rare, etc.) is just how you like it, and then you give it a good hot sear in a pan so you form a flavorful crust on the outside. It's pretty intuitive when you consider the following:
* Making sure steak (or chicken, or pork chops, or other quick-cooking cuts of meat) is cooked through simply involves getting it to the desired internal temperature. The more consistent the internal temperature throughout the meat, the more consistent the texture and juiciness.
+ The best way to control the overall internal temperature of the meat is to use gentler lower temperature methods of cooking so the inside has time to warm up before the outside gets overcooked.
* Getting optimum flavor in a steak requires a nice sear/crust on the meat.
+ The best way to get a nice crust on your steak is to add a decent amount of salt, and use a high-heat cooking method to trigger the Maillard reaction (what's happening chemically when browning occurs) and perhaps some charring.
You can see where the conflict lies between these two needs.
Using the method you read about, you can use the oven to gently bring it up to temperature so it's consistently cooked inside, and then you can use a pan (which does not have a nonstick coating) to give it a nice hot sear after it comes out of the oven.
It is easy to overcook steak if you're not particularly experienced, especially using more complicated dual-cook methods. Nobody wants to eat a tough, dry mess. Though it's tempting to rely on cooking times you find on the internet, **time is usually the least precise method to determine how cooked something is.** I highly recommend using an instant-read thermometer to check the actual temperature inside. | The method I think you are referring to is called "reverse sear". When I do a reverse sear, I use a standard [wire rack](http://dailydecor.foodiefriendsfridaydailydish.com/wp-content/uploads/2015/04/30b0052baa76.jpg) on top of a foil covered baking sheet. I'm not sure precisely what you mean by a dessert tray - but you probably want something (like a wire rack) that allows airflow on all sides, including the bottom.
IMO the [Serious Eats guide](https://www.seriouseats.com/2017/03/how-to-reverse-sear-best-way-to-cook-steak.html) is great, it got me started using this method.
Edit(3) to add: the big advantage of the reverse sear is that you can control the cooking process more precisely and get a steak that's seared on the outside, but not overcooked on the inside. Similar to Cooking Sous Vide then searing, but without the expense/clutter of a SV cooker.
As SomeInterwebDev points out, you definitely want to be cooking to an internal temp, not by time to get a good result here. | 2 | 1 |
31,714,522 | I have two strings.
```
str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"
```
I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`).
I know I could solve this with something like the following:
```
def diff_char_index(str_a, str_b)
arr_a, arr_b = str_a.split(""), str_b.split("")
return -1 unless valid_string?(str_a) && valid_string?(str_b)
arr_a.each_index do |i|
return i unless arr_a[i] == arr_b[i]
end
end
def valid_string?(str)
return false unless str.is_a?(String)
return false unless str.size > 0
true
end
diff_char_index(str_a, str_b) # => 10
```
Is there a better way to do this? | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295407/"
] | Something like this ought to work:
```
str_a.each_char.with_index
.find_index {|char, idx| char != str_b[idx] } || str_a.size
```
**Edit:** It works: <http://ideone.com/Ttwu1x>
**Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4).
Here's another method that may strike some as slightly simpler:
```
(0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size
```
<http://ideone.com/275cEU> | ```
i = 0
i += 1 while str_a[i] and str_a[i] == str_b[i]
i
``` | 4 | 1 |
31,714,522 | I have two strings.
```
str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"
```
I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`).
I know I could solve this with something like the following:
```
def diff_char_index(str_a, str_b)
arr_a, arr_b = str_a.split(""), str_b.split("")
return -1 unless valid_string?(str_a) && valid_string?(str_b)
arr_a.each_index do |i|
return i unless arr_a[i] == arr_b[i]
end
end
def valid_string?(str)
return false unless str.is_a?(String)
return false unless str.size > 0
true
end
diff_char_index(str_a, str_b) # => 10
```
Is there a better way to do this? | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295407/"
] | Something like this ought to work:
```
str_a.each_char.with_index
.find_index {|char, idx| char != str_b[idx] } || str_a.size
```
**Edit:** It works: <http://ideone.com/Ttwu1x>
**Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4).
Here's another method that may strike some as slightly simpler:
```
(0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size
```
<http://ideone.com/275cEU> | This uses a binary search to find the index where a slice of `str_a` no longer occurs at the beginning of `str_b`:
```
(0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 }
``` | 4 | 0 |
31,714,522 | I have two strings.
```
str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"
```
I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`).
I know I could solve this with something like the following:
```
def diff_char_index(str_a, str_b)
arr_a, arr_b = str_a.split(""), str_b.split("")
return -1 unless valid_string?(str_a) && valid_string?(str_b)
arr_a.each_index do |i|
return i unless arr_a[i] == arr_b[i]
end
end
def valid_string?(str)
return false unless str.is_a?(String)
return false unless str.size > 0
true
end
diff_char_index(str_a, str_b) # => 10
```
Is there a better way to do this? | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295407/"
] | Something like this ought to work:
```
str_a.each_char.with_index
.find_index {|char, idx| char != str_b[idx] } || str_a.size
```
**Edit:** It works: <http://ideone.com/Ttwu1x>
**Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4).
Here's another method that may strike some as slightly simpler:
```
(0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size
```
<http://ideone.com/275cEU> | ```
str_a = "the_quick_brown_dog"
str_b = "the_quick_red_dog"
(0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? }
#=> 10
str_a = "the_quick_brown_dog"
str_b = "the_quick_brown_dog"
(0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? }
#=> 19
str_a.size
#=> 19
``` | 4 | 1 |
31,714,522 | I have two strings.
```
str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"
```
I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`).
I know I could solve this with something like the following:
```
def diff_char_index(str_a, str_b)
arr_a, arr_b = str_a.split(""), str_b.split("")
return -1 unless valid_string?(str_a) && valid_string?(str_b)
arr_a.each_index do |i|
return i unless arr_a[i] == arr_b[i]
end
end
def valid_string?(str)
return false unless str.is_a?(String)
return false unless str.size > 0
true
end
diff_char_index(str_a, str_b) # => 10
```
Is there a better way to do this? | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295407/"
] | ```
i = 0
i += 1 while str_a[i] and str_a[i] == str_b[i]
i
``` | This uses a binary search to find the index where a slice of `str_a` no longer occurs at the beginning of `str_b`:
```
(0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 }
``` | 1 | 0 |
31,714,522 | I have two strings.
```
str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"
```
I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`).
I know I could solve this with something like the following:
```
def diff_char_index(str_a, str_b)
arr_a, arr_b = str_a.split(""), str_b.split("")
return -1 unless valid_string?(str_a) && valid_string?(str_b)
arr_a.each_index do |i|
return i unless arr_a[i] == arr_b[i]
end
end
def valid_string?(str)
return false unless str.is_a?(String)
return false unless str.size > 0
true
end
diff_char_index(str_a, str_b) # => 10
```
Is there a better way to do this? | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295407/"
] | ```
str_a = "the_quick_brown_dog"
str_b = "the_quick_red_dog"
(0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? }
#=> 10
str_a = "the_quick_brown_dog"
str_b = "the_quick_brown_dog"
(0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? }
#=> 19
str_a.size
#=> 19
``` | This uses a binary search to find the index where a slice of `str_a` no longer occurs at the beginning of `str_b`:
```
(0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 }
``` | 1 | 0 |
2,015 | So this question... <https://serverfault.com/questions/45734/the-coolest-server-names>
It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community).
I understand that it's being kept around for its historical significance, but it's not this site's history.
It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots.
Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end?
The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. | 2011/09/04 | [
"https://meta.serverfault.com/questions/2015",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/33118/"
] | If it were my choice, I'd just hit the delete button on it here and be done with it.
Yes, by today's rules it is off topic both here and on Stack Overflow. I don't feel it adds *any* useful information to this site, or any on the Stack Exchange network. It goes no way towards the Stack Exchange mission of "make the internet better" and as such should simply be obliterated.
I'd like to think we've all become much less tolerant of crap since December '10 when it was resurrected, and I'd hope everyone else would also agree. There has been a very visible onslaught against bad questions that don't add value to the internet, and to me this is one of them. Hey, it was practically Christmas - maybe Jeff had a few drinks and was feeling generous? :-) | Send it back from whence it came. | 4 | 0 |
2,015 | So this question... <https://serverfault.com/questions/45734/the-coolest-server-names>
It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community).
I understand that it's being kept around for its historical significance, but it's not this site's history.
It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots.
Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end?
The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. | 2011/09/04 | [
"https://meta.serverfault.com/questions/2015",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/33118/"
] | If it were my choice, I'd just hit the delete button on it here and be done with it.
Yes, by today's rules it is off topic both here and on Stack Overflow. I don't feel it adds *any* useful information to this site, or any on the Stack Exchange network. It goes no way towards the Stack Exchange mission of "make the internet better" and as such should simply be obliterated.
I'd like to think we've all become much less tolerant of crap since December '10 when it was resurrected, and I'd hope everyone else would also agree. There has been a very visible onslaught against bad questions that don't add value to the internet, and to me this is one of them. Hey, it was practically Christmas - maybe Jeff had a few drinks and was feeling generous? :-) | It needs to be burniated.
It adds nothing to the site. It was a "fun" question once upon a time *maybe* but we've moved on from that.
Perhaps it should be locked while its fate is being debated? | 4 | 2 |
2,015 | So this question... <https://serverfault.com/questions/45734/the-coolest-server-names>
It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community).
I understand that it's being kept around for its historical significance, but it's not this site's history.
It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots.
Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end?
The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. | 2011/09/04 | [
"https://meta.serverfault.com/questions/2015",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/33118/"
] | Hear ye, hear ye, hear ye,
--------------------------
Three days have passed. Since then:
* 30% of our >10K users have voted to delete that question, independent of the vote going on here.
* 22 upvotes for sun-based disposal
* 4 upvotes for 'send it back from whence it came'
* Showers of hate upon 'Leave it'.
Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting.
It is gone.
![Record of destruction](https://i.stack.imgur.com/3jY0B.png) | It needs to be burniated.
It adds nothing to the site. It was a "fun" question once upon a time *maybe* but we've moved on from that.
Perhaps it should be locked while its fate is being debated? | 4 | 2 |
2,015 | So this question... <https://serverfault.com/questions/45734/the-coolest-server-names>
It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community).
I understand that it's being kept around for its historical significance, but it's not this site's history.
It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots.
Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end?
The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. | 2011/09/04 | [
"https://meta.serverfault.com/questions/2015",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/33118/"
] | Throw this question into the sun. | I've certainly done my bit to try and get rid of that question, as well as similar ones, but the system is against us. If Jeff brought it back from the dead I'd love to hear his reasoning for doing so. The only reasoning I can think of is that it brings traffic due to Google and traffic translates to revenue and revenue is the reason Stack Exchange exists.
That question is part of the history of SF only in the sense of being a great example of what NOT to post. Rather than adding value it merely detracts from SF and on at least one occasion I've seen it referenced as an excuse to post an off-topic question ("if they can do it why can't I?"). | 5 | 3 |
2,015 | So this question... <https://serverfault.com/questions/45734/the-coolest-server-names>
It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community).
I understand that it's being kept around for its historical significance, but it's not this site's history.
It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots.
Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end?
The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. | 2011/09/04 | [
"https://meta.serverfault.com/questions/2015",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/33118/"
] | Throw this question into the sun. | Hear ye, hear ye, hear ye,
--------------------------
Three days have passed. Since then:
* 30% of our >10K users have voted to delete that question, independent of the vote going on here.
* 22 upvotes for sun-based disposal
* 4 upvotes for 'send it back from whence it came'
* Showers of hate upon 'Leave it'.
Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting.
It is gone.
![Record of destruction](https://i.stack.imgur.com/3jY0B.png) | 5 | 4 |
115,769 | I have a 40 gallon (bladdered) pressure tank in the basement which keeps pressure to my office building, and a 2-inch 2 horsepower submersible pump in a dug well 450 feet away.
The pump is cycling waaay too fast, and the tank will hold pressure at 41 pounds to 43 pounds but not at 60 pounds at shut-off pressure. (The pump comes on at 40 and shuts off at 60). It only takes 6 seconds for the pump to come on and shut off and I fear I will cook the pump if this keeps up.
I have recently tested the pressure in the tank and it is 50 pounds. Does this mean the bladder leaked and caused pressure to increase in the tank? I know the tank pressure should be set at around 39, or a little below the 'turn-on' pressure. Could this be the cause of the short cycle? | 2017/06/02 | [
"https://diy.stackexchange.com/questions/115769",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/70373/"
] | The bladder is there to flatten the pressure/volume curve so pressure doesn't change rapidly as water is pumped.
This allows for a longer duty cycle.
The expected symptom of a burst bladder is just as you describe. | It needs air.
Get hold of an air compressor and give it a charge. Be sure to be running water while charging, and the pump is off. Easy.
If you need to do this more than once a year there might be a problem with the bladder. | 1 | 0 |
9,482,602 | I'm working on a Google Chrome extension with a popup, in which I load a page from a node.js + express.js server. The page I load changes depending on the status of the `req.session.user` in this way:
```
app.get('/', function(req, res){
if(req.session.user){
res.render(__dirname + '/pages/base.jade', {});
}
else{
res.render(__dirname + '/pages/login_register.jade', {});
}
});
```
If `req.session.user` is null I send a page in which the user can do the login or register. If he/she does a login, this is what happens in the server:
```
app.post('/login', function(req, res){
var user = {};
user.username = req.body.username;
user.password = req.body.password;
checkLogin(user, function(foundUser){
//login correct
console.log("login!");
req.session.user = foundUser;
res.render(__dirname + '/pages/base.jade', {
});
});
});
```
So if the user logs in correctly `req.session.user` should be set with the credentials of the current user. The problem is that once I log in and then close the popup of the Chrome extension, whenever I reopen it I still receive the login page.
My question is: does the popup supports session storage in the express.js server? If yes, then there is something wrong with my code, can anyone point out what am I doing wrong? Thanks.
EDIT:
This is how I setup the server:
```
var app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
```
I might be doing something redundant here, since I still don't have a deep understanding of how that works. | 2012/02/28 | [
"https://Stackoverflow.com/questions/9482602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/617461/"
] | The problem is how you have set up your server - you're using the `cookieParser` and `session` middlewares twice:
```
var app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
```
You should only use *either* middlewares as parameters to `createServer`, *or* `use`, so:
```
var app = express.createServer();
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
``` | Popup page probably reloads every time you open it. You should create a backgroundpage for your extension where you could store/manage sessions. Then you can communicate from popup to backgroundpage passing messages [docs](http://code.google.com/chrome/extensions/messaging.html). Using messaging you can send login data to backgroundpage and also ask whether user has already logged in. | 3 | 0 |
19,270,638 | I am creating a BitSet with a fixed number of bits.
In this case the length of my String holding the binary representation is 508 characters long.
So I create BitSet the following way:
```
BitSet bs = new BitSet(binary.length());
// binary.length() = 508
```
But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.
Maybe there is some misunderstanding of the following documentation:
> **BitSet(int nbits)**
>
>
> Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.
Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19270638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664010/"
] | The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that.
> So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ?
Correct, and yes.
If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method.
> If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0.
In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value.
A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.) | According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use.
Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time. | 3 | 2 |
19,270,638 | I am creating a BitSet with a fixed number of bits.
In this case the length of my String holding the binary representation is 508 characters long.
So I create BitSet the following way:
```
BitSet bs = new BitSet(binary.length());
// binary.length() = 508
```
But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.
Maybe there is some misunderstanding of the following documentation:
> **BitSet(int nbits)**
>
>
> Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.
Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19270638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664010/"
] | The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that.
> So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ?
Correct, and yes.
If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method.
> If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0.
In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value.
A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.) | That's just a hint for a collection (this applies to all collections I think) so it don't have to resize itself after adding elements. For instance, if you know that your collection will hold 100 elements at maximum, you can set it's size to 100 and no resize will be made which is better for performance. | 3 | 0 |
19,270,638 | I am creating a BitSet with a fixed number of bits.
In this case the length of my String holding the binary representation is 508 characters long.
So I create BitSet the following way:
```
BitSet bs = new BitSet(binary.length());
// binary.length() = 508
```
But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.
Maybe there is some misunderstanding of the following documentation:
> **BitSet(int nbits)**
>
>
> Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.
Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19270638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664010/"
] | The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that.
> So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ?
Correct, and yes.
If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method.
> If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0.
In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value.
A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.) | The BitSet size will be set to the first multiple of 64 that is equal to or greater than the number you use for 'size'. If you specify a 'size' of 508, you will get a BitSet with an actual size of 512, which is the next highest multiple of 64. | 3 | 0 |
19,270,638 | I am creating a BitSet with a fixed number of bits.
In this case the length of my String holding the binary representation is 508 characters long.
So I create BitSet the following way:
```
BitSet bs = new BitSet(binary.length());
// binary.length() = 508
```
But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.
Maybe there is some misunderstanding of the following documentation:
> **BitSet(int nbits)**
>
>
> Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.
Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19270638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664010/"
] | According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use.
Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time. | That's just a hint for a collection (this applies to all collections I think) so it don't have to resize itself after adding elements. For instance, if you know that your collection will hold 100 elements at maximum, you can set it's size to 100 and no resize will be made which is better for performance. | 2 | 0 |
19,270,638 | I am creating a BitSet with a fixed number of bits.
In this case the length of my String holding the binary representation is 508 characters long.
So I create BitSet the following way:
```
BitSet bs = new BitSet(binary.length());
// binary.length() = 508
```
But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.
Maybe there is some misunderstanding of the following documentation:
> **BitSet(int nbits)**
>
>
> Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.
Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19270638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664010/"
] | According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use.
Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time. | The BitSet size will be set to the first multiple of 64 that is equal to or greater than the number you use for 'size'. If you specify a 'size' of 508, you will get a BitSet with an actual size of 512, which is the next highest multiple of 64. | 2 | 0 |
41,004,429 | hi guys this is my "login.php":
```
<?php
session_start();
// connect to database
if (isset($_POST['login_btn'])) {
$username =$_POST['username'];
$password =$_POST['password'];
$_SESSION['username'] = $_POST['username'];
$conn = oci_connect('insidedba', 'progetto16', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$password = md5($password); // remember we hashed password before storing last time
$sql = oci_parse($conn,"SELECT * FROM UTENTI WHERE USERNAME='$username' AND PASSWORD='$password'");
$result =oci_execute($sql);
if ($result) {
$stid = oci_parse($conn, "SELECT * FROM UTENTI WHERE username='$username' AND password='$password'");
oci_execute($stid);
oci_fetch($stid);
if (oci_num_rows($stid) == 1) {
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: panel/index.php"); //redirect to home page
} else{
$_SESSION['message'] = "Username/password combination incorrect";
}
} else {
$_SESSION['message'] = "Query error";
}
}
?>
```
and it works,and i'm asking if i can use the $username variable in another php.
"myorder.php":
```
<?php
session_start()
$conn = oci_connect('insidedba', 'progetto16', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$columns = array(
'Nome cinema ' => 'NOME_CINEMA',
'Ora' => 'ORARIO',
'Data' => 'DATA',
'Titolo' => 'TITOLO',
'Numero prenotazione' =>'Codice_della_prenotazione',
'Numero sala' =>'Numero_sala',
'Fila' =>'fila',
'Numero sala' =>'numero',
);
// Run the query
$sql = oci_parse($conn,"SELECT DISTINCT CIN.NOME AS NOME_CINEMA,PAL.DATA as DATA,PAL.ORA ORARIO,F.Titolo as TITOLO,
PRE.ID as Codice_della_prenotazione,S.CODS AS Numero_sala,P.FILA as fila,P.NUMERO as numero
FROM (((((UTENTI U JOIN PRENOTAZIONI PRE ON PRE.UTENTE=U.ID AND U.USERNAME='$username')
JOIN PALINSESTI PAL ON PAL.ID=PRE.PALINSESTO)
JOIN FILM F ON F.ID=PAL.FILM)
JOIN CINEMA CIN ON CIN.ID=PAL.CINEMA )
JOIN POSTI P ON P.PRENOTAZIONE=PRE.ID AND P.CINEMA=CIN.ID)
JOIN SALE S ON S.CINEMA=CIN.ID and p.SALA=S.CODS WHERE BOOL_PAGATO=1
ORDER BY PRE.ID");
oci_execute($sql);
// Output table header
echo "<table border=\"1px solid black\" width=\"95%\"><tr>";
foreach ($columns as $name => $col_name) {
echo "<th>$name</th>";
}
echo "</tr>";
// Output rows
while($row = oci_fetch_array($sql)) {
echo "<tr>";
foreach ($columns as $name => $col_name) {
echo "<td style=\"text-align:center;\">". $row[$col_name] . "</td>";
}
echo "</tr>";
}
// Close table
echo "</table>"
?>
```
it says undefined variable,
How can i solve this?
i tried " but it still doesnt work. | 2016/12/06 | [
"https://Stackoverflow.com/questions/41004429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7160791/"
] | If it's stored in session you can.
```
session_start();
if(!empty($_SESSION['username'])) $username = $_SESSION['username'];
else $username = "guest";
``` | You need to use the `U.USERNAME=$_SESSION['username']` variable in your *myorder.php* file.
By the way, in the code you're showing you don't have a `$username` variable in *myorder.php*, I guess you had in the SQL query that you now have: `U.USERNAME='$prova'` | 2 | 0 |
65,915,932 | I tried to look in other solutions. But it didn't help me out. Kindly look into this.
my html code.
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %}
<form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
my views.py and urls.py code
```
def delete_data(request,id):
if request.method == 'POST':
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
urlpatterns=[
re_path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2021/01/27 | [
"https://Stackoverflow.com/questions/65915932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533843/"
] | You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`.
Regex solution:
```
urlpatterns=[
re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata")
]
```
path solution:
```
from django.urls import path
urlpatterns=[
path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
```
**Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template.
Change your view definition (and all usages of the variable in the view function to **pk**) to:
```
def delete_data(request, pk):
``` | Try this
In the template, you have used pk
change in the template or in view and url
```
urlpatterns=[
re_path('<int:pk>/',views.update_data,name="deletedata")
]
```
Or
```
<form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
``` | 2 | 1 |
65,915,932 | I tried to look in other solutions. But it didn't help me out. Kindly look into this.
my html code.
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %}
<form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
my views.py and urls.py code
```
def delete_data(request,id):
if request.method == 'POST':
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
urlpatterns=[
re_path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2021/01/27 | [
"https://Stackoverflow.com/questions/65915932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533843/"
] | Try this
In the template, you have used pk
change in the template or in view and url
```
urlpatterns=[
re_path('<int:pk>/',views.update_data,name="deletedata")
]
```
Or
```
<form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
``` | {% url 'deletedata' pk = st.id %}
in thr URL just remove the spaces, bellow code it should work
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a>
<form action="{% url 'deletedata' pk=st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
``` | 1 | 0 |
65,915,932 | I tried to look in other solutions. But it didn't help me out. Kindly look into this.
my html code.
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %}
<form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
my views.py and urls.py code
```
def delete_data(request,id):
if request.method == 'POST':
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
urlpatterns=[
re_path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2021/01/27 | [
"https://Stackoverflow.com/questions/65915932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533843/"
] | Try this
In the template, you have used pk
change in the template or in view and url
```
urlpatterns=[
re_path('<int:pk>/',views.update_data,name="deletedata")
]
```
Or
```
<form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
``` | You can also write it with one a tag
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a>
<a href="{% url 'deletedata' pk=st.id %}" class="d-inline">Delete</a>
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
and then your views.py
```
def delete_data(request,id):
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
```
Urls.py
```
urlpatterns=[
path('<int:pk>/',views.delete_data,name="deletedata")
]
``` | 1 | 0 |
65,915,932 | I tried to look in other solutions. But it didn't help me out. Kindly look into this.
my html code.
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %}
<form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
my views.py and urls.py code
```
def delete_data(request,id):
if request.method == 'POST':
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
urlpatterns=[
re_path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2021/01/27 | [
"https://Stackoverflow.com/questions/65915932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533843/"
] | You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`.
Regex solution:
```
urlpatterns=[
re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata")
]
```
path solution:
```
from django.urls import path
urlpatterns=[
path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
```
**Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template.
Change your view definition (and all usages of the variable in the view function to **pk**) to:
```
def delete_data(request, pk):
``` | {% url 'deletedata' pk = st.id %}
in thr URL just remove the spaces, bellow code it should work
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a>
<form action="{% url 'deletedata' pk=st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
``` | 2 | 0 |
65,915,932 | I tried to look in other solutions. But it didn't help me out. Kindly look into this.
my html code.
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %}
<form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
my views.py and urls.py code
```
def delete_data(request,id):
if request.method == 'POST':
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
urlpatterns=[
re_path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2021/01/27 | [
"https://Stackoverflow.com/questions/65915932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533843/"
] | You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`.
Regex solution:
```
urlpatterns=[
re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata")
]
```
path solution:
```
from django.urls import path
urlpatterns=[
path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
```
**Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template.
Change your view definition (and all usages of the variable in the view function to **pk**) to:
```
def delete_data(request, pk):
``` | You can also write it with one a tag
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a>
<a href="{% url 'deletedata' pk=st.id %}" class="d-inline">Delete</a>
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
and then your views.py
```
def delete_data(request,id):
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
```
Urls.py
```
urlpatterns=[
path('<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2 | 0 |
12,165,002 | You know how PHP's `isset()` can accept multiple (no limit either) arguments?
Like I can do:
```
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
```
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12165002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use `func_get_args()`, it will return an array of arguments.
```
function work_with_arguments() {
echo implode(", ", func_get_args());
}
work_with_arguments("Hello", "World");
//Outputs: Hello, World
``` | Calling `[func_get_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP. | 2 | 1 |
12,165,002 | You know how PHP's `isset()` can accept multiple (no limit either) arguments?
Like I can do:
```
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
```
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12165002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Starting with PHP 5.6 you can use the token "**...**"
Example:
```
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
```
Source:
<http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list> | Calling `[func_get_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP. | 5 | 1 |
12,165,002 | You know how PHP's `isset()` can accept multiple (no limit either) arguments?
Like I can do:
```
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
```
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12165002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | [`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want:
```
function infinite_parameters() {
foreach (func_get_args() as $param) {
echo "Param is $param" . PHP_EOL;
}
}
```
You can also use `func_get_arg` to get a specific parameter (it's zero-indexed):
```
function infinite_parameters() {
echo func_get_arg(2);
}
```
But be careful to check that you have that parameter:
```
function infinite_parameters() {
if (func_num_args() < 3) {
throw new BadFunctionCallException("Not enough parameters!");
}
}
```
You can even mix together `func_*_arg` and regular parameters:
```
function foo($param1, $param2) {
echo $param1; // Works as normal
echo func_get_arg(0); // Gets $param1
if (func_num_args() >= 3) {
echo func_get_arg(2);
}
}
```
But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice? | Starting with PHP 5.6 you can use the token "**...**"
Example:
```
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
```
Source:
<http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list> | 7 | 5 |
12,165,002 | You know how PHP's `isset()` can accept multiple (no limit either) arguments?
Like I can do:
```
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
```
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12165002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | [`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want:
```
function infinite_parameters() {
foreach (func_get_args() as $param) {
echo "Param is $param" . PHP_EOL;
}
}
```
You can also use `func_get_arg` to get a specific parameter (it's zero-indexed):
```
function infinite_parameters() {
echo func_get_arg(2);
}
```
But be careful to check that you have that parameter:
```
function infinite_parameters() {
if (func_num_args() < 3) {
throw new BadFunctionCallException("Not enough parameters!");
}
}
```
You can even mix together `func_*_arg` and regular parameters:
```
function foo($param1, $param2) {
echo $param1; // Works as normal
echo func_get_arg(0); // Gets $param1
if (func_num_args() >= 3) {
echo func_get_arg(2);
}
}
```
But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice? | You can use `func_get_args()`, it will return an array of arguments.
```
function work_with_arguments() {
echo implode(", ", func_get_args());
}
work_with_arguments("Hello", "World");
//Outputs: Hello, World
``` | 7 | 2 |
12,165,002 | You know how PHP's `isset()` can accept multiple (no limit either) arguments?
Like I can do:
```
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
```
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12165002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Starting with PHP 5.6 you can use the token "**...**"
Example:
```
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
```
Source:
<http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list> | You can use `func_get_args()`, it will return an array of arguments.
```
function work_with_arguments() {
echo implode(", ", func_get_args());
}
work_with_arguments("Hello", "World");
//Outputs: Hello, World
``` | 5 | 2 |
75,277 | I've seen quite a few security camera examples and many have options for a duty schedule that activates the camera during certain specified days/hours to set up a routine. However I have fairly dynamic schedule and would like for my security cameras to turn on when our phones are not on the WiFi network. This would be an easy shortcut to "on when we're not home" and prevents it from taking intrusive pictures when we are.
Is there a way to configure OpenCV or Motion, or to run a python script to activate a camera when our phones are off the WiFi network? I would like to take advantage of some features of the above software to email or stream footage, so I would like to avoid redesigning a system from the ground up to do this.
Any advice? Thanks! | 2017/11/16 | [
"https://raspberrypi.stackexchange.com/questions/75277",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/54665/"
] | You'd need to know either the MAC or IP address of the phones you want to monitor but you could just `ping` or `arping` each one in turn and if none reply start your recording otherwise stop recording. Calling something like this from `cron` might do the trick:
```
#!/bin/bash
#
# Determine if we should be recording or not by pinging each phone in the list
# and setting the variable to "NO" if any reply. If the variable is still "YES"
# at the end we check if the recording process is running and start it if not.
#
LIST="192.168.123.25 192.168.123.56 192.168.123.13 MyPhone.local 192.168.123.78"
RECORD_CMD="RecordingCommand"
RECORD="YES"
for HOST in $LIST; do
ping -c1 "$HOST" &> /dev/null && RECORD="NO"
done
if [ "$RECORD" == "YES" ]; then
# Start or continue recording?
if [ $(pgrep -c "$RECORD_CMD") -eq 0 ]; then
# Not currently recording so we need to start...
"$RECORD_CMD"
fi
else
# Stop recording...
killall "$RECORD_CMD"
fi
exit 0
``` | Your question appears to be about ***activating*** and ***disabling*** the cameras when you are not able to connect to them directly when your phones are not on the same local subnet. So it seems to be about ***networking*** and access to control them, rather than the phones themselves that you reference. That's what I *believe* that I see here.
Since the cameras are on an RFC 1918 non-routable address, when you're away from home you can't connect to 192.168.1.1 for example as it's *not routable across the Internet*. The solution is a VPN. Many routers now have this functionality as standard and make it easy to set up a VPN connection back to your home network just by adding a username and password for the VPN account and off you go. Once you connect to your home router via that VPN connection, you can now be connect to the cameras, switch, etc on their non-public IP addresses.
With a VPN you'd just ssh into the Pi-Cam via it's local address and execute `sudo systemctl stop/start motion` and directly issue commands to control it. Further, with a VPN connection back to your home network, you will be able to view streams from the cameras directly on a web browser on your phone. | 1 | 0 |
58,655,207 | I'm currently trying to extend [a model](https://github.com/microsoft/MASS) that is based on FairSeq/PyTorch. During training I need to train two encoders: one with the target sample, and the original one with the source sample.
So the current forward function looks like this:
```
def forward(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
decoder_out = self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs)
return decoder_out
```
And based on this [this idea](https://github.com/golsun/SpaceFusion) i want something like this:
```
def forward_test(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
decoder_out = self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs)
return decoder_out
def forward_train(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
autoencoder_out = self.encoder(tgt_tokens, src_lengths=src_lengths, **kwargs)
concat = some_concatination_func(encoder_out, autoencoder_out)
decoder_out = self.decoder(prev_output_tokens, encoder_out=concat, **kwargs)
return decoder_out
```
Is there any way to do this?
Edit:
These are the constraints that I have, since I need to extend *FairseqEncoderDecoderModel*:
```
@register_model('transformer_mass')
class TransformerMASSModel(FairseqEncoderDecoderModel):
def __init__(self, encoder, decoder):
super().__init__(encoder, decoder)
```
Edit 2:
The parameters passed to the forward function in Fairseq can be altered by implementing your own Criterion, see for example [CrossEntropyCriterion](https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/cross_entropy.py#L28), where `sample['net_input']` is passed to the `__call__` function of the model, which invokes the `forward` method. | 2019/11/01 | [
"https://Stackoverflow.com/questions/58655207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128562/"
] | First of all you should **always use and define `forward`** not some other methods that you call on the `torch.nn.Module` instance.
**Definitely do not overload `eval()` as shown by [trsvchn](https://stackoverflow.com/a/58659193/10886420) as it's evaluation method defined by PyTorch ([see here](https://pytorch.org/docs/stable/nn.html#torch.nn.Module.eval)).** This method allows layers inside your model to be put into evaluation mode (e.g. specific changes to layers like inference mode for `Dropout` or `BatchNorm`).
Furthermore you should call it with `__call__` magic method. Why? Because hooks and other PyTorch specific stuff is registered that way properly.
**Secondly, do not use some external `mode` string variable as suggested by [@Anant Mittal](https://stackoverflow.com/questions/58655207/pytorch-different-forward-methods-for-train-and-test-validation/58655415#58655415)**. That's what `train` variable in PyTorch is for, it's standard to differentiate by it whether model is in `eval` mode or `train` mode.
That being said you are the best off doing it like this:
```
import torch
class Network(torch.nn.Module):
def __init__(self):
super().__init__()
...
# You could split it into two functions but both should be called by forward
def forward(
self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs
):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
if self.train:
return self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs)
autoencoder_out = self.encoder(tgt_tokens, src_lengths=src_lengths, **kwargs)
concat = some_concatination_func(encoder_out, autoencoder_out)
return self.decoder(prev_output_tokens, encoder_out=concat, **kwargs)
```
You could (and arguably should) split the above into two separate methods, but that's not too bad as the function is rather short and readable that way. Just stick to PyTorch's way of handling things if easily possible and not some ad-hoc solutions. And no, there will be no problem with backpropagation, why would there be one? | By default, calling `model()` invoke `forward` method which is train forward in your case, so you just need to define new method for your test/eval path inside your model class, smth like here:
Code:
```py
class FooBar(nn.Module):
"""Dummy Net for testing/debugging.
"""
def __init__(self):
super().__init__()
...
def forward(self, x):
# here will be train forward
...
def evaltest(self, x):
# here will be eval/test forward
...
```
Examples:
```py
model = FooBar() # initialize model
# train time
pred = model(x) # calls forward() method under the hood
# test/eval time
test_pred = model.evaltest(x)
```
**Comment:**
I would like to recommend you to split these two forward paths into 2 separate methods, because it easier to debug and to avoid some possible problems when backpropagating. | 4 | 0 |
3,829,211 | I did some changes at my CoreData Model. So far, I added a attribute called 'language'. When my application is launched and I click on "Create new Customer" a instance variable Customer is created. This variable is created by:
```
Customer *newCustomer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:appDelegate.managedObjectContext];
```
Before I did these changes everything worked fine and as planned. But now i get a dump with this error message:`reason = "The model used to open the store is incompatible with the one used to create the store";`
What do I have to do to solve this? reseting the persistence store didn't help so far. | 2010/09/30 | [
"https://Stackoverflow.com/questions/3829211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455928/"
] | What I did to get around this problem was to add this
> [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
to my appDelegate in the persistentStoreCoordinator before adding the persistent store. This deletes the existing store that no longer is compatible with your data model. Remember to comment this line before you run the application the next time if you want to keep what is stored.
My implementation of the persistentStoreCoordinator looks like this when I have to remove an old store.
```
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSError *error = nil;
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyPinballScore.sqlite"]];
//The following line removes your current store so that you can create a new one that is compatible with your new model
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
```
} | The answer is a bit tricky but this always works for me. This is for a **clean** installation of a new compatible .sqlite file, **not a migration**!
launch simulator, delete the app and the data (the popup after you delete the app).
quit simulator
open X-Code, after making any edits to your data model
delete the `{*appname*}.sqlite` file (or back it up, remove it from project folder, and delete reference)
clean the app (`Product > Clean`)
Run the app in a simulator (for this tutorial I will assume 4.2)
While the simulator is running, in a Finder window, navigate to:
`{*home*} > Library > Application Support > iPhone Simulator > 4.2 > Applications > {*random identifier*} > Documents > {*appname*}.sqlite`
**Copy** this file to another location
Stop running your app in X-Code
Drag and drop the {*appname*}.sqlite file into the files list in X-Code.
In the dialog that pops up, make sure the `copy to folder` checkbox, is checked.
`Product > Clean`
Then run the app in the simulator again
Now you should have a working sqlite file!
Cheers,
Robert | 2 | 0 |
11,678,794 | I have problem with dll file and have project which need this file System.Windows.Controls.dll for
```
listBox1.ItemsSource
```
error fix , and add reference with this dll to fix error.
Where i can find this dll file?
Is there any download link ? Share please !
Thanks !
In "Add Reference" it doesn't exist !
Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> | 2012/07/26 | [
"https://Stackoverflow.com/questions/11678794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539124/"
] | Here are the steps:
1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE)
2. Select `Add Reference`
3. In the window that opens, Select `Assemblies > Framework`
4. Check the `PresentationFramework` component box and click ok | This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace.
<http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx>
You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL | 5 | 3 |
11,678,794 | I have problem with dll file and have project which need this file System.Windows.Controls.dll for
```
listBox1.ItemsSource
```
error fix , and add reference with this dll to fix error.
Where i can find this dll file?
Is there any download link ? Share please !
Thanks !
In "Add Reference" it doesn't exist !
Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> | 2012/07/26 | [
"https://Stackoverflow.com/questions/11678794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539124/"
] | This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace.
<http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx>
You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL | I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll"
Hope this helps! | 3 | 0 |
11,678,794 | I have problem with dll file and have project which need this file System.Windows.Controls.dll for
```
listBox1.ItemsSource
```
error fix , and add reference with this dll to fix error.
Where i can find this dll file?
Is there any download link ? Share please !
Thanks !
In "Add Reference" it doesn't exist !
Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> | 2012/07/26 | [
"https://Stackoverflow.com/questions/11678794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539124/"
] | Here are the steps:
1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE)
2. Select `Add Reference`
3. In the window that opens, Select `Assemblies > Framework`
4. Check the `PresentationFramework` component box and click ok | I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll"
Hope this helps! | 5 | 0 |
9,525,464 | So I am figuring out how to set up some options for a class. 'options' is a hash. I want to
1) filter out options I don't want or need
2) set some instance variables to use elsewhere
3) and set up another hash with the processed options as @current\_options.
```
def initialize_options(options)
@whitelisted_options, @current_options = [:timestamps_offset, :destructive, :minimal_author], {}
n_options = options.select { |k,v| @whitelisted_options.include?(k) }
@current_options[:timestamps_offset] = @timestamp_offset = n_options.fetch(:timestamps_offset, 0)*(60*60*24)
@current_options[:destructive] = @destructive = n_options.fetch(:destructive, false)
@current_options[:minimal_author] = @minimal_author = n_options.fetch(:minimal_author, false)
end
```
I'm guessing this is a bit much, no matter what I pass in I get:
```
{:timestamps_offset=>0, :destructive=>false, :minimal_author=>false}
```
When I do this line by line from the command line, it works as I want it to but not in my class. So what is going on and how do I clean this up?
EDIT: this actually works disembodied from the class I'm using it in, but inside it doesn't so the reality is something is going on I'm not aware of right now.
attr\_reader :current\_options is how this is set on the class, perhaps that needs some revision.
EDIT2: line 2 of the method is supposed to select from @whitelisted\_options
EDIT3: Actually turned out to be something I wasn't thinking of..."options" comes in parsed from a yaml file as strings....and I was fetching symbols, changing that around makes a difference where before the method was looking for symbols and finding none, e.g. "destructive" vs :destructive, so always defaulting to the defaults. In short, I just needed to symbolize the hash keys when options are imported. | 2012/03/01 | [
"https://Stackoverflow.com/questions/9525464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697364/"
] | Your `@current_options` is initialized as an empty hash. When you filter the `options` passed as params, none of the keys will be present in `@current_options` so `n_options` will end up empty.
Then when you set up `@current_options` in the following lines, it will always grab the default values `(0, false, false)`, and that's why your output's always the same.
You solve this problem by conditionally initializing @current\_options so that it's only set to `{}` once:
@current\_options ||= {}
**Post-OP edit:**
Your issue's with `options.select` -- in Ruby 1.8, it doesn't return a Hash, but rather an Array. Your calls to `fetch` are then always failing (as symbols can't be array indexes), so always returning defaults.
Instead, try:
```
n_options = options.inject({}) {|h, p| h[p[0]] = p[1] if @whitelisted_options.include? p[0]; h }
```
where `p` is an array containing each key/value pair.
In Ruby 1.9.2, `Hash.select` behaves the way you expected it to.
**Edit 2: Here's how I'd approach it:**
```
class Foo
@@whitelisted_options= {:timestamps_offset => 0, :destructive => false, :minimal_author =>false}
@@whitelisted_options.keys.each do |option|
define_method(option) { return @current_options[option] rescue nil}
end
def initialize_options(options)
@current_options = {}
@@whitelisted_options.each {|k, v| @current_options[k] = options[k] || v}
@current_options
end
end
```
In use:
```
f = Foo.new
f.destructive #=> nil
f.initialize_options(:minimal_author => true, :ignore => :lol)
f.destructive #=> false
f.minimal_author #=> true
f.timestamps_offset #=> 0
``` | 1. What is `@whitelisted_options` for?
2. What do you want to happen if `:destructive` is not a key in `options`? Do you want to have `:destructive => false`, or do you want `@current_options` to not mention `:destructive` at all? | 2 | 0 |