qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
58,186,365 | I have a problem sending json data to a controller with ajax.
I think I sent the data well but I get the following warn.
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'bno' is not present]
```
code:400
message:HTTP Status 400 – Bad Requesth1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}HTTP Status 400 – Bad Request
=============================
**Type** Status Report
**Message** Required int parameter 'bno' is not present
**Description** The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
### Apache Tomcat/8.5.34
```
I'll show my ajax code
```
var headers = {"Content-Type" : "application/json"
,"X-HTTP-Method-Override" : "DELETE"
};
$.ajax({
url: root+"/restcmt/"+uid+"/"+cno
, headers: headers
, type: 'DELETE'
, data : JSON.stringify({"bno":bno})
, beforeSend : function(xhr){
xhr.setRequestHeader(_csrf_name, _csrf_token);
}
, success: function(result){
showcmtlist(bno);
}
, error: function(request,status,error){
console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
});
```
And my controller
```
@RequestMapping(value="/{uid}/{cno}", method=RequestMethod.DELETE)
public void deletecmt(@PathVariable int cno ,@PathVariable String uid,@RequestParam int bno
,@AuthenticationPrincipal SecurityCustomUser securityCustomUser) throws Exception{
}
```
and request payload
```
{"bno":14}
```
I'm not sure what's wrong.
What's wrong? | 2019/10/01 | [
"https://Stackoverflow.com/questions/58186365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10665710/"
] | `{"bno": bno}` is in the body of the request. So your Controller method should be `@RequestBody int bno`. `@RequestParam` is for servlet request parameters. i.e: `/uid/cno?bno=14`
difference for reference: [What is difference between @RequestBody and @RequestParam?](https://stackoverflow.com/questions/28039709/what-is-difference-between-requestbody-and-requestparam) | In the Spring-World request payload should correspond to @RequestBody, e.x:
```
public SomethingElse updateValue(@RequestBody Something value) {
// ...
}
```
Where "Something" is any POJO.
In order to use @RequestParam, see:
<https://github.com/jquery/jquery/issues/3269>
($.ajax Sends `data` property in DELETE body instead of query string) |
45,384,608 | I have searched again and again but nothing seems to be solving my problem. When
```
mail = imaplib.IMAP4_SSL("imap.google.com")
```
is declared it throws a syntax error, but tells me absolutely nothing but that it is incorrect. Does anyone know what is going on here or knows how to fix it? Feel free to ask for more details if needed. I am using SMTP port 143.
Code snippet:
```
from subprocess import Popen
import smtplib
import time
import imaplib
import email
import threading
ORG_EMAIL = "@gmail.com"
FROM_EMAIL = "magikboy01" + ORG_EMAIL
FROM_PWD = "********"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT = 143
def read_email_from_gmail():
threading.Timer(300, read_email_from_gmail().start()
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login( FROM_EMAIL, FROM_PWD )
mail.select( 'inbox' )
``` | 2017/07/29 | [
"https://Stackoverflow.com/questions/45384608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6873202/"
] | Numpy does not seem to allow fractional powers of negative numbers, even if the power would not result in a complex number. (I actually had this same problem earlier today, unrelatedly). One workaround is to use
```
np.sign(a) * (np.abs(a)) ** (1 / 3)
``` | change the dtype to complex numbers
```
a = np.array(-1, dtype=np.complex)
```
The problem arises when you are working with roots of negative numbers. |
2,757,655 | **The Question:**
Find all primes $p$ such that $\phi(x)=x^{13}$ is a homomorphism $\Bbb Z/p\Bbb Z \rightarrow \Bbb Z/p\Bbb Z$
---
**My Thoughts:**
So from what I understand
\begin{align}
\ & \phi:\Bbb Z/p\Bbb Z \rightarrow \Bbb Z/p\Bbb Z \quad\text{is a homomorphism} \\
\ \iff & \phi(xy) \equiv \phi(x)\phi(y) \pmod p \quad \forall \; x,y\\
\ \iff & (xy)^{13}\equiv x^{13}y^{13} \pmod p\quad \forall \; x,y
\end{align}
But isn't $(xy)^{13}\equiv x^{13}y^{13} \pmod p\quad \forall \; x,y$ always true, regardless of $p$?
Or is there something I am not understanding? | 2018/04/28 | [
"https://math.stackexchange.com/questions/2757655",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/520107/"
] | I believe the OP's various comments are all correct. Therefore I cannot claim any credit for this answer, but I'm just writing it out more fully for the record, so that others can scrutinize it better.
**Necessity:** 8 queries are not enough for a win, because: an adversary can answer "1" to any 8 queries, and still have multiple solutions available where no location is guaranteed to have a real ring.
Let $Q\_j$ denote the number of real rings in the range $\{j, j+1, j+2, j+3, j+4\}.$ (Obviously all indexing are mod $11$.) After 8 queries, let $Q\_a, Q\_b, Q\_c$ be the 3 queries *not* asked, where $a,b,c$ are all distinct.
After answering "1" to the 8 queries, the answers so far are consistent with these 3 scenarios:
* $Q\_a = 0, Q\_b=Q\_c=1,$ the real rings are at locations $R\_a = \{a-1, a+5\}$.
* $Q\_b = 0, Q\_a=Q\_c=1,$ the real rings are at locations $R\_b = \{b-1, b+5\}$.
* $Q\_c = 0, Q\_b=Q\_a=1,$ the real rings are at locations $R\_c = \{c-1, c+5\}$.
The crucial observation is that $R\_a \cap R\_b \cap R\_c = \emptyset.$ (Suppose on the contrary there is a common element, e.g. $x=a-1 = b+5 = c-1$, but this is impossible because $a\neq c$. Any "assignment" of the common $x$ to the $2^3$ choices result in a similar contradition.)
Because $R\_a \cap R\_b \cap R\_c = \emptyset$, there is no location guaranteed to be a real ring. (To be even more explicit: any guessed location $x$ would satisfy $x \notin R\_e$ for some $e \in \{a,b,c\}$, i.e. the adversary can claim $x$ is a fake ring by claiming that the real rings are at $R\_e$.)
This proves that 8 queries are not enough for a win.
**Sufficiency:** Meanwhile, with a 9th query, we have only two unasked queries $Q\_a, Q\_b$ and, as the OP also pointed out, if we make sure $a+6=b$ (e.g. the unasked queries are $Q\_1, Q\_7$), then $a+5 \in R\_a$ and $a+5 = b-1 \in R\_b$ so that must be a real ring.
Therefore the optimal answer is 9. | Let $r\_1, ..., r\_{11}$ be all different 11 rings, ordered by indices. There are 2 rings $r\_i$ and $r\_j$, with $i\neq j\in\{1,...,11\}$, that are real and the rest is fake. Select 5 consecutive rings. Now there are 3 cases.
**Case 1**
Suppose that we've picked 5 fake rings. This implies that the other 6 rings must contain the real rings. Again, pick 5 rings from the other 6 we did not already ask. Note that there must be at least 1 real ring in this new collection of rings. Now we have 2 subcases:
**Subcase 1.1** If we now know that there must be 1 real ring in our last selection, we immediately know that the 1 ring we didn't choose must be a real one and we're done in 2 steps.
**Subcase 1.2** If there were 2 real rings in our last selection,then we must apply a 'smart' algorithm. Say we now have $r\_3, ..., r\_7$ as our selection containing 2 real rings. Let's pick $r\_4, ..., r\_8$ and assume the worst case scenario: still 2 real rings ($r\_3$ was fake). Then we take $r\_5, ..., r\_9$ and again assume worst case. Persume with $r\_6, ..., r\_{10}$ and now you know either $r\_5$ is a real ring or both $r\_6$ and $r\_7$ are real rings, it depends on the answer (what answers?).
Case 1 took us **5 steps**.
**Case 2** We have picked a sequence containing 2 rings. Apply the algorithm from case 1.2.
Case 2 took us **3 steps**.
**Case 3** There's only 1 real ring. Apply case 1.2's algorithm. It takes at most 5 steps from now to find a real ring. Since we're looking for the worst case scenarios to determine the minimal steps it takes us to know with 100% certainty where at least 1 real ring is positioned, we apply this algorithm. Of course, we can produce a smarter algorithm for which the chance of picking a ring-sequence is bigger. But for now, we assume that we want to know the minimal amount of steps for finding a real ring in **every** case. Worst cases included. The very worst case is when $r\_1$ and $r\_6$ are real rings. If we chose rings $r\_1, ..., r\_5$ and thereafter rings $r\_2, ..., r\_6$, then we still got 1 real ring. Then continue the algorithm and it will take 6 steps in total to have found that ring. Case 3 took us **6 steps**.
We conclude that the minimal steps necessary for finding a real ring (when every possible case is considered) is **6**.
**Special case** It may happen to be 2 steps (to find a real ring) in the best case: select $r\_1, ..., r\_5$ and it contains 1 ring. Now select $r\_6, ..., r\_{10}$ and it contains no ring $\rightarrow r\_{11}$ is a real ring. |
18,353,624 | I am playing video in Qt using opencv. I am having 6 tiled view cameras from which I am playing video. The problem is if one of the videos is not playing i.e finishes then the GUI freezes and exits. The error I get is you must reimplement QApplication::notify() and catch the exceptions there. How to do this?
The code I am using is as follows.
Somewhere in a function
```
void MainWindow::ActivateWindow()
{
//Some part of code to set Index for stacked widget
if(stackWidget->currentIndex()==9)
{
const int imagePeriod == 1000/25;
imageTimer->setInterval(imagePeriod);
connect(imageTimer,SIGNAL(timeout()),this,SLOT(demoSlot());
imageTimer->start();
}
}
```
In slot demoSlot
```
void MainWindow::demoSlot()
{
captureCamera1 cvCaptureFromFile("/root/mp.mp4");
captureCamera2 cvCaptureFromFile("/root/mp.mp4");
captureCamera3 cvCaptureFromFile("/root/mp.mp4");
while(imageTimer->isActive())
{
frameCamera1 = cvQueryFrame(captureCamera1);
frameCamera2 = cvQueryFrame(captureCamera2);
frameCamera3 = cvQueryFrame(captureCamera2);
sourceImageCam1 = frameCamera1;
sourceImageCam2 = frameCamera2;
sourceImageCam3 = frameCamera3;
cv::resize(sourceImageCam1,sourceImageCam1,cv::size(400,100),0,0);
cv::resize(sourceImageCam1,sourceImageCam1,cv::size(400,100),0,0);
cv::resize(sourceImageCam1,sourceImageCam1,cv::size(400,100),0,0);
cv::cvtColor(sourceImageCam1,sourceImageCam2,CV_BGR2RGB);
cv::cvtColor(sourceImageCam2,sourceImageCam2,CV_BGR2RGB);
cv::cvtColor(sourceImageCam2,sourceImageCam2,CV_BGR2RGB);
QImage tempImage1 = QImage((const unsigned char* sourceImageCam1.data,sourceImageCam1.cols,sourceImageCam2.rows,QImage::Format_RG888);
QImage tempImage2 = QImage((const unsigned char* sourceImageCam2.data,sourceImageCam2.cols,sourceImageCam2.rows,QImage::Format_RG888);
QImage tempImage3 = QImage((const unsigned char* sourceImageCam3.data,sourceImageCam3.cols,sourceImageCam3.rows,QImage::Format_RG888);
labelCameraCapture1->setPixmap(QPixmap::fromImage(tempImage1)); //label to display video
labelCameraCapture2->setPixmap(QPixmap::fromImage(tempImage2));
labelCameraCapture3->setPixmap(QPixmap::fromImage(tempImage3));
lblCameraCapture1->resize(lblCameraCapture1->Pixmap->size());
lblCameraCapture1->resize(lblCameraCapture1->Pixmap->size());
lblCameraCapture1->resize(lblCameraCapture1->Pixmap->size());
cvWaitkey(20);
qApp->processEvents();
}
if(imageTimer->isActive())
{
imageTimer->stop();
}
else
{
imageTimer->start();
}
}
```
In header file
```
cvCapture *captureCamera1;
cvCapture *captureCamera1;
cvCapture *captureCamera1;
IplImage frameCamera1;
IplImage frameCamera2;
IplImage frameCamera3;
cv::Mat sourceImageCam1;
cv::Mat sourceImageCam2;
cv::Mat sourceImageCam3;
``` | 2013/08/21 | [
"https://Stackoverflow.com/questions/18353624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548968/"
] | This will do the trick changing that to 3 movies is simple.
```
class MainWindow : public QMainWindow {
Q_OBJECT
explicit QMainWindow(QWidget *parent) ....
// prepare timer and so on
public slots:
void startVideo() {
vid1.close();
vid1.open("/root/mp.mp4");
imageTimer->start();
}
void demoSlot() {
cv::Mat frame;
vid1 >> frame;
cv::cvtColor(frame,frame,CV_BGR2RGB);
QImage img((uchar*) frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
label1->setPixmap(QPixmap::fromImage(img));
}
private:
...
QTimer *imageTimer;
cv::VideoCapture vid1;
};
``` | Check if frame captured from camera is NULL. Then simply skip processing steps for this camera.
And it'll be better to not mix C++ and C interfaces (I mean cv::Mat and IplImage). |
49,585,780 | It's possibile with security file config to redirect user already logged in to specific route (e.g homepage) if they try to access on login/register pages? One solution that I already found is to attach a listener to EventRequest, but I prefer to use security config if it's possible. | 2018/03/31 | [
"https://Stackoverflow.com/questions/49585780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7334516/"
] | After some googling I noticed that another solution is to override the fosuserbundle controllers. But because I need that this behavior should works also for /register and /resetting pages, instead to override also those controller, I preferred to use EventListener. Maybe this's the best solution in this case. I'm using Symfony 4, so for the other versions could be different.
My code:
```
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class LoggedInUserListener
{
private $router;
private $authChecker;
public function __construct(RouterInterface $router, AuthorizationCheckerInterface $authChecker)
{
$this->router = $router;
$this->authChecker = $authChecker;
}
/**
* Redirect user to homepage if tryes to access in anonymously path
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$path = $request->getPathInfo();
if ($this->authChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') && $this->isAnonymouslyPath($path)) {
$response = new RedirectResponse($this->router->generate('homepage'));
$event->setResponse($response);
}
}
/**
* Check if $path is an anonymously path
* @param string $path
* @return bool
*/
private function isAnonymouslyPath(string $path): bool
{
return preg_match('/\/login|\/register|\/resetting/', $path) ? true : false;
}
}
```
add this to services.yaml:
```
App\EventListener\LoggedInUserListener:
tags:
- { name: kernel.event_listener, event: kernel.request }
``` | @Mintendo, I have errors using your code:
```
request.CRITICAL: Exception thrown when handling an exception (Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: The token storage contains no authentication token.
php.CRITICAL: Uncaught Exception: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
```
Besides that debug bar also showed error and was broken.
But you pushed me in the right direction, so I have modified your code a little.
And it works without errors now:
```
<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
class LoggedInUserListener
{
private $router;
private $security;
public function __construct(RouterInterface $router, Security $security)
{
$this->router = $router;
$this->security = $security;
}
/**
* Redirect user to homepage if tries to access in anonymously path
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$path = $request->getPathInfo();
if ($this->security->getUser() && $this->isAnonymouslyPath($path)) {
$response = new RedirectResponse($this->router->generate('dashboard'));
$event->setResponse($response);
}
}
/**
* Check if $path is an anonymously path
* @param string $path
* @return bool
*/
private function isAnonymouslyPath(string $path): bool
{
return preg_match('/\/login|\/register|\/resetting/', $path) ? true : false;
}
}
``` |
7,711,957 | I have two activities, one is a list for item, the other one is the edit view for the item. When user clicks the item in the first view, the second edit view will show.
In android the stack based mechanism, if I do this the behavior is weird.
List view -> click -> edit view -> save -> list view -> click -> edit ->... it's a loop.
If I edit and save the item several times the stack will be full of list view & edit view...
Now the user wants to press back key to exit the program, by stack based activity manager, the user will meet up many times of the two activities.
What's the recommend way to resolve this issue? | 2011/10/10 | [
"https://Stackoverflow.com/questions/7711957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197036/"
] | Pardon me if I'm wrong but I think you handle the Edit->List switching with a startActivity().
I think you should just `finish()` your activity when you handle save (letting activity stack go back to List) | For your any one of the activity as per your requirement set the following attribute in your project manifest file
```
android:noHistory="true"
```
so that activity will not be kept on stack and chain will break. |
7,711,957 | I have two activities, one is a list for item, the other one is the edit view for the item. When user clicks the item in the first view, the second edit view will show.
In android the stack based mechanism, if I do this the behavior is weird.
List view -> click -> edit view -> save -> list view -> click -> edit ->... it's a loop.
If I edit and save the item several times the stack will be full of list view & edit view...
Now the user wants to press back key to exit the program, by stack based activity manager, the user will meet up many times of the two activities.
What's the recommend way to resolve this issue? | 2011/10/10 | [
"https://Stackoverflow.com/questions/7711957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197036/"
] | For your any one of the activity as per your requirement set the following attribute in your project manifest file
```
android:noHistory="true"
```
so that activity will not be kept on stack and chain will break. | You Can also write this code for back to activity
if you want to move back five stack back then put this line code
```
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
``` |
7,711,957 | I have two activities, one is a list for item, the other one is the edit view for the item. When user clicks the item in the first view, the second edit view will show.
In android the stack based mechanism, if I do this the behavior is weird.
List view -> click -> edit view -> save -> list view -> click -> edit ->... it's a loop.
If I edit and save the item several times the stack will be full of list view & edit view...
Now the user wants to press back key to exit the program, by stack based activity manager, the user will meet up many times of the two activities.
What's the recommend way to resolve this issue? | 2011/10/10 | [
"https://Stackoverflow.com/questions/7711957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197036/"
] | Pardon me if I'm wrong but I think you handle the Edit->List switching with a startActivity().
I think you should just `finish()` your activity when you handle save (letting activity stack go back to List) | From ListView actiivty call EditView activity by `startActivityForResult()` . and after save the EditView just `finish()` the EditView activity.
and in Manifest file just put `android:noHistory="true"`.
EDIT:
```
android:noHistory
```
Whether or not the activity should be removed from the activity stack and finished
(its finish() method called) when the user navigates away from it and it's no longer
visible on screen — "true" if it should be finished, and "false" if not. The default
value is "false".
A value of "true" means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it.
```
This attribute was introduced in API Level 3.
``` |
7,711,957 | I have two activities, one is a list for item, the other one is the edit view for the item. When user clicks the item in the first view, the second edit view will show.
In android the stack based mechanism, if I do this the behavior is weird.
List view -> click -> edit view -> save -> list view -> click -> edit ->... it's a loop.
If I edit and save the item several times the stack will be full of list view & edit view...
Now the user wants to press back key to exit the program, by stack based activity manager, the user will meet up many times of the two activities.
What's the recommend way to resolve this issue? | 2011/10/10 | [
"https://Stackoverflow.com/questions/7711957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197036/"
] | From ListView actiivty call EditView activity by `startActivityForResult()` . and after save the EditView just `finish()` the EditView activity.
and in Manifest file just put `android:noHistory="true"`.
EDIT:
```
android:noHistory
```
Whether or not the activity should be removed from the activity stack and finished
(its finish() method called) when the user navigates away from it and it's no longer
visible on screen — "true" if it should be finished, and "false" if not. The default
value is "false".
A value of "true" means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it.
```
This attribute was introduced in API Level 3.
``` | You Can also write this code for back to activity
if you want to move back five stack back then put this line code
```
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
``` |
7,711,957 | I have two activities, one is a list for item, the other one is the edit view for the item. When user clicks the item in the first view, the second edit view will show.
In android the stack based mechanism, if I do this the behavior is weird.
List view -> click -> edit view -> save -> list view -> click -> edit ->... it's a loop.
If I edit and save the item several times the stack will be full of list view & edit view...
Now the user wants to press back key to exit the program, by stack based activity manager, the user will meet up many times of the two activities.
What's the recommend way to resolve this issue? | 2011/10/10 | [
"https://Stackoverflow.com/questions/7711957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197036/"
] | Pardon me if I'm wrong but I think you handle the Edit->List switching with a startActivity().
I think you should just `finish()` your activity when you handle save (letting activity stack go back to List) | You Can also write this code for back to activity
if you want to move back five stack back then put this line code
```
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
moveTaskToBack(true);
``` |
52,073,059 | I have this problem with actions of AlertDialog
```
AlertDialog(
title: ...,
content: ...,
actions: <Widget>[
FlatButton(onPressed: ...,
child: Text(btn_download)),
FlatButton(onPressed: ...,
child: Text('btn_select')),
FlatButton(onPressed: ...,
child: Text(btn_qr)),
FlatButton(onPressed: ...,
child: Text(btn_cancel)),
],
);
```
When I show this dialog I get this:
[](https://i.stack.imgur.com/LyU9C.png)
I tried to use Wrap or other scrolling and multi-child widets, but nothing helps.
Found the same issue [here](https://github.com/flutter/flutter/issues/18448), but no answer yet
Does anybody knows how this can be fixed? | 2018/08/29 | [
"https://Stackoverflow.com/questions/52073059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7130820/"
] | I don't have access to AndroidStudio to validate my hypothesis, but I'd try something like this:
```
AlertDialog(
title: ...,
content: ...,
actions: <Widget>[
new Container (
child: new Column (
children: <Widget>[
FlatButton(onPressed: ...,
child: Text(btn_download)),
FlatButton(onPressed: ...,
child: Text('btn_select'))
),
new Container (
child: new Column (
children: <Widget>[
FlatButton(onPressed: ...,
child: Text(btn_gr)),
FlatButton(onPressed: ...,
child: Text('btn_cancel'))
),
),
],
);
```
**Edit**: this code *works*, but you have to use a width-constrained `Container`, even though it seems that a 75% screen width is somewhat of a sweet spot, since it works both in portrait and landscape mode.
```
import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<Null> _neverSatisfied() async {
double c_width = MediaQuery.of(context).size.width*0.75;
return showDialog<Null>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return new AlertDialog(
title: new Text('Rewind and remember'),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new Text('You will never be satisfied.'),
new Text('You\’re like me. I’m never satisfied.'),
],
),
),
actions: <Widget>[
new Container(
width: c_width,
child: new Wrap(
spacing: 4.0,
runSpacing: 4.0,
children: <Widget>[
new FlatButton(
child: new Text('The Lamb'),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('Lies Down'),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('On'),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('Broadway'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
)
)
],
);
},
);
}
void _doNeverSatisfied() {
_neverSatisfied()
.then( (Null) {
print("Satisfied, at last. ");
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _doNeverSatisfied,
tooltip: 'Call dialog',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
``` | The `ButtonBar` is not made for so many buttons.
Place your buttons in a `Wrap` widget or a `Column`. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | When you are navigating *forward*, can you set **NavigationCacheMode** to **Disabled** before you call **Frame.Navigate**? Then, in **OnNavigatedTo()** set **NavigationCacheMode** back to **Enabled** again.
That should make it so that when you navigate forward, caching is disabled. But when you arrive on the new page instance, **OnNavigatedTo** would enable it again. When you want to navigate back, you wouldn't touch the **NavigationCacheMode** before calling **Frame.GoBack**. That should give you the cached instance, I think.
I believe this would work but I haven't tested it. I'd be curious to know if it does. Interesting scenario there. I'd love to see the app in action and better understand the use of this behavior. | You use the NavigationCacheMode property to specify whether a new instance of the page is created for each visit to the page or if a previously constructed instance of the page that has been saved in the cache is used for each visit.
The default value for the NavigationCacheMode property is Disabled. Set the NavigationCacheMode property to Enabled or Required when a new instance of the page is not essential for each visit. By using a cached instance of the page, you can improve the performance of your application and reduce the load on your server.
Setting NavigationCacheMode to Required means that the page is cached regardless of the number of cached pages specified in the CacheSize property. Pages marked as Required do not count against the CacheSize total. Setting NavigationCacheMode to Enabled means the page is cached, but it is eligible for disposal if the number of cached pages exceeds the value of CacheSize.
Set the NavigationCacheMode property to Disabled if a new instance must be created for each visit. For example, you should not cache a page that displays information that is unique to each customer.
The OnNavigatedTo method is called for each request, even when the page is retrieved from the cache. You should include in this method code that must be executed for each request rather than placing that code in the Page constructor. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | I had much the same problem. I wanted it such that when I was moving forward in Metro (Windows Store to be proper), it would create a new instance. However, when going back, it would keep the data that I wanted save.
So, I likewise used NavigationCacheMode = NavigationCacheMode.Enabled. I found that regardless of which way I was traversing, forward or backward, everything was always saved. So, I would go forward several pages, then step back a few. Hoping everything was reset as I moved forward, I invariably found that it wasn't; it had retained the data.
I tried everything, including writing my own back button code to include NavigationCacheMode = NavigationCacheMode.Disabled, but to no avail. As others have pointed out, once you have enabled it, the NavigationCacheMode simply won't disable.
I did find a solution. I went to the LayoutAwarePage.cs and simply made a minor change. Under the "OnNavigatedTo" I found the line:
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null) return;
```
However, the comment ran contrary to what I wanted. I was looking for state loading in a unidirectional pattern. If moving forward, I wanted state loading; if moving backward I wanted the behavior the comment indicated - no state loading.
So I simply modified the line.
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null && e.NavigationMode == NavigationMode.Back) return;
```
I have tested it and it works perfectly. Now, when navigating backwards it remembers the state and keeps the page the same. Navigating forward, it loads fresh.
Perhaps not best practice, but I do not call "OnNavigatedTo" from my code-behind. I do everything through the "LoadState." If you are overriding "OnNavigatedTo" in the code-behind you might see different behavior.
Thank you,
Joseph Irvine | When **NavigationCacheMode** is enabled, you can call **Dispose()** (conditionally) in **OnNavigatedFrom()** to make sure that a new instance of the page will be created the next time the application navigates to it. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The solution can be downloaded here:
<https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**Update:**
The page class now also provides the **OnNavigatingFromAsync** method to show for example an async popup and cancel navigation if required... | I achieved this by:
* Setting NavigationCacheMode to Required/Enabled for required Pages.
* On clicking on Page2 button/link:
Traverse the Frame BackStack and find out if the Page2 is in BackStack.
If Page2 is found call Frame.GoBack() required number of times.
If not found just navigate to the new Page.
This will work for any no of pages.
Code Sample:
```
public void Page2Clicked(object sender, RoutedEventArgs e)
{
int isPresent = 0;
int frameCount = 0;
//traverse BackStack in reverse order as the last element is latest page
for(int index= Frame.BackStack.Count-1; index>=0;index--)
{
frameCount += 1;
//lets say the first page name is page1 which is cached
if ("Page2".Equals(Frame.BackStack[index].SourcePageType.Name))
{
isPresent = 1;
//Go back required no of times
while (frameCount >0)
{
Frame.GoBack();
frameCount -= 1;
}
break;
}
}
if (isPresent == 0)
{
Frame.Content = null;
Frame.Navigate(typeof(Page2));
}
}
```
This will be helpful if forward/backward buttons will not be made much use of.
as this solution will affect the forward/backward navigation.
If you wish to use forward/backward navigation as well, then some additional cases has to be handled. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | You use the NavigationCacheMode property to specify whether a new instance of the page is created for each visit to the page or if a previously constructed instance of the page that has been saved in the cache is used for each visit.
The default value for the NavigationCacheMode property is Disabled. Set the NavigationCacheMode property to Enabled or Required when a new instance of the page is not essential for each visit. By using a cached instance of the page, you can improve the performance of your application and reduce the load on your server.
Setting NavigationCacheMode to Required means that the page is cached regardless of the number of cached pages specified in the CacheSize property. Pages marked as Required do not count against the CacheSize total. Setting NavigationCacheMode to Enabled means the page is cached, but it is eligible for disposal if the number of cached pages exceeds the value of CacheSize.
Set the NavigationCacheMode property to Disabled if a new instance must be created for each visit. For example, you should not cache a page that displays information that is unique to each customer.
The OnNavigatedTo method is called for each request, even when the page is retrieved from the cache. You should include in this method code that must be executed for each request rather than placing that code in the Page constructor. | When **NavigationCacheMode** is enabled, you can call **Dispose()** (conditionally) in **OnNavigatedFrom()** to make sure that a new instance of the page will be created the next time the application navigates to it. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The solution can be downloaded here:
<https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**Update:**
The page class now also provides the **OnNavigatingFromAsync** method to show for example an async popup and cancel navigation if required... | I had to derive a `page2` class from my `page` class and then when I want to navigate to a second version of the same page, I detect if the `this` object is `page` or `page2`. I then navigate to `page2` if I was in `page` and navigate to `page` if in `page2`.
The only drawback, which is a huge one, is that there is no way to derive one XAML file from another. Thus, all of the C# code is in the `page` class code-behind as expected, but there are two almost identical XAML files, one for each version of the page.
A small script could probably be added as a pre-build step to generate the second page class from the first, copying the XAML data and adjusting the class names.
It's ugly but it almost works perfectly and I never have to worry about C# code duplication or weird navigation cache issues. I just end up having duplicate XMAL code, which in my case really never changes anyhow. I also end up with two warnings about not using the `new` keyword on the automatically generated code for `page2.InitializeComponent()` and `page2.Connect()`.
Interestingly, navigating to `page` then to `page2` then to `page` doesn't cause a problem and the second instance of the `page` class is an actual second instance unrelated to the first.
Note that this solution is probably recommended against by MS. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | You use the NavigationCacheMode property to specify whether a new instance of the page is created for each visit to the page or if a previously constructed instance of the page that has been saved in the cache is used for each visit.
The default value for the NavigationCacheMode property is Disabled. Set the NavigationCacheMode property to Enabled or Required when a new instance of the page is not essential for each visit. By using a cached instance of the page, you can improve the performance of your application and reduce the load on your server.
Setting NavigationCacheMode to Required means that the page is cached regardless of the number of cached pages specified in the CacheSize property. Pages marked as Required do not count against the CacheSize total. Setting NavigationCacheMode to Enabled means the page is cached, but it is eligible for disposal if the number of cached pages exceeds the value of CacheSize.
Set the NavigationCacheMode property to Disabled if a new instance must be created for each visit. For example, you should not cache a page that displays information that is unique to each customer.
The OnNavigatedTo method is called for each request, even when the page is retrieved from the cache. You should include in this method code that must be executed for each request rather than placing that code in the Page constructor. | I achieved this by:
* Setting NavigationCacheMode to Required/Enabled for required Pages.
* On clicking on Page2 button/link:
Traverse the Frame BackStack and find out if the Page2 is in BackStack.
If Page2 is found call Frame.GoBack() required number of times.
If not found just navigate to the new Page.
This will work for any no of pages.
Code Sample:
```
public void Page2Clicked(object sender, RoutedEventArgs e)
{
int isPresent = 0;
int frameCount = 0;
//traverse BackStack in reverse order as the last element is latest page
for(int index= Frame.BackStack.Count-1; index>=0;index--)
{
frameCount += 1;
//lets say the first page name is page1 which is cached
if ("Page2".Equals(Frame.BackStack[index].SourcePageType.Name))
{
isPresent = 1;
//Go back required no of times
while (frameCount >0)
{
Frame.GoBack();
frameCount -= 1;
}
break;
}
}
if (isPresent == 0)
{
Frame.Content = null;
Frame.Navigate(typeof(Page2));
}
}
```
This will be helpful if forward/backward buttons will not be made much use of.
as this solution will affect the forward/backward navigation.
If you wish to use forward/backward navigation as well, then some additional cases has to be handled. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | I had much the same problem. I wanted it such that when I was moving forward in Metro (Windows Store to be proper), it would create a new instance. However, when going back, it would keep the data that I wanted save.
So, I likewise used NavigationCacheMode = NavigationCacheMode.Enabled. I found that regardless of which way I was traversing, forward or backward, everything was always saved. So, I would go forward several pages, then step back a few. Hoping everything was reset as I moved forward, I invariably found that it wasn't; it had retained the data.
I tried everything, including writing my own back button code to include NavigationCacheMode = NavigationCacheMode.Disabled, but to no avail. As others have pointed out, once you have enabled it, the NavigationCacheMode simply won't disable.
I did find a solution. I went to the LayoutAwarePage.cs and simply made a minor change. Under the "OnNavigatedTo" I found the line:
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null) return;
```
However, the comment ran contrary to what I wanted. I was looking for state loading in a unidirectional pattern. If moving forward, I wanted state loading; if moving backward I wanted the behavior the comment indicated - no state loading.
So I simply modified the line.
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null && e.NavigationMode == NavigationMode.Back) return;
```
I have tested it and it works perfectly. Now, when navigating backwards it remembers the state and keeps the page the same. Navigating forward, it loads fresh.
Perhaps not best practice, but I do not call "OnNavigatedTo" from my code-behind. I do everything through the "LoadState." If you are overriding "OnNavigatedTo" in the code-behind you might see different behavior.
Thank you,
Joseph Irvine | You use the NavigationCacheMode property to specify whether a new instance of the page is created for each visit to the page or if a previously constructed instance of the page that has been saved in the cache is used for each visit.
The default value for the NavigationCacheMode property is Disabled. Set the NavigationCacheMode property to Enabled or Required when a new instance of the page is not essential for each visit. By using a cached instance of the page, you can improve the performance of your application and reduce the load on your server.
Setting NavigationCacheMode to Required means that the page is cached regardless of the number of cached pages specified in the CacheSize property. Pages marked as Required do not count against the CacheSize total. Setting NavigationCacheMode to Enabled means the page is cached, but it is eligible for disposal if the number of cached pages exceeds the value of CacheSize.
Set the NavigationCacheMode property to Disabled if a new instance must be created for each visit. For example, you should not cache a page that displays information that is unique to each customer.
The OnNavigatedTo method is called for each request, even when the page is retrieved from the cache. You should include in this method code that must be executed for each request rather than placing that code in the Page constructor. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The solution can be downloaded here:
<https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**Update:**
The page class now also provides the **OnNavigatingFromAsync** method to show for example an async popup and cancel navigation if required... | When **NavigationCacheMode** is enabled, you can call **Dispose()** (conditionally) in **OnNavigatedFrom()** to make sure that a new instance of the page will be created the next time the application navigates to it. |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The solution can be downloaded here:
<https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**Update:**
The page class now also provides the **OnNavigatingFromAsync** method to show for example an async popup and cancel navigation if required... | I had much the same problem. I wanted it such that when I was moving forward in Metro (Windows Store to be proper), it would create a new instance. However, when going back, it would keep the data that I wanted save.
So, I likewise used NavigationCacheMode = NavigationCacheMode.Enabled. I found that regardless of which way I was traversing, forward or backward, everything was always saved. So, I would go forward several pages, then step back a few. Hoping everything was reset as I moved forward, I invariably found that it wasn't; it had retained the data.
I tried everything, including writing my own back button code to include NavigationCacheMode = NavigationCacheMode.Disabled, but to no avail. As others have pointed out, once you have enabled it, the NavigationCacheMode simply won't disable.
I did find a solution. I went to the LayoutAwarePage.cs and simply made a minor change. Under the "OnNavigatedTo" I found the line:
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null) return;
```
However, the comment ran contrary to what I wanted. I was looking for state loading in a unidirectional pattern. If moving forward, I wanted state loading; if moving backward I wanted the behavior the comment indicated - no state loading.
So I simply modified the line.
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null && e.NavigationMode == NavigationMode.Back) return;
```
I have tested it and it works perfectly. Now, when navigating backwards it remembers the state and keeps the page the same. Navigating forward, it loads fresh.
Perhaps not best practice, but I do not call "OnNavigatedTo" from my code-behind. I do everything through the "LoadState." If you are overriding "OnNavigatedTo" in the code-behind you might see different behavior.
Thank you,
Joseph Irvine |
11,539,755 | I'm trying to create an UWP (Universal Windows App) application with C#. My problem is the `Frame` control: If I use it without `NavigationCacheMode = Required`, every time the user goes back, the page is not kept in memory and will be recreated. If I set `NavigationCacheMode` to `Required` or `Enabled`, going back works correctly (no new page object) **but** if I navigate to another page from the same type, the previous page object is recycled and reused (no new page instance).
**Desired behavior:**
Is there a way to have the following behaviour with the original `Frame` control (like in Windows Phone):
1. Create new page instance on `Navigate()`
2. Keep the page instance on `GoBack()`
The only solution I know is to create an own `Frame` control but this leads to other problems (e.g.: missing `SetNavigationState()` method, etc...)
**Sample scenario:**
Simple application example with three pages: `TvShowListPage`, `TvShowDetailsPage`, `SeasonDetailsPage`.
1. `TvShowListPage` is the entry page. After clicking on a `TvShow` navigate to `TvShowDetailsPage`.
2. Now in `TvShowDetailsPage` select a season in the list and navigate to the `TvShowDetailsPage`.
3. If navigating back, the pages should stay in memory to avoid reloading the pages.
4. But if the users goes back to `TvShowListPage` and selects another `TvShow` the `TvShowDetailsPage` gets recycled and is maybe in the wrong state (eg showing the cast pivot instead of the first, seasons pivot)
I'm looking for the default Windows Phone 7 behavior: Navigating creates a new page on the page stack, going back removes the top page from the stack and displays the previous page from the stack (stored in the memory).
**Solution:**
Because there was no solution to this problem, I had to reimplement all paging relevant classes: Page, Frame, SuspensionManager, etc...
The **library MyToolkit** which provides all these classes can be downloaded here: <https://github.com/MyToolkit/MyToolkit/wiki/Paging-Overview>
**References:**
* <http://www.jayway.com/2012/05/25/clearing-the-windows-8-page-cache/>: No good solution
* <http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/88e6d1b3-1fa6-4ab4-a816-e77c86ef236f/>: Implementing of an own Frame class is no solution as it doesn't work with `SuspensionManager` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11539755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876814/"
] | I had much the same problem. I wanted it such that when I was moving forward in Metro (Windows Store to be proper), it would create a new instance. However, when going back, it would keep the data that I wanted save.
So, I likewise used NavigationCacheMode = NavigationCacheMode.Enabled. I found that regardless of which way I was traversing, forward or backward, everything was always saved. So, I would go forward several pages, then step back a few. Hoping everything was reset as I moved forward, I invariably found that it wasn't; it had retained the data.
I tried everything, including writing my own back button code to include NavigationCacheMode = NavigationCacheMode.Disabled, but to no avail. As others have pointed out, once you have enabled it, the NavigationCacheMode simply won't disable.
I did find a solution. I went to the LayoutAwarePage.cs and simply made a minor change. Under the "OnNavigatedTo" I found the line:
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null) return;
```
However, the comment ran contrary to what I wanted. I was looking for state loading in a unidirectional pattern. If moving forward, I wanted state loading; if moving backward I wanted the behavior the comment indicated - no state loading.
So I simply modified the line.
```
// Returning to a cached page through navigation shouldn't trigger state loading
if (this._pageKey != null && e.NavigationMode == NavigationMode.Back) return;
```
I have tested it and it works perfectly. Now, when navigating backwards it remembers the state and keeps the page the same. Navigating forward, it loads fresh.
Perhaps not best practice, but I do not call "OnNavigatedTo" from my code-behind. I do everything through the "LoadState." If you are overriding "OnNavigatedTo" in the code-behind you might see different behavior.
Thank you,
Joseph Irvine | I had to derive a `page2` class from my `page` class and then when I want to navigate to a second version of the same page, I detect if the `this` object is `page` or `page2`. I then navigate to `page2` if I was in `page` and navigate to `page` if in `page2`.
The only drawback, which is a huge one, is that there is no way to derive one XAML file from another. Thus, all of the C# code is in the `page` class code-behind as expected, but there are two almost identical XAML files, one for each version of the page.
A small script could probably be added as a pre-build step to generate the second page class from the first, copying the XAML data and adjusting the class names.
It's ugly but it almost works perfectly and I never have to worry about C# code duplication or weird navigation cache issues. I just end up having duplicate XMAL code, which in my case really never changes anyhow. I also end up with two warnings about not using the `new` keyword on the automatically generated code for `page2.InitializeComponent()` and `page2.Connect()`.
Interestingly, navigating to `page` then to `page2` then to `page` doesn't cause a problem and the second instance of the `page` class is an actual second instance unrelated to the first.
Note that this solution is probably recommended against by MS. |
11,086,112 | I'm pretty new to Regex and I'm just trying to get my head around it. The string I am trying to search through is this:
```
100 ON 12C 12,41C High Cool OK 0
101 OFF 32C 04,93C Low Dry OK 1
102 ON 07C 08,27C High Dry OK 0
```
What I am trying to do is work out the part to find the part `32C` from the string. If possible, would the code be able to be changed a little each time in order to find the Nth occurrence of the word in the String. If it makes any difference I am going to be using this code in an iPhone application and thus Objective-C. | 2012/06/18 | [
"https://Stackoverflow.com/questions/11086112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1392240/"
] | Your example is line-oriented and of equal weight (at the same time) biased towards the beginning of the line in the string.
If your engine flavor does grouping, you should be able to specify an occurance quantifier that will get you a single exact answer, without the need to do arrays and such.
In both cases the answer is in capture buffer 1.
examples:
```
$occurance = "2";
---------
/(?:[^\n]*?(\d+C)[^\n]*.*?){$occurance}/s
---------
or
---------
/(?:^.*?(\d+C)[\S\s]*?){$occurance}/m
```
expanded:
```
/
(?:
[^\n]*?
( \d+C )
[^\n]* .*?
){2}
/xs
/
(?:
^ .*?
( \d+C )
[\S\s]*?
){2}
/xm
``` | You could try something like the following. You will have to replace regex\_pattern with your regular expression pattern. In your case, regex\_pattern should be something like `@"\\s\\d\\dC"` (a whitespace character (`\\s`) followed by a digit (`\\d`) followed by a digit (`\\d`) followed an upper-case letter `C`.
You may also wish to remove the `NSRegularExpressionCaseInsensitive` option if you can be sure that the letter C will never be lower case.
```
NSError *error = nil;
NSString *regex_pattern = @"\\s\\d\\dC";
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:regex_pattern
options:(NSRegularExpressionCaseInsensitive |
NSRegularExpressionDotMatchesLineSeparators)
error:&error];
NSArray *arrayOfMatches = [regex matchesInString:myString
options:0
range:NSMakeRange(0, [myString length])];
// arrayOfMatches now contains an array of NSRanges;
// now, find and extract the 2nd match as an integer:
if ([arrayOfMatches count] >= 2) // be sure that there are at least 2 elements in the array
{
NSRange rangeOfSecondMatch = [arrayOfMatches objectAtIndex:1]; // remember that the array indices start at 0, not 1
NSString *secondMatchAsString = [myString substringWithRange:
NSMakeRange(rangeOfSecondMatch.location + 1, // + 1 to skip over the initial space
rangeOfSecondMatch.length - 2)] // - 2 because we ignore both the initial space and the final "C"
NSLog(@"secondMatchAsString = %@", secondMatchAsString);
int temperature = [secondMatchAsString intValue]; // should be 32 for your sample data
NSLog(@"temperature = %d", temperature);
}
``` |
18,811,343 | I'm not using RESTAdapter so I create Ember Object and using reopenClass method and jquery ajax function for ajax requesting and the code is:
```
OlapApp.Dimenssions = Ember.Object.extend({});
OlapApp.Dimenssions.reopenClass({
measure:Ember.A(),
find:function(cubeUniqueName){
var c = Ember.A();
var xhr = $.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'http://localhost:9095/service.asmx/getDimension',
data: '{"cubeUniqueName":"'+cubeUniqueName+'"}',
success: function(response) {
var data = JSON.parse(response.d);
$.each(data.hierarchies,function(i,v) {
c.pushObject(OlapApp.Dimenssions.create(v));
});
console.log(c);
}
});
return c;
}
});
```
when `OlapApp.Dimenssions.find()` called the server response a json like this:
```
{
"uniqueName": "[Customers] = [Database].[Cube 2]",
"name": "Customers",
"caption": "Customers",
"dimensionUniqueName": null,
"description": "Description",
"levelUniqueName": null,
"hierarchyUniqueName": null,
"visible": true,
"hierarchies": [
{
"uniqueName": "[Customers]",
"name": "Customers",
"caption": "Customers",
"dimensionUniqueName": "[Customers]",
"levels": [
{
"uniqueName": "[Customers].[(All)]",
"name": "(All)",
"caption": "(All)",
"description": "Description",
"hierarchyUniqueName": "[Customers]",
"dimensionUniqueName": "[Customers]",
"visible": true
},
{
"uniqueName": "[Customers].[Country]",
"name": "Country",
"caption": "Country",
"description": "Description",
"hierarchyUniqueName": "[Customers]",
"dimensionUniqueName": "[Customers]",
"visible": true
}
]
}
]
}
```
the first problem is here that I can't push json corectly in **c** arrary so I try to create a model for this and the model code is:
```
OlapApp.RootMembers = DS.Model.extend({
id:DS.attr("number"),
uniqueName:DS.attr('string'),
name:DS.attr('string'),
caption:DS.attr('string'),
dimensionUniqueName:DS.attr('string'),
description:DS.attr('string'),
levelUniqueName:DS.attr('string'),
hierarchyUniqueName:DS.attr('string')
});
OlapApp.Levels = DS.Model.extend({
id:DS.attr("number"),
uniqueName:DS.attr('string'),
name:DS.attr('string'),
caption:DS.attr('string'),
hierarchyUniqueName:DS.attr('string'),
dimensionUniqueName:DS.attr('string'),
visible:DS.attr('boolean'),
description:DS.attr('string')
});
OlapApp.Hierarchies = DS.Model.extend({
id:DS.attr("number"),
uniqueName:DS.attr('string'),
name:DS.attr('string'),
caption:DS.attr('string'),
dimensionUniqueName:DS.attr('string'),
levels:DS.hasMany(OlapApp.Levels,{embedded:always}),
rootMembers:DS.hasMany(OlapApp.RootMembers,{embedded:always})
});
```
you can see real json that returned form server [here](https://www.paste.org/67355)
but how can I map this json to these model ? if I can't map to model can I map nested json to Ember.Object. | 2013/09/15 | [
"https://Stackoverflow.com/questions/18811343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1262045/"
] | ```
this.set('yourModelClass', yourArray.props);
```
This should do the trick as you said that you have all the json data in Array `'C'` | i can fix my problem with this line of code :
```
var data = JSON.parse(response.d);
c.pushObject(Ember.Object.create(data));
``` |
22,698,371 | I have searched for possible solution by googling/so/forums for pdfClown/pdfbox and posting the problem at SO.
**Problem:** I have been trying to find a solution to highlight text, which spans across multiple lines in pdf document. The pdf can have one/two-column pages.
By using pdf-clown, I was able to highlight phrases, ONLY if all the words appear in the same line. pdfBox has created the XML for individual words, I could not find solution for phrases/lines.
Please suggest solution for pdf-clown, if any. (or) any other tool that is capable of highlighting text in multiple lines in pdf, with JAVA compatibility.
I could not understand the answer similar question, but iText, any help?:
[Multiline markup annotations with iText](https://stackoverflow.com/questions/18208636/multiline-markup-annotations-with-itext) | 2014/03/27 | [
"https://Stackoverflow.com/questions/22698371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1830284/"
] | Here you go: **<http://jsfiddle.net/8t3Xq/1/>**
This demonstrates loading your `<li>` thumbs just as your question does, then I show how to easily change one of them. How to "*change*" them is endless, this is just a simple example of changing the content and background. So you must not have your selectors right.
This is just a snippet, see fiddle for everything...
```
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"><a href="#playVideo"></a></li>');
console.log(videoThm);
});
});
window.changeIt=function()
{
$('li').first().html("I'm changed!");
$('li').first().css("background-image","");
}
```
Just make sure the `<li>`s are present first before your code that changes them is present. Would need to see more of you code to understand when/how that happens. | there is no way that my answer is so far removed from the problem statement. my guess is that either I somehow errantly posted this answer or the problem was edited. apologies
you could also use:
```
$(document).on('click','li .playVideo',function(){
//do something
});
```
i would probably change your #playVideo to a class, if you will have multiple li's |
22,698,371 | I have searched for possible solution by googling/so/forums for pdfClown/pdfbox and posting the problem at SO.
**Problem:** I have been trying to find a solution to highlight text, which spans across multiple lines in pdf document. The pdf can have one/two-column pages.
By using pdf-clown, I was able to highlight phrases, ONLY if all the words appear in the same line. pdfBox has created the XML for individual words, I could not find solution for phrases/lines.
Please suggest solution for pdf-clown, if any. (or) any other tool that is capable of highlighting text in multiple lines in pdf, with JAVA compatibility.
I could not understand the answer similar question, but iText, any help?:
[Multiline markup annotations with iText](https://stackoverflow.com/questions/18208636/multiline-markup-annotations-with-itext) | 2014/03/27 | [
"https://Stackoverflow.com/questions/22698371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1830284/"
] | ```
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').append('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"><a href="#playVideo"></a></li>');
console.log(videoThm);
$( "#galThms li" ).click(function() {
$(this).hide();
});
});
});
```
try this | there is no way that my answer is so far removed from the problem statement. my guess is that either I somehow errantly posted this answer or the problem was edited. apologies
you could also use:
```
$(document).on('click','li .playVideo',function(){
//do something
});
```
i would probably change your #playVideo to a class, if you will have multiple li's |
38,978,805 | I will try to explain my problem as clearly as possible, please tell me if it is not.
I have a table `[MyTable]` that looks like this:
```
----------------------------------------
|chn:integer | auds:integer (repeated) |
----------------------------------------
|1 |3916 |
|1 |4983 |
|1 |6233 |
|1 |1214 |
|2 |1200 |
|2 |900 |
|2 |2030 |
|2 |2345 |
----------------------------------------
```
`Auds` is always repeated 4 times.
If I query `SELECT chn, auds FROM [MyTable] WHERE chn = 1`, I get the following result:
```
-------------------
|Row | chn | auds |
-------------------
|1 |1 |3916 |
|2 |1 |4983 |
|3 |1 |6233 |
|4 |1 |1214 |
-------------------
```
If I query `SELECT chn, auds FROM [MyTable] WHERE (chn = 1 OR chn = 2)`, I get the following result:
```
-------------------
|Row | chn | auds |
-------------------
|1 |1 |1200 |
|2 |1 |900 |
|3 |1 |2030 |
|4 |2 |2345 |
-------------------
```
Logically, I get twice as much results, but what I would like to get is the `SUM()` of the repeated field `auds` for `chn = 1` and `chn = 2`, or visually, something like this:
```
-------------------
|Row | chn | auds |
-------------------
|1 |3 |5116 |
|2 |3 |5883 |
|3 |3 |8263 |
|4 |3 |3559 |
-------------------
```
I tried to to something:
```
SELECT a1+a2 FROM
(SELECT auds AS a1 FROM [MyTable] WHERE chn = 1),
(SELECT auds AS a2 FROM [MyTable] WHERE chn = 2)
```
But I get the following error:
```
Error: Cannot query the cross product of repeated fields a1 and a2.
``` | 2016/08/16 | [
"https://Stackoverflow.com/questions/38978805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613459/"
] | It's much easier to express this sort of logic with [standard SQL](https://cloud.google.com/bigquery/sql-reference/) (uncheck "Use Legacy SQL" under "Show Options"). Here's an example that computes sums over the `auds` arrays:
```
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
)
SELECT
chn,
(SELECT SUM(aud) FROM UNNEST(auds) AS aud) AS auds_sum
FROM MyTable;
+-----+----------+
| chn | auds_sum |
+-----+----------+
| 1 | 20 |
| 2 | 45 |
+-----+----------+
```
And another that computes pairwise sums for `chn = 1` and `chn = 2` (which I think is what you wanted based on your question):
```
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
)
SELECT
ARRAY(SELECT first_aud + second_auds[OFFSET(off)]
FROM UNNEST(first_auds) AS first_aud WITH OFFSET off)
AS summed_auds
FROM (
SELECT
(SELECT auds FROM MyTable WHERE chn = 1) AS first_auds,
(SELECT auds FROM MyTable WHERE chn = 2) AS second_auds
);
+---------------------+
| summed_auds |
+---------------------+
| [9, 11, 13, 15, 17] |
+---------------------+
```
Edit: one more example that sums corresponding array elements across all rows. This probably won't be particularly efficient, but it should produce the intended result:
```
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
UNION ALL SELECT
3 AS chn,
[-1, -6, 2, 3, 2] AS auds
)
SELECT
ARRAY(SELECT
(SELECT SUM(auds[OFFSET(off)]) FROM UNNEST(all_auds))
FROM UNNEST(all_auds[OFFSET(0)].auds) WITH OFFSET off)
AS summed_auds
FROM (
SELECT
ARRAY_AGG(STRUCT(auds)) AS all_auds
FROM MyTable
);
+--------------------+
| summed_auds |
+--------------------+
| [8, 5, 15, 18, 19] |
+--------------------+
``` | Just use `GROUP BY` in conjunction with `SUM`.
```
SELECT SUM(auds), chn FROM [MyTable] GROUP BY chn
``` |
38,978,805 | I will try to explain my problem as clearly as possible, please tell me if it is not.
I have a table `[MyTable]` that looks like this:
```
----------------------------------------
|chn:integer | auds:integer (repeated) |
----------------------------------------
|1 |3916 |
|1 |4983 |
|1 |6233 |
|1 |1214 |
|2 |1200 |
|2 |900 |
|2 |2030 |
|2 |2345 |
----------------------------------------
```
`Auds` is always repeated 4 times.
If I query `SELECT chn, auds FROM [MyTable] WHERE chn = 1`, I get the following result:
```
-------------------
|Row | chn | auds |
-------------------
|1 |1 |3916 |
|2 |1 |4983 |
|3 |1 |6233 |
|4 |1 |1214 |
-------------------
```
If I query `SELECT chn, auds FROM [MyTable] WHERE (chn = 1 OR chn = 2)`, I get the following result:
```
-------------------
|Row | chn | auds |
-------------------
|1 |1 |1200 |
|2 |1 |900 |
|3 |1 |2030 |
|4 |2 |2345 |
-------------------
```
Logically, I get twice as much results, but what I would like to get is the `SUM()` of the repeated field `auds` for `chn = 1` and `chn = 2`, or visually, something like this:
```
-------------------
|Row | chn | auds |
-------------------
|1 |3 |5116 |
|2 |3 |5883 |
|3 |3 |8263 |
|4 |3 |3559 |
-------------------
```
I tried to to something:
```
SELECT a1+a2 FROM
(SELECT auds AS a1 FROM [MyTable] WHERE chn = 1),
(SELECT auds AS a2 FROM [MyTable] WHERE chn = 2)
```
But I get the following error:
```
Error: Cannot query the cross product of repeated fields a1 and a2.
``` | 2016/08/16 | [
"https://Stackoverflow.com/questions/38978805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613459/"
] | Elliott’s answers are always inspiration for me! Please vote and accept his answer if it works for you (it should :o))
Meantime, wanted to add alternative option with [Scalar JS UDF](https://cloud.google.com/bigquery/sql-reference/user-defined-functions#user-defined-functions)
```
CREATE TEMPORARY FUNCTION mySUM(a ARRAY<INT64>, b ARRAY<INT64>)
RETURNS ARRAY<INT64>
LANGUAGE js AS """
var sum = [];
for(var i = 0; i < a.length; i++){
sum.push(parseInt(a[i]) + parseInt(b[i]));
}
return sum
""";
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
)
SELECT
first_auds.chn AS first_auds_chn,
second_auds.chn AS second_auds_chn,
mySUM(first_auds.auds, second_auds.auds) AS summed_auds
FROM MyTable AS first_auds
JOIN MyTable AS second_auds
ON first_auds.chn = 1 AND second_auds.chn = 2
```
I like this option because it less filled with multiple UNNESTs, ARRAYs etc so it is much cleaner to read. | Just use `GROUP BY` in conjunction with `SUM`.
```
SELECT SUM(auds), chn FROM [MyTable] GROUP BY chn
``` |
38,978,805 | I will try to explain my problem as clearly as possible, please tell me if it is not.
I have a table `[MyTable]` that looks like this:
```
----------------------------------------
|chn:integer | auds:integer (repeated) |
----------------------------------------
|1 |3916 |
|1 |4983 |
|1 |6233 |
|1 |1214 |
|2 |1200 |
|2 |900 |
|2 |2030 |
|2 |2345 |
----------------------------------------
```
`Auds` is always repeated 4 times.
If I query `SELECT chn, auds FROM [MyTable] WHERE chn = 1`, I get the following result:
```
-------------------
|Row | chn | auds |
-------------------
|1 |1 |3916 |
|2 |1 |4983 |
|3 |1 |6233 |
|4 |1 |1214 |
-------------------
```
If I query `SELECT chn, auds FROM [MyTable] WHERE (chn = 1 OR chn = 2)`, I get the following result:
```
-------------------
|Row | chn | auds |
-------------------
|1 |1 |1200 |
|2 |1 |900 |
|3 |1 |2030 |
|4 |2 |2345 |
-------------------
```
Logically, I get twice as much results, but what I would like to get is the `SUM()` of the repeated field `auds` for `chn = 1` and `chn = 2`, or visually, something like this:
```
-------------------
|Row | chn | auds |
-------------------
|1 |3 |5116 |
|2 |3 |5883 |
|3 |3 |8263 |
|4 |3 |3559 |
-------------------
```
I tried to to something:
```
SELECT a1+a2 FROM
(SELECT auds AS a1 FROM [MyTable] WHERE chn = 1),
(SELECT auds AS a2 FROM [MyTable] WHERE chn = 2)
```
But I get the following error:
```
Error: Cannot query the cross product of repeated fields a1 and a2.
``` | 2016/08/16 | [
"https://Stackoverflow.com/questions/38978805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613459/"
] | It's much easier to express this sort of logic with [standard SQL](https://cloud.google.com/bigquery/sql-reference/) (uncheck "Use Legacy SQL" under "Show Options"). Here's an example that computes sums over the `auds` arrays:
```
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
)
SELECT
chn,
(SELECT SUM(aud) FROM UNNEST(auds) AS aud) AS auds_sum
FROM MyTable;
+-----+----------+
| chn | auds_sum |
+-----+----------+
| 1 | 20 |
| 2 | 45 |
+-----+----------+
```
And another that computes pairwise sums for `chn = 1` and `chn = 2` (which I think is what you wanted based on your question):
```
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
)
SELECT
ARRAY(SELECT first_aud + second_auds[OFFSET(off)]
FROM UNNEST(first_auds) AS first_aud WITH OFFSET off)
AS summed_auds
FROM (
SELECT
(SELECT auds FROM MyTable WHERE chn = 1) AS first_auds,
(SELECT auds FROM MyTable WHERE chn = 2) AS second_auds
);
+---------------------+
| summed_auds |
+---------------------+
| [9, 11, 13, 15, 17] |
+---------------------+
```
Edit: one more example that sums corresponding array elements across all rows. This probably won't be particularly efficient, but it should produce the intended result:
```
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
UNION ALL SELECT
3 AS chn,
[-1, -6, 2, 3, 2] AS auds
)
SELECT
ARRAY(SELECT
(SELECT SUM(auds[OFFSET(off)]) FROM UNNEST(all_auds))
FROM UNNEST(all_auds[OFFSET(0)].auds) WITH OFFSET off)
AS summed_auds
FROM (
SELECT
ARRAY_AGG(STRUCT(auds)) AS all_auds
FROM MyTable
);
+--------------------+
| summed_auds |
+--------------------+
| [8, 5, 15, 18, 19] |
+--------------------+
``` | Elliott’s answers are always inspiration for me! Please vote and accept his answer if it works for you (it should :o))
Meantime, wanted to add alternative option with [Scalar JS UDF](https://cloud.google.com/bigquery/sql-reference/user-defined-functions#user-defined-functions)
```
CREATE TEMPORARY FUNCTION mySUM(a ARRAY<INT64>, b ARRAY<INT64>)
RETURNS ARRAY<INT64>
LANGUAGE js AS """
var sum = [];
for(var i = 0; i < a.length; i++){
sum.push(parseInt(a[i]) + parseInt(b[i]));
}
return sum
""";
WITH MyTable AS (
SELECT
1 AS chn,
[2, 3, 4, 5, 6] AS auds
UNION ALL SELECT
2 AS chn,
[7, 8, 9, 10, 11] AS auds
)
SELECT
first_auds.chn AS first_auds_chn,
second_auds.chn AS second_auds_chn,
mySUM(first_auds.auds, second_auds.auds) AS summed_auds
FROM MyTable AS first_auds
JOIN MyTable AS second_auds
ON first_auds.chn = 1 AND second_auds.chn = 2
```
I like this option because it less filled with multiple UNNESTs, ARRAYs etc so it is much cleaner to read. |
17,675,715 | The way I do it now is:
1. CTRL + F
2. Enter Data to Find (e.g. "57011-141")
3. Click Find All
4. Usually 10-20 rows will come up. I then go one by one copying and pasting into a new book.
I am looking to automate this process as it is time consuming and error prone. | 2013/07/16 | [
"https://Stackoverflow.com/questions/17675715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1911755/"
] | If the `57011-141` appears in a single column (sorting irrelevant)
Filter the data (This image is from Excel 2010)

The down arrow next to the column name will allow you to set the filter under TextFilters -> Contains
Once the filter is applied, select all the displayed data - use `ALT`+`;`
Copy the data (use menu or `CTRL`+`C`)
Find your destination and paste (use menu or `CTRL`+`V`)
This will copy column headers, as well as the filtered data, so if you have multiple copies to do, you will have to remove the extra headers | If `57011-141` appears in single column, here is the solution.
1. Sort the book with that particular column.
2. CTRL + F
3. Data to Find (e.g. "57011-141")
4. Click Find All
5. Cntrl + A
6. Close Find & Replace Dialog
7. Shift + Space to select all rows which returned by Find
8. Copy and paste into new sheet
Edit:
if "57011-141" found in middle of a string in cell,
1. Add a new column (D) next to the search column (C)
2. Formula in column D1 `=ISNUMBER(SEARCH("57011-141",C1,1))`
3. Copy & Paste the formula to all rows
4. Sort column D
Now you will get all the identified rows in column D if value `TRUE` |
35,261 | I've recently moved into a home with a gas oven, but I've never used a gas oven before. What general differences might I expect compared to cooking in an electric oven? Humidity? Cook times? What rack setting to use? What temperature to use? Different cooking characteristics? Etc. | 2013/07/12 | [
"https://cooking.stackexchange.com/questions/35261",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/6992/"
] | My experience with gas ovens is that they are much more susceptible to heat 'zones'. The top of the oven is markedly hotter than the bottom, and the back, nearer the flame, is hotter than the front. Other than that they are pretty similar to electric ovens.
Gas ovens *may* use gas mark settings rather than a temperature scale - converters abound online if so. | In almost all respects, cooking in a gas oven is the same as cooking in an electric oven.
Some differences you may find:
* Some gas ovens have a broiler (or grill, in UK parlance) at the top of the main oven chamber. When using this, you *may* need to have the door partially opened—see the manual of your particular oven.
* In most gas ovens, the actual flame elements are *beneath* the oven floor (except for the broiler element described above), so you don't want to block the floor with a pizza stone or similar.
While it is technically true that gas ovens are less airtight, and slightly more humid (due to water produced as a byproduct of burning the natural gas) than electric ovens, in practice this makes little difference at all.
You still want to cook by temperature, not by "mark" or "dial" setting. You should get an oven thermometer if you don't already have one, to calibrate that setting shown on the dial or control matches the actual temperature inside the oven, at least to within 25 degrees F (or about 10 degrees C) or so.
---
You will actually find more differences just as variance from one oven to another—some bake a little hot, or a little cold. Others have different hot spots or heat circulation patterns.
Baking some simple cookies or sheet cakes that you know well, and monitoring the results should help you get used to any adjustments you need to make for your new oven. Of course, so will the oven thermometer! |
11,943 | I am using `auto.arima()` for forecasting. When I am using any in built data such as "AirPassengers" it is capturing seasonality. But, If I am entering data in any other format (in vector form or from an excel sheet) it is not detecting seasonality.
Is there any specific format in which it detects seasonality or I am doing some thing wrong?
Does data have to be entered in a specific format? | 2011/06/15 | [
"https://stats.stackexchange.com/questions/11943",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/5028/"
] | As @Dmitrij Celov commented, make sure your data is a ts() object, with the proper frequency. For example, if you have a vector of quarterly data, x = c(4,3,2,1,4,3,2,1), create y=ts(x,frequency=4). Use frequency=12 for monthly data, etc. | convert to ts, ts(x, start=c(2006,10), freq=12) |
66,193,536 | The result of this code is different depend on type of reference variable does this mean variables (int a) are bounded in static way
```
class A{
int a = 10;
}
public class Main extends A {
int a = 30;
public static void main(String[] args){
A m = new Main();
System.out.println("A : " + m.a);
}
}
``` | 2021/02/14 | [
"https://Stackoverflow.com/questions/66193536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15206995/"
] | This is not just like `static` or `dynamic binding`. There is no `polymorphism` for `fields` in Java, only for `methods`.
Variables decisions are always taken at `compile-time`.
So, during the `upcasting` base class variable will be taken. | The variable `m` you have declared is of type `A` so the output would be `10`. Instead if you have initialized `m` as `Main m = new Main();`, then the output would have been `30`. This is because, the object is of type `Main` and since `Main` also has a field `a`, this would override the parent field `a`. |
66,193,536 | The result of this code is different depend on type of reference variable does this mean variables (int a) are bounded in static way
```
class A{
int a = 10;
}
public class Main extends A {
int a = 30;
public static void main(String[] args){
A m = new Main();
System.out.println("A : " + m.a);
}
}
``` | 2021/02/14 | [
"https://Stackoverflow.com/questions/66193536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15206995/"
] | This is not just like `static` or `dynamic binding`. There is no `polymorphism` for `fields` in Java, only for `methods`.
Variables decisions are always taken at `compile-time`.
So, during the `upcasting` base class variable will be taken. | You have two object's type (`A, Main`) both from them have their own meaning for a variable `a`, so when your variable m has type `A` you get value `10` and if variable m has type `Main` you will get value `30`. |
40,621,770 | I was trying to clear my git after adding files from the wrong directory and ran the git clean -df function. This resulted in all my user data being deleted.
I haven't done anything more in git after this, and I don't dare to turn of my PC at the moment. However, I noticed that there is a .git folder which contains about 600MB of data. Is it possible that y files are stored there and can be recovered?
I run Windows 10 and do not have any backup or restore points for the user data folder.
Any help would be greatly appreciated as I had som really important data stored.
Thank you | 2016/11/15 | [
"https://Stackoverflow.com/questions/40621770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7119826/"
] | There's no way to recover from this unless you had a backup or want to explore using undelete utilities. Git is not saving backups anywhere. | Short answer and most probable there is not!!
Still some IDE's track and store locally this information see for example:
[Is it still possible to restore deleted untracked files in git?](https://stackoverflow.com/questions/9750049/is-it-possible-to-restore-deleted-untracked-files-in-git)
So depending on your IDE or text editor it still might be possible. |
40,621,770 | I was trying to clear my git after adding files from the wrong directory and ran the git clean -df function. This resulted in all my user data being deleted.
I haven't done anything more in git after this, and I don't dare to turn of my PC at the moment. However, I noticed that there is a .git folder which contains about 600MB of data. Is it possible that y files are stored there and can be recovered?
I run Windows 10 and do not have any backup or restore points for the user data folder.
Any help would be greatly appreciated as I had som really important data stored.
Thank you | 2016/11/15 | [
"https://Stackoverflow.com/questions/40621770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7119826/"
] | There's no way to recover from this unless you had a backup or want to explore using undelete utilities. Git is not saving backups anywhere. | If you're using Eclipse, and you're only missing code or text, don't despair, not all may be lost. Go to:
```
[WORKSPACE]/.metadata/.plugins/org.eclipse.core.resources/.history
```
Then use `grep` (\*nix), `FINDSTR` (Windows) or a similiar tool to search for text snippets you know to have occurred in the deleted files. Eclipse keeps a lot of local history revisions around, so if you worked on these files recently, you will probably have **a lot** of matches. Then you need to find most recent one of these, which can be a bit tricky.
To give an example: After doing a quick `git clean -d -fx` to show this dangerous feature to a colleague, I was missing an untracked java code file, of which I knew it contained the String `XrefCollector`. I was able to find the last local history revision by doing this:
```
find . -printf "%T@ %p\n" | sort -n | cut -d" " -f2 | xargs grep -l XrefCollector | tail -n1
```
Here, `find` prepends the date (epoch) to the files, `sort` sorts (numerically), `cut` removes the date again, and `xargs` passes the filenames on to `grep`, which searches for the desired string. Finally, `tail` only shows the last line of output. |
40,621,770 | I was trying to clear my git after adding files from the wrong directory and ran the git clean -df function. This resulted in all my user data being deleted.
I haven't done anything more in git after this, and I don't dare to turn of my PC at the moment. However, I noticed that there is a .git folder which contains about 600MB of data. Is it possible that y files are stored there and can be recovered?
I run Windows 10 and do not have any backup or restore points for the user data folder.
Any help would be greatly appreciated as I had som really important data stored.
Thank you | 2016/11/15 | [
"https://Stackoverflow.com/questions/40621770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7119826/"
] | Short answer and most probable there is not!!
Still some IDE's track and store locally this information see for example:
[Is it still possible to restore deleted untracked files in git?](https://stackoverflow.com/questions/9750049/is-it-possible-to-restore-deleted-untracked-files-in-git)
So depending on your IDE or text editor it still might be possible. | If you're using Eclipse, and you're only missing code or text, don't despair, not all may be lost. Go to:
```
[WORKSPACE]/.metadata/.plugins/org.eclipse.core.resources/.history
```
Then use `grep` (\*nix), `FINDSTR` (Windows) or a similiar tool to search for text snippets you know to have occurred in the deleted files. Eclipse keeps a lot of local history revisions around, so if you worked on these files recently, you will probably have **a lot** of matches. Then you need to find most recent one of these, which can be a bit tricky.
To give an example: After doing a quick `git clean -d -fx` to show this dangerous feature to a colleague, I was missing an untracked java code file, of which I knew it contained the String `XrefCollector`. I was able to find the last local history revision by doing this:
```
find . -printf "%T@ %p\n" | sort -n | cut -d" " -f2 | xargs grep -l XrefCollector | tail -n1
```
Here, `find` prepends the date (epoch) to the files, `sort` sorts (numerically), `cut` removes the date again, and `xargs` passes the filenames on to `grep`, which searches for the desired string. Finally, `tail` only shows the last line of output. |
24,648,183 | I currently work on a project in python and I would have liked to make a SQL query with an apostrophe in my character string. Ex: `"Jimmy's home."`
And I have this error:
```
1064 You have an error in your SQL syntax
```
So, I've tried to put a `\` before the apostrophe, but when I look at my database, just the strings before the `\'` are in my field.
String to in query: `"Jimmy\'s home"`
String in Database: `"Jimmy"`
I don't understand why? | 2014/07/09 | [
"https://Stackoverflow.com/questions/24648183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816599/"
] | If you apply the class to be added as the `id` for buttons, you can do the following:
```
$('.btn').click(function(){
$('.active').removeClass('active');
$(this).addClass('active');
$('.item').removeClass().addClass('item').addClass(this.id);
});
```
[Demo](http://jsfiddle.net/6UW33/7/)
*side note: you had a typo in your css, the class in second button is `grid`, in css its `gird`* | [DEMO](http://jsfiddle.net/straszak_piotr/6UW33/1/)
Best practice would be using `data-yourVariableName` (`data-class` in my DEMO) attributes for data that will be used by your code. Then you just write something like that:
```
$("button").click(function(){
$(".item").toggleClass($(this).attr('data-class'));
});
```
This is jQuery code. If it's unfamiliar to you, here's their [API](http://api.jquery.com/). |
24,648,183 | I currently work on a project in python and I would have liked to make a SQL query with an apostrophe in my character string. Ex: `"Jimmy's home."`
And I have this error:
```
1064 You have an error in your SQL syntax
```
So, I've tried to put a `\` before the apostrophe, but when I look at my database, just the strings before the `\'` are in my field.
String to in query: `"Jimmy\'s home"`
String in Database: `"Jimmy"`
I don't understand why? | 2014/07/09 | [
"https://Stackoverflow.com/questions/24648183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816599/"
] | You can get `class` by `attr` and then remove `btn` class to get other `class` names. But, I would prefer to save class names in `data` attribute.
**[Demo](http://jsfiddle.net/6UW33/5/)**
**HTML:**
```
<button type="button" data-class="gridLarge" class="btn gridLarge active">largegrid</button>
<button type="button" data-class="grid" class="btn grid">smallgrid</button>
<button type="button" data-class="list" class="btn list">list</button>
<div class="item"></div>
```
**Javascript:**
```
$('.btn').click(function () {
var $this = $(this);
$('.btn').removeClass('active');
$this.addClass('active');
$('.item').removeClass('gridLarge grid list').addClass($this.data('class'));
});
```
**CSS:**
```
.item {
height:240px;
border:1px solid orange;
}
.item.list {
width:600px;
height:500px;
border:1px solid red;
}
.item.grid {
width:400px;
height:500px;
border:1px solid red;
}
.item.gridlarge {
width:500px;
height:500px;
border:1px solid red;
}
button {
cursor:pointer;
border:1px solid green;
padding:20px;
color:red;
margin-bottom:20px;
}
.btn.active {
color:green;
background-color:red;
}
``` | [DEMO](http://jsfiddle.net/straszak_piotr/6UW33/1/)
Best practice would be using `data-yourVariableName` (`data-class` in my DEMO) attributes for data that will be used by your code. Then you just write something like that:
```
$("button").click(function(){
$(".item").toggleClass($(this).attr('data-class'));
});
```
This is jQuery code. If it's unfamiliar to you, here's their [API](http://api.jquery.com/). |
24,648,183 | I currently work on a project in python and I would have liked to make a SQL query with an apostrophe in my character string. Ex: `"Jimmy's home."`
And I have this error:
```
1064 You have an error in your SQL syntax
```
So, I've tried to put a `\` before the apostrophe, but when I look at my database, just the strings before the `\'` are in my field.
String to in query: `"Jimmy\'s home"`
String in Database: `"Jimmy"`
I don't understand why? | 2014/07/09 | [
"https://Stackoverflow.com/questions/24648183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816599/"
] | If you apply the class to be added as the `id` for buttons, you can do the following:
```
$('.btn').click(function(){
$('.active').removeClass('active');
$(this).addClass('active');
$('.item').removeClass().addClass('item').addClass(this.id);
});
```
[Demo](http://jsfiddle.net/6UW33/7/)
*side note: you had a typo in your css, the class in second button is `grid`, in css its `gird`* | You can get `class` by `attr` and then remove `btn` class to get other `class` names. But, I would prefer to save class names in `data` attribute.
**[Demo](http://jsfiddle.net/6UW33/5/)**
**HTML:**
```
<button type="button" data-class="gridLarge" class="btn gridLarge active">largegrid</button>
<button type="button" data-class="grid" class="btn grid">smallgrid</button>
<button type="button" data-class="list" class="btn list">list</button>
<div class="item"></div>
```
**Javascript:**
```
$('.btn').click(function () {
var $this = $(this);
$('.btn').removeClass('active');
$this.addClass('active');
$('.item').removeClass('gridLarge grid list').addClass($this.data('class'));
});
```
**CSS:**
```
.item {
height:240px;
border:1px solid orange;
}
.item.list {
width:600px;
height:500px;
border:1px solid red;
}
.item.grid {
width:400px;
height:500px;
border:1px solid red;
}
.item.gridlarge {
width:500px;
height:500px;
border:1px solid red;
}
button {
cursor:pointer;
border:1px solid green;
padding:20px;
color:red;
margin-bottom:20px;
}
.btn.active {
color:green;
background-color:red;
}
``` |
39,714,618 | I'm creating a 2D array for baseball scores, and if the home team's score is greater than visiting team score after the top of the 9th, then I need that array position to display a hyphen "-" instead of zero.
```
if (eigthhomeScore > visitorScore) {
scoreArray [1][8] = 0;
}
``` | 2016/09/27 | [
"https://Stackoverflow.com/questions/39714618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6765907/"
] | You would be correct in saying that.
The short answer is no. Hashing provides a 1-way interface for obscuring data where as encryption provides a 2-way interface for the encryption of data / decryption of encrypted data.
The only way an hash cant be 'decrypted' and I use that term loosely is by brute forcing via the hashing method. This is done by running a bunch of password and salt combinations through the same hashing method until a match is found to the original hash. However with a strong hashing method and password + salt this can become an almost impossible task.
Helpful Discussion: [Fundamental difference between Hashing and Encryption algorithms](https://stackoverflow.com/questions/4948322/fundamental-difference-between-hashing-and-encryption-algorithms)
EDIT:
The link of the online cryptographer you provided uses what is known as a Symmetric-key algorithm. This means that a single key is used for the encryption and decryption of the data.
<https://en.wikipedia.org/wiki/Symmetric-key_algorithm> | Short answer: no.
See also <https://en.wikipedia.org/wiki/Hash_function>
Correctly salted hashes cannot be reverted, which is the point of doing that. |
39,714,618 | I'm creating a 2D array for baseball scores, and if the home team's score is greater than visiting team score after the top of the 9th, then I need that array position to display a hyphen "-" instead of zero.
```
if (eigthhomeScore > visitorScore) {
scoreArray [1][8] = 0;
}
``` | 2016/09/27 | [
"https://Stackoverflow.com/questions/39714618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6765907/"
] | Short answer: no.
See also <https://en.wikipedia.org/wiki/Hash_function>
Correctly salted hashes cannot be reverted, which is the point of doing that. | No. Not easily.
A Hash will take some text and produce a number ( usually )
eg, a md5 hash
```
password => 5f4dcc3b5aa765d61d8327deb882cf99
```
By the nature of the hash, there is no easy way to get back from the number to the original text "password"
But, for the semi clever hacker, you can generate hashes using a dictionary of all words and in reasonable time crack most hashed passwords because people use common combinations of words and symbols. So if you happen to get a list of hashed passwords you can run a dictionary attack on them. Anyone who uses "password" as their password will end up having the same hash.
So as a defense to that, if you add some text unique to each user, a Salt, say, your username, now you've made it harder :-
your string to hash becomes "`Yukkipassword`" which hashes to `52fbd06f5b93a51b3f3cd9e807a9f61c`
Now everyone who uses "password" for their passsword will also have a different hash, and it becomes really difficult to dictionary attack the password |
39,714,618 | I'm creating a 2D array for baseball scores, and if the home team's score is greater than visiting team score after the top of the 9th, then I need that array position to display a hyphen "-" instead of zero.
```
if (eigthhomeScore > visitorScore) {
scoreArray [1][8] = 0;
}
``` | 2016/09/27 | [
"https://Stackoverflow.com/questions/39714618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6765907/"
] | You would be correct in saying that.
The short answer is no. Hashing provides a 1-way interface for obscuring data where as encryption provides a 2-way interface for the encryption of data / decryption of encrypted data.
The only way an hash cant be 'decrypted' and I use that term loosely is by brute forcing via the hashing method. This is done by running a bunch of password and salt combinations through the same hashing method until a match is found to the original hash. However with a strong hashing method and password + salt this can become an almost impossible task.
Helpful Discussion: [Fundamental difference between Hashing and Encryption algorithms](https://stackoverflow.com/questions/4948322/fundamental-difference-between-hashing-and-encryption-algorithms)
EDIT:
The link of the online cryptographer you provided uses what is known as a Symmetric-key algorithm. This means that a single key is used for the encryption and decryption of the data.
<https://en.wikipedia.org/wiki/Symmetric-key_algorithm> | No. Not easily.
A Hash will take some text and produce a number ( usually )
eg, a md5 hash
```
password => 5f4dcc3b5aa765d61d8327deb882cf99
```
By the nature of the hash, there is no easy way to get back from the number to the original text "password"
But, for the semi clever hacker, you can generate hashes using a dictionary of all words and in reasonable time crack most hashed passwords because people use common combinations of words and symbols. So if you happen to get a list of hashed passwords you can run a dictionary attack on them. Anyone who uses "password" as their password will end up having the same hash.
So as a defense to that, if you add some text unique to each user, a Salt, say, your username, now you've made it harder :-
your string to hash becomes "`Yukkipassword`" which hashes to `52fbd06f5b93a51b3f3cd9e807a9f61c`
Now everyone who uses "password" for their passsword will also have a different hash, and it becomes really difficult to dictionary attack the password |
59,968,513 | I have a few files that have a randomly generated number that corresponds with a date:
```
736815 = 01/05/2018
```
I need to create a function or process that applies logic to sequential numbers so that the next number equals the next calendar date.
Ideally i would need it in a key:pair format, so that when i convert the file to a new format i can apply the date in place of the auto file name.
Hopefully this makes more sense, it is to be used to name a converted file. | 2020/01/29 | [
"https://Stackoverflow.com/questions/59968513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12366745/"
] | I think `origin` parameter is possible use here, also add `unit='D'` to [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html):
```
df = pd.DataFrame({'col':[5678, 5679, 5680]})
df['date'] = pd.to_datetime(df['col'] - 5678, unit='D', origin=pd.Timestamp('2020-01-01'))
print (df)
col date
0 5678 2020-01-01
1 5679 2020-01-02
2 5680 2020-01-03
```
Non pandas solution, only pure python with same idea:
```
from datetime import datetime, timedelta
L = [5678, 5679, 5680]
a = [timedelta(x-5678) + datetime(2020,1,1) for x in L]
print (a)
[datetime.datetime(2020, 1, 1, 0, 0),
datetime.datetime(2020, 1, 2, 0, 0),
datetime.datetime(2020, 1, 3, 0, 0)]
``` | The number doesn't need to translate into the date directly in any way. You just need to pick a start date and a number, and add another number either via simple addition or via a `timedelta`:
```
from datetime import date, timedelta
from random import randint
start_date = date.today()
start_int = randint(1000, 10000)
for i in range(10):
print(start_int + i, start_date + timedelta(days=i))
```
```none
6964 2020-01-29
6965 2020-01-30
6966 2020-01-31
6967 2020-02-01
6968 2020-02-02
6969 2020-02-03
6970 2020-02-04
6971 2020-02-05
6972 2020-02-06
6973 2020-02-07
```
If you're getting your list of numbers from somewhere else, add/subtract appropriately from a start int/date for the same effect. |
59,968,513 | I have a few files that have a randomly generated number that corresponds with a date:
```
736815 = 01/05/2018
```
I need to create a function or process that applies logic to sequential numbers so that the next number equals the next calendar date.
Ideally i would need it in a key:pair format, so that when i convert the file to a new format i can apply the date in place of the auto file name.
Hopefully this makes more sense, it is to be used to name a converted file. | 2020/01/29 | [
"https://Stackoverflow.com/questions/59968513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12366745/"
] | I think `origin` parameter is possible use here, also add `unit='D'` to [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html):
```
df = pd.DataFrame({'col':[5678, 5679, 5680]})
df['date'] = pd.to_datetime(df['col'] - 5678, unit='D', origin=pd.Timestamp('2020-01-01'))
print (df)
col date
0 5678 2020-01-01
1 5679 2020-01-02
2 5680 2020-01-03
```
Non pandas solution, only pure python with same idea:
```
from datetime import datetime, timedelta
L = [5678, 5679, 5680]
a = [timedelta(x-5678) + datetime(2020,1,1) for x in L]
print (a)
[datetime.datetime(2020, 1, 1, 0, 0),
datetime.datetime(2020, 1, 2, 0, 0),
datetime.datetime(2020, 1, 3, 0, 0)]
``` | Another solution is to create an object, which encapsulates the date and the base number to count from. Each call to this object (implemented using the `__call__` special method) will create a new date object using the time delta between the base number and the supplied number.
```py
import datetime
class RelativeDate:
def __init__(self, date, base):
self.date = date
self.base = base
def __call__(self, number):
delta = datetime.timedelta(days=number - self.base)
return self.date + delta
def create_base_date(number, date):
return RelativeDate(
date=datetime.datetime.strptime(date, '%d/%m/%Y'),
base=number,
)
base_date = create_base_date(1, '03/01/2020')
base_date(3)
```
>
> datetime.datetime(2020, 1, 5, 0, 0)
>
>
>
---
Example snippet:
```
base_date = create_base_date(1, '03/01/2020')
{i: base_date(i) for i in range(1, 10)}
```
Output:
```
{1: datetime.datetime(2020, 1, 3, 0, 0),
2: datetime.datetime(2020, 1, 4, 0, 0),
3: datetime.datetime(2020, 1, 5, 0, 0),
4: datetime.datetime(2020, 1, 6, 0, 0),
5: datetime.datetime(2020, 1, 7, 0, 0),
6: datetime.datetime(2020, 1, 8, 0, 0),
7: datetime.datetime(2020, 1, 9, 0, 0),
8: datetime.datetime(2020, 1, 10, 0, 0),
9: datetime.datetime(2020, 1, 11, 0, 0)}
``` |
59,968,513 | I have a few files that have a randomly generated number that corresponds with a date:
```
736815 = 01/05/2018
```
I need to create a function or process that applies logic to sequential numbers so that the next number equals the next calendar date.
Ideally i would need it in a key:pair format, so that when i convert the file to a new format i can apply the date in place of the auto file name.
Hopefully this makes more sense, it is to be used to name a converted file. | 2020/01/29 | [
"https://Stackoverflow.com/questions/59968513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12366745/"
] | The number doesn't need to translate into the date directly in any way. You just need to pick a start date and a number, and add another number either via simple addition or via a `timedelta`:
```
from datetime import date, timedelta
from random import randint
start_date = date.today()
start_int = randint(1000, 10000)
for i in range(10):
print(start_int + i, start_date + timedelta(days=i))
```
```none
6964 2020-01-29
6965 2020-01-30
6966 2020-01-31
6967 2020-02-01
6968 2020-02-02
6969 2020-02-03
6970 2020-02-04
6971 2020-02-05
6972 2020-02-06
6973 2020-02-07
```
If you're getting your list of numbers from somewhere else, add/subtract appropriately from a start int/date for the same effect. | Another solution is to create an object, which encapsulates the date and the base number to count from. Each call to this object (implemented using the `__call__` special method) will create a new date object using the time delta between the base number and the supplied number.
```py
import datetime
class RelativeDate:
def __init__(self, date, base):
self.date = date
self.base = base
def __call__(self, number):
delta = datetime.timedelta(days=number - self.base)
return self.date + delta
def create_base_date(number, date):
return RelativeDate(
date=datetime.datetime.strptime(date, '%d/%m/%Y'),
base=number,
)
base_date = create_base_date(1, '03/01/2020')
base_date(3)
```
>
> datetime.datetime(2020, 1, 5, 0, 0)
>
>
>
---
Example snippet:
```
base_date = create_base_date(1, '03/01/2020')
{i: base_date(i) for i in range(1, 10)}
```
Output:
```
{1: datetime.datetime(2020, 1, 3, 0, 0),
2: datetime.datetime(2020, 1, 4, 0, 0),
3: datetime.datetime(2020, 1, 5, 0, 0),
4: datetime.datetime(2020, 1, 6, 0, 0),
5: datetime.datetime(2020, 1, 7, 0, 0),
6: datetime.datetime(2020, 1, 8, 0, 0),
7: datetime.datetime(2020, 1, 9, 0, 0),
8: datetime.datetime(2020, 1, 10, 0, 0),
9: datetime.datetime(2020, 1, 11, 0, 0)}
``` |
40,148,759 | I have a worksheet which contains a lot of sheets and each one contains some rows with specific background color
Is it possible to remove background color of all cells or rows which have specific color (yellow in my case) background in a worksheet
[here is an example file](http://s000.tinyupload.com/?file_id=28547251375822364965) | 2016/10/20 | [
"https://Stackoverflow.com/questions/40148759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6482460/"
] | Yes it is possible. You have to check for the Range.Interior.Color value of a specific Range. In VBA this would look like this:
```
If ActiveWorksheet.Range("A1").Interior.Color = RGB(255,255,0) Then
'Do something
End If
```
`RGB(255,255,0)` is yellow in this case. You can use all other values as well. See [RGB Function](https://msdn.microsoft.com/en-us/library/zc1dyw8b(v=vs.90).aspx). To remove the color use this:
```
Range("A1").Interior.Pattern = xlNone
```
If you need further help, please give more detail information about your problem and/or leave a comment.
You might also want to check out these links: [Range.Interior](https://msdn.microsoft.com/en-us/library/office/ff836210.aspx), [Interior.Color](https://msdn.microsoft.com/en-us/library/office/ff840499.aspx).
EDIT: According to your example data, you might want to remove green coloring from various sheets in columns "E","F","G" and "H". The RGB of the green is `RGB(146,208,80)`. This code should do the work:
```
Sub removeColor()
Dim lastRow As Long
Dim ws As Worksheet
Dim i As Long
Dim color As Long
color = RGB(146, 208, 80)
For Each ws In ThisWorkbook.Worksheets
lastRow = ws.Range("A65536").End(xlUp).Row
For i = 3 To lastRow
If ws.Range("E" & i).Interior.color = color Then
ws.Range("E" & i).Interior.Pattern = xlNone
End If
If ws.Range("F" & i).Interior.color = color Then
ws.Range("F" & i).Interior.Pattern = xlNone
End If
If ws.Range("G" & i).Interior.color = color Then
ws.Range("G" & i).Interior.Pattern = xlNone
End If
If ws.Range("H" & i).Interior.color = color Then
ws.Range("H" & i).Interior.Pattern = xlNone
End If
Next i
Next ws
End Sub
```
EDIT: If you want to check ALL cells for their color use this:
```
Sub removeColor()
Dim ws As Worksheet
Dim cell as Range
Dim color As Long
color = RGB(146, 208, 80)
For Each ws In ThisWorkbook.Worksheets
For Each cell in ws.UsedRange
If cell.Interior.Color = color Then
cell.Interior.Pattern = xlNone
End If
Next cell
Next ws
End Sub
``` | This might solve youre problem:
```
For i = 1 To Sheets.Count
On Error GoTo nex:
Sheets(i).Activate
For j = 1 To ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
For k = 1 To ActiveSheet.Cells.Find("*", SearchOrder:=xlByColumns, LookIn:=xlValues, SearchDirection:=xlPrevious).Column
'65535 equals yellow
'5296274 equals green
If ActiveSheet.Cells(j, k).Interior.Color = 65535 Then ActiveSheet.Cells(j, k).Interior.Pattern = xlNone
Next
Next
nex:
Next
```
The loop goes through all Worksheets and looks for the backcolor in all used cells.
To get the number representing a color you can just color A1 in the desired color and run following code:
```
MsgBox (ActiveSheet.Cells(1, 1).Interior.Color)
```
Hope I could help. |
10,317,259 | When you decorate a model object's property with the `Required` attribute and don't specify `ErrorMessage` or `ResourceType/Name` you get the validation message in the interpolated form of "The {0} field is required.", where param 0 is the value of the `DisplayName` attribute of that property.
I want to change that default string to something else but I want to keep the generic nature of it, that is I don't want to specify `ErrorMessage` or `ResourceType/Name` for every property of the model object. Where is the default string stored and how can I change it? | 2012/04/25 | [
"https://Stackoverflow.com/questions/10317259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382783/"
] | Simply use the [file\_exists()](http://php.net/manual/en/function.file-exists.php) function | php has a function file\_exists. Use that to make some logic about if you show a link or not. |
10,317,259 | When you decorate a model object's property with the `Required` attribute and don't specify `ErrorMessage` or `ResourceType/Name` you get the validation message in the interpolated form of "The {0} field is required.", where param 0 is the value of the `DisplayName` attribute of that property.
I want to change that default string to something else but I want to keep the generic nature of it, that is I don't want to specify `ErrorMessage` or `ResourceType/Name` for every property of the model object. Where is the default string stored and how can I change it? | 2012/04/25 | [
"https://Stackoverflow.com/questions/10317259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382783/"
] | To look for files by a certain pattern you can use [glob](http://co.php.net/glob), then use is\_readable to check if you can read the files.
```
$files = array();
foreach(glob($dirname . DIRECTORY_SEPARATOR . $clientId . '-*' as $file) {
if(is_readable($file) {
$files[] = $file;
}
}
``` | Simply use the [file\_exists()](http://php.net/manual/en/function.file-exists.php) function |
10,317,259 | When you decorate a model object's property with the `Required` attribute and don't specify `ErrorMessage` or `ResourceType/Name` you get the validation message in the interpolated form of "The {0} field is required.", where param 0 is the value of the `DisplayName` attribute of that property.
I want to change that default string to something else but I want to keep the generic nature of it, that is I don't want to specify `ErrorMessage` or `ResourceType/Name` for every property of the model object. Where is the default string stored and how can I change it? | 2012/04/25 | [
"https://Stackoverflow.com/questions/10317259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382783/"
] | To look for files by a certain pattern you can use [glob](http://co.php.net/glob), then use is\_readable to check if you can read the files.
```
$files = array();
foreach(glob($dirname . DIRECTORY_SEPARATOR . $clientId . '-*' as $file) {
if(is_readable($file) {
$files[] = $file;
}
}
``` | php has a function file\_exists. Use that to make some logic about if you show a link or not. |
11,310,150 | This code is not compilable.
I can't find why in standard. Can someone explain?
```
#include <iostream>
#include <string>
template<typename T>
class S
{
public:
explicit S(const std::string& s_):s(s_)
{
}
std::ostream& print(std::ostream& os) const
{
os << s << std::endl;
return os;
}
private:
std::string s;
};
template<typename T>
std::ostream& operator << (std::ostream& os, const S<T>& obj)
{
return obj.print(os);
}
/*template<>
std::ostream& operator << <std::string> (std::ostream& os, const S<std::string>& obj)
{
return obj.print(os);
}*/
class Test
{
public:
explicit Test(const std::string& s_):s(s_)
{
}
//operator std::string() const { return s; }
operator S<std::string>() const { return S<std::string>(s); }
private:
std::string s;
};
int main()
{
Test t("Hello");
std::cout << t << std::endl;
}
```
Compiler output:
```
source.cpp: In function 'int main()':
source.cpp:47:17: error: no match for 'operator<<' in 'std::cout << t'
source.cpp:47:17: note: candidates are:
In file included from include/c++/4.7.1/iostream:40:0,
from source.cpp:1:
include/c++/4.7.1/ostream:106:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>::__ostream_type& (*)(std::basic_ostream<_CharT, _Traits>::__ostream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
include/c++/4.7.1/ostream:106:7: note: no known conversion for argument 1 from 'Test' to 'std::basic_ostream<char>::__ostream_type& (*)(std::basic_ostream<char>::__ostream_type&) {aka std::basic_ostream<char>& (*)(std::basic_ostream<char>&)}'
....
``` | 2012/07/03 | [
"https://Stackoverflow.com/questions/11310150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1498580/"
] | Thats because no conversions, except for array-to-pointer, function-to-pointer, lvalue-to-rvalue and top-level const/volatile removal (cf. c++11 or c++03, 14.8.2.1), are considered when matching a template function. Specifically, your user-defined conversion operator `Test -> S<string>` is not considered when deducing `T` for your `operator<<` overload, and that fails.
To make this universal overload work, you must do all the work at the receiving side:
```
template <class T>
typename enable_if<is_S<T>::value, ostream&>::type operator <<(ostream&, const T&);
```
That overload would take any `T`, if it weren't for the `enable_if` (it would be unfortunate, since we don't want it to interfere with other `operator<<` overloads). `is_S` would be a traits type that would tell you that `T` is in fact `S<...>`.
Plus, there's no way the compiler can guess (or at least it doesn't try) that you intended to convert `Test` to a `S<string>` and not `S<void>` or whatever (this conversion could be enabled by eg. a converting constructor in `S`). So you have to specify that
* `Test` is (convertible to) an `S` too
* the template parameter of `S`, when converting a `Test`, is `string`
---
```
template <class T>
struct is_S {
static const bool value = false;
};
template <class T>
struct is_S<S<T>> {
static const bool value = true;
typedef T T_type;
};
template <>
struct is_S<Test> {
static const bool value = true;
typedef string T_type;
};
```
You will have to convert the `T` to the correct `S` manually in the `operator<<` overload (eg. `S<typename is_S<T>::T_type> s = t`, or, if you want to avoid unnecessary copying, `const S<typename is_S<T>::T_type> &s = t`). | The first paragraph of @jpalecek's answer explains what the issue is. If you need a workaround, you could add a declaration like:
```
inline std::ostream& operator<< (std::ostream& os, const S<std::string>& s)
{ return operator<< <> (os, s); }
```
Since that overload is not a template, implicit conversions to `S<std::string>` will be considered.
But I can't see any way to do this for all types `S<T>`... |
64,552 | The number I am thinking of is 80808. This is a palindrome. However, it is more than a palindrome, because it can be flipped or mirrored and will still read the same way.
Is there a word for this? | 2012/04/17 | [
"https://english.stackexchange.com/questions/64552",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/7429/"
] | There's a term for words written in such a form that they can be read from another viewpoint, direction or orientation. They are called **ambigrams**. See the relevant [Wikipedia article](http://en.wikipedia.org/wiki/Ambigram). | I think the word you may want is [dihedral](http://mathworld.wolfram.com/DihedralPrime.html). The only numbers that can appear in such a construction are 0, 1, 2, 5, and 8, and the property primarily applies to numbers displayed on a calculator or using LED's.
There are also dihedral letters, namely the capitals H, I, O, and X. |
64,552 | The number I am thinking of is 80808. This is a palindrome. However, it is more than a palindrome, because it can be flipped or mirrored and will still read the same way.
Is there a word for this? | 2012/04/17 | [
"https://english.stackexchange.com/questions/64552",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/7429/"
] | [***Strobogrammatic number***](https://en.wikipedia.org/wiki/Strobogrammatic_number):
>
> A **strobogrammatic number** is a number that, given a base and given
> a set of glyphs, appears the same whether viewed normally or upside
> down by rotation of 180 degrees. (Wikipedia)
>
>
> | I think the word you may want is [dihedral](http://mathworld.wolfram.com/DihedralPrime.html). The only numbers that can appear in such a construction are 0, 1, 2, 5, and 8, and the property primarily applies to numbers displayed on a calculator or using LED's.
There are also dihedral letters, namely the capitals H, I, O, and X. |
64,552 | The number I am thinking of is 80808. This is a palindrome. However, it is more than a palindrome, because it can be flipped or mirrored and will still read the same way.
Is there a word for this? | 2012/04/17 | [
"https://english.stackexchange.com/questions/64552",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/7429/"
] | There's a term for words written in such a form that they can be read from another viewpoint, direction or orientation. They are called **ambigrams**. See the relevant [Wikipedia article](http://en.wikipedia.org/wiki/Ambigram). | I believe the term you are looking for is: `mirror-image ambigram`
More on [Wikipedia](http://en.wikipedia.org/wiki/Ambigram)... |
64,552 | The number I am thinking of is 80808. This is a palindrome. However, it is more than a palindrome, because it can be flipped or mirrored and will still read the same way.
Is there a word for this? | 2012/04/17 | [
"https://english.stackexchange.com/questions/64552",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/7429/"
] | There's a term for words written in such a form that they can be read from another viewpoint, direction or orientation. They are called **ambigrams**. See the relevant [Wikipedia article](http://en.wikipedia.org/wiki/Ambigram). | [***Strobogrammatic number***](https://en.wikipedia.org/wiki/Strobogrammatic_number):
>
> A **strobogrammatic number** is a number that, given a base and given
> a set of glyphs, appears the same whether viewed normally or upside
> down by rotation of 180 degrees. (Wikipedia)
>
>
> |
64,552 | The number I am thinking of is 80808. This is a palindrome. However, it is more than a palindrome, because it can be flipped or mirrored and will still read the same way.
Is there a word for this? | 2012/04/17 | [
"https://english.stackexchange.com/questions/64552",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/7429/"
] | [***Strobogrammatic number***](https://en.wikipedia.org/wiki/Strobogrammatic_number):
>
> A **strobogrammatic number** is a number that, given a base and given
> a set of glyphs, appears the same whether viewed normally or upside
> down by rotation of 180 degrees. (Wikipedia)
>
>
> | I believe the term you are looking for is: `mirror-image ambigram`
More on [Wikipedia](http://en.wikipedia.org/wiki/Ambigram)... |
5,848,490 | How can i read users of a remote linux server with PHP?
(like LDAP in windows)
If `finger` server has been runned on the remote linux server,**Now what?** | 2011/05/01 | [
"https://Stackoverflow.com/questions/5848490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726631/"
] | If you are talking about the [Request](http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Request.html) and [Response](http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Response.html) objects, there was a discussion about this on the Symfony developers mailing list a few days ago. I invite you to take a look at it [here](https://groups.google.com/forum/#!topic/symfony-devs/CiJuSno85_8).
Why not getters? Not sure if there is a definitive answer to this but I think it is a decision based on personal tastes mainly.
Does it break encapsulation? Not really in my opinion for this particular case. My reasoning is that for now, no special logic is performed on the various objects that are public right now. So in the end, you would end up retrieving the object via a getter and read or modify it directly. There is not much difference with retrieving the object using a public property.
```
// With Getters
$parameterBag = $request->getQuery();
$parameterBag->get('key');
// With Public Properties
$parameterBag = $request->query;
$parameterBag->get('key');
```
Encapsulation should be enforced when you need to be sure that a property has a particular value or format. For example, say you have a class with a cost property and this property should never be negative. So if the cost property was public, it could be possible to set it to a negative value by doing something like `$receipt->cost = -1;`. However, if you make it private and the user of the class is only able to set it via a setter, then you could ensure that the cost is never below 0 by doing some special validation in the setter code.
In our case, we are talking about a collection object, a ParameterBag object to be precise. I don't think there are special requirements on this object but I could be wrong. So for me, it is correct to have access to those properties via public properties.
The main argument I could see in favor of the getters is that it would be more consistent with the other parts of the framework where getters are used. However, the getters could co-exist with the public properties.
To conclude, I think it is safe for this particular case. Public properties should be used only in special cases where it seems to be beneficial and where it is correct to do so. | Do you mean the [Request](http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Request.html) object? Or what properties are you thinking of?
If you're worried about safety, then take a look at the [Security](http://symfony.com/doc/2.0/book/security/overview.html) component, use Test-Driven-Development, use tested libraries (don't invent your own authentication, cryptography and related solutions) and do code reviews. |
5,848,490 | How can i read users of a remote linux server with PHP?
(like LDAP in windows)
If `finger` server has been runned on the remote linux server,**Now what?** | 2011/05/01 | [
"https://Stackoverflow.com/questions/5848490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726631/"
] | If you are talking about the [Request](http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Request.html) and [Response](http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Response.html) objects, there was a discussion about this on the Symfony developers mailing list a few days ago. I invite you to take a look at it [here](https://groups.google.com/forum/#!topic/symfony-devs/CiJuSno85_8).
Why not getters? Not sure if there is a definitive answer to this but I think it is a decision based on personal tastes mainly.
Does it break encapsulation? Not really in my opinion for this particular case. My reasoning is that for now, no special logic is performed on the various objects that are public right now. So in the end, you would end up retrieving the object via a getter and read or modify it directly. There is not much difference with retrieving the object using a public property.
```
// With Getters
$parameterBag = $request->getQuery();
$parameterBag->get('key');
// With Public Properties
$parameterBag = $request->query;
$parameterBag->get('key');
```
Encapsulation should be enforced when you need to be sure that a property has a particular value or format. For example, say you have a class with a cost property and this property should never be negative. So if the cost property was public, it could be possible to set it to a negative value by doing something like `$receipt->cost = -1;`. However, if you make it private and the user of the class is only able to set it via a setter, then you could ensure that the cost is never below 0 by doing some special validation in the setter code.
In our case, we are talking about a collection object, a ParameterBag object to be precise. I don't think there are special requirements on this object but I could be wrong. So for me, it is correct to have access to those properties via public properties.
The main argument I could see in favor of the getters is that it would be more consistent with the other parts of the framework where getters are used. However, the getters could co-exist with the public properties.
To conclude, I think it is safe for this particular case. Public properties should be used only in special cases where it seems to be beneficial and where it is correct to do so. | What's the point to encapsulate what already's been encapsulated? I mean - each of this properties is a parameterBag instance with it's encapsulation. |
450,278 | Everytime I reboot, I've to turn off and on hotcorners from `unity-tweak-tool`. Other wise hot corners don't work. Any fix??
Thanks in advance! | 2014/04/19 | [
"https://askubuntu.com/questions/450278",
"https://askubuntu.com",
"https://askubuntu.com/users/38788/"
] | The guy in IRC was almost there, but not quite. The package that you need is called `dh-make` no `devscripts`. A simple `sudo apt-get install dh-make` should fix the issue.
How to know:
```
chmod 744 debian/pxpress/switch*
dh build
make: dh: Command not found
make: *** [build-arch] Error 127
dpkg-buildpackage: error: debian/rules build gave error exit status 2
```
`dh build` starts creating a debian package with the debhelper scripts, all these scripts are appended with the `dh_` string. In this case, `dh` called a helper called `dh_make` to build the debian package.
Another cue you have is this line:
```
dpkg-checkbuilddeps: Unmet build dependencies: debhelper (>= 7) dh-modaliases execstack
```
You need debhelper, dh-modaliases and execstack to build the package. debhelper suggests dh-make, and suggestions are normally installed. | 
Install your driver though Software center.
>
> Ubuntu software center > Edit menu > Software sources > Additional Drivers
>
>
>
OR
==
run these commands in your Terminal:
>
> sudo apt-get install build-essential linux-headers-generic
>
> sudo apt-get install fglrx
>
>
>
Then you will be able to use Catalyst Control Center. |
41,688,180 | Without concat strings or `if` conditionals and such, use arithmetics one-liner. Preferably written in Python please.
---
Background of the story: a legacy system requires a listening port last digit ends in [0-4] so [5-9] is reserved for a mirror TCP.
I wrote a deploy script which generates [idempotent random number](https://ansibledaily.com/idempotent-random-number/) but having trouble guarantee the last digit in [0-4]. Since Ansible & Jinja2 template language is limited so I don't want the code relies too much on hairy string operations and `if` conditions.
Once a idempotent random number is generated, I need a arithmetic function to *project* the number to another integer which the last digit is between 0 and 4 and still guarantee the idempotence | 2017/01/17 | [
"https://Stackoverflow.com/questions/41688180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41948/"
] | Here's one way to do it with `random.sample` and `mod`:
```
>>> import random
>>> [i for i in random.sample(range(100), 100) if i%10<5]
[24, 23, 62, 90, 80, 12, 4, 30, 43, 92, 21, 33, 41, 63, 52, 44, 81, 61, 31, 70, 73, 20, 0, 74, 2, 84, 11, 53, 13, 42, 50, 64, 60, 32, 71, 34, 72, 51, 1, 22, 91, 94, 40, 14, 82, 93, 3, 83, 54, 10]
```
You can use `next` and a gen. exp to generate a single number:
```
>>> gen = (i for i in random.sample(range(101), 101) if i%10<5) # include 100 in sample
>>> next(gen)
72
>>> next(gen)
84
>>> next(gen)
51
>>> next(gen)
71
>>> next(gen)
34
>>> next(gen)
40
``` | If you don't mind disallowing 100, you can simply generate two random numbers, one between 0 and 9, the other between 0 and 4, and combine them arithmetically.
```
port = 10 * random.randint(0,9) + random.randint(0,4)
```
This chooses any of the 50 such ports uniformly.
The simplest way to add 100 to the mix is to simply generate a random number between 0 and 50 (inclusive), and treat one of them as a proxy for 100, with the rest indicating that *another* random number be generated using the scheme above.
```
port = 100 if random.randint(0,50) == 50 else 10 * random.randint(0,9) + random.randint(0,4)
``` |
41,688,180 | Without concat strings or `if` conditionals and such, use arithmetics one-liner. Preferably written in Python please.
---
Background of the story: a legacy system requires a listening port last digit ends in [0-4] so [5-9] is reserved for a mirror TCP.
I wrote a deploy script which generates [idempotent random number](https://ansibledaily.com/idempotent-random-number/) but having trouble guarantee the last digit in [0-4]. Since Ansible & Jinja2 template language is limited so I don't want the code relies too much on hairy string operations and `if` conditions.
Once a idempotent random number is generated, I need a arithmetic function to *project* the number to another integer which the last digit is between 0 and 4 and still guarantee the idempotence | 2017/01/17 | [
"https://Stackoverflow.com/questions/41688180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41948/"
] | After some discussion in the comments, if you've randomly selected a number `x` in range(0,50), you can map it to {0,1,2,3,4,10,11,...} like this:
```
y = 10*(x//5) + x % 5
```
For example:
```
In [8]: out = [10 * (x//5) + x % 5 for x in range(50)]
In [9]: out[:10]
Out[9]: [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
In [10]: out[-10:]
Out[10]: [80, 81, 82, 83, 84, 90, 91, 92, 93, 94]
```
This will turn any number you've generated in the [0,50) range into one satisfying your < 5 mod 10 criterion. | Here's one way to do it with `random.sample` and `mod`:
```
>>> import random
>>> [i for i in random.sample(range(100), 100) if i%10<5]
[24, 23, 62, 90, 80, 12, 4, 30, 43, 92, 21, 33, 41, 63, 52, 44, 81, 61, 31, 70, 73, 20, 0, 74, 2, 84, 11, 53, 13, 42, 50, 64, 60, 32, 71, 34, 72, 51, 1, 22, 91, 94, 40, 14, 82, 93, 3, 83, 54, 10]
```
You can use `next` and a gen. exp to generate a single number:
```
>>> gen = (i for i in random.sample(range(101), 101) if i%10<5) # include 100 in sample
>>> next(gen)
72
>>> next(gen)
84
>>> next(gen)
51
>>> next(gen)
71
>>> next(gen)
34
>>> next(gen)
40
``` |
41,688,180 | Without concat strings or `if` conditionals and such, use arithmetics one-liner. Preferably written in Python please.
---
Background of the story: a legacy system requires a listening port last digit ends in [0-4] so [5-9] is reserved for a mirror TCP.
I wrote a deploy script which generates [idempotent random number](https://ansibledaily.com/idempotent-random-number/) but having trouble guarantee the last digit in [0-4]. Since Ansible & Jinja2 template language is limited so I don't want the code relies too much on hairy string operations and `if` conditions.
Once a idempotent random number is generated, I need a arithmetic function to *project* the number to another integer which the last digit is between 0 and 4 and still guarantee the idempotence | 2017/01/17 | [
"https://Stackoverflow.com/questions/41688180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41948/"
] | After some discussion in the comments, if you've randomly selected a number `x` in range(0,50), you can map it to {0,1,2,3,4,10,11,...} like this:
```
y = 10*(x//5) + x % 5
```
For example:
```
In [8]: out = [10 * (x//5) + x % 5 for x in range(50)]
In [9]: out[:10]
Out[9]: [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
In [10]: out[-10:]
Out[10]: [80, 81, 82, 83, 84, 90, 91, 92, 93, 94]
```
This will turn any number you've generated in the [0,50) range into one satisfying your < 5 mod 10 criterion. | If you don't mind disallowing 100, you can simply generate two random numbers, one between 0 and 9, the other between 0 and 4, and combine them arithmetically.
```
port = 10 * random.randint(0,9) + random.randint(0,4)
```
This chooses any of the 50 such ports uniformly.
The simplest way to add 100 to the mix is to simply generate a random number between 0 and 50 (inclusive), and treat one of them as a proxy for 100, with the rest indicating that *another* random number be generated using the scheme above.
```
port = 100 if random.randint(0,50) == 50 else 10 * random.randint(0,9) + random.randint(0,4)
``` |
198,726 | I'm responsible for several (rather small) programs, which share a lot of code via different libraries. I'm wondering what the best repository layout is to develop the different prorgrams (and libraries), and keep the libraries in sync across all the programs.
For the sake of argument let's say there are two programs with two libraries:
* Program1
+ Library1
+ Library2
* Program2
+ Library1
+ Library2
Naturally, bug fixes and enhancements for the libraries should (eventually) merge to all programs. Since the libraries are being worked on while working on the different programs, using [externals definitions](http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html) seems out of the question.
So I thought to treat my libraries at all but one place as [vendor branches](http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html) but I'm not sure what the best layout for this would be.
I was thinking something along the lines of:
* Libraries
+ Library1 (ancestor)
+ Library2 (ancestor)
* Program1
+ Program1 code
+ Library1 (vendor branch)
+ Library2 (vendor branch)
* ...
Then say when developing Program1 some changes are made for Library2, I merge them back to the Libraries part of the repository, and merge them from there to all other programs when desired.
Merging to the other programs can't always happen immediately, the people working on Program2 could be close to a release and rather finish that first, create a tag, and only then update all libraries.
I'm a bit concerned this will result in many merges and a bit of a maintenance headache after a while but I don't really see a much better solution.
Then again, this seems a rather common use case to me, so I thought I'd just ask the stackoverflow community, what's the best repository layout to achieve this? | 2008/10/13 | [
"https://Stackoverflow.com/questions/198726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5822/"
] | Well, I guess I disagree that externals are out of the question. I've had a similar problem in the past. I solved it using the svn property externals.
Create your library repositories:
```
svnadmin create /path/library1
svnadmin create /path/library2
...
```
Create client repositories:
```
svnadmin create /path/program1
svnadmin create /path/program2
...
```
Now declare the libraries as external within the program repositories:
```
cd /path/program1
svn propset svn:externals "library1 svnpath://wherever/library1/trunk/" .
svn propset svn:externals "library2 svnpath://wherever2/library2/trunk/" .
```
Now then you can make changes to programs 1 & 2 and making commits at the root of those projects doesn't affect the libraries... but, if you needed to make changes to the libraries you can. Then if and only if you have write permissions to the library repositories you could commit those changes too - but only from the library's subdirectory.
I.e. this doesn't make a commit to the libraries...
```
... make a change in /path/program1/library1 ...
cd /path/program1
svn commit -m "some change"
```
This commits the change made in the library above:
```
cd /path/program1/library1
svn commit -m "change to library code"
``` | Why does the source for the library have to exist in the program tree. Compile your libraries separately and link them into your programs. |
66,047,188 | So I am making a Discord bot that DMs mod-type roles when someone goes against the rules. This is my first discord bot, and have really just been going off the example on GitHub. I can't seem to find how to check a role or DM everyone in a role. I found stuff like
```
if message.author.server_privileges("kick_members"):
```
And stuff for checking the role. Although it always says "member has no attribute 'server\_privileges" or something like that. Anyways, I was hoping you guys could help me. These are the last things I need to finish. Here's my code:
```
class MyClient(discord.Client):
async def on_ready(self):
print("")
print('Logged on as', self.user)
async def on_message(self, message):
reasons = []
# don't respond to ourselves
if message.author == self.user:
return
if CheckBot.susCheck(self, message.content, susWords):
reasons.append("Being sus")
# DM staff, admins, and headstaff
report = "Caught " + str(message.author) + " being sus with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
if CheckBot.badCheck(self, message.content, badWords):
reasons.append("Saying bad words")
# DM staff, admins and headstaff
report = "Caught " + str(message.author) + " saying bad words with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
if #Check if message author has certain role:
if CheckBot.spamCheck(self, message.content, 100000000000000000):
reasons.append("Spam")
# DM staff, admins, and headstaff
report = "Caught " + str(message.author) + " spamming with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
else:
if CheckBot.spamCheck(self, message.content, 55):
reasons.append("Spam")
# DM staff, admins, owner, and headstaff
report = "Caught " + str(message.author) + "spamming with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
```
CheckBot is a class I made, that contains the functions that check if someone is going against the rules. Anything you recommend would be great, and helpful. | 2021/02/04 | [
"https://Stackoverflow.com/questions/66047188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15145476/"
] | You could probably:
```
static int crt = -1;
static readonly IReadOnlyList<A> Items = Enumerable.Range(1, 15).Select(i => new A()).ToList();
static readonly int itemsCount = Items.Count;
static readonly int maxItemCount = itemsCount * 100;
static A GetInstance()
{
int newIndex;
while (true)
{
newIndex = Interlocked.Increment(ref crt);
if (newIndex >= itemsCount)
{
while (newIndex >= itemsCount && Interlocked.CompareExchange(ref crt, -1, newIndex) != newIndex)
{
// There is an implicit memory barrier caused by the Interlockd.CompareExchange around the
// next line
// See for example https://afana.me/archive/2015/07/10/memory-barriers-in-dot-net.aspx/
// A full memory barrier is the strongest and interesting one. At least all of the following generate a full memory barrier implicitly:
// Interlocked class mehods
newIndex = crt;
}
continue;
}
break;
}
var instance = Items[newIndex % itemsCount];
//Console.WriteLine($"{DateTime.Now.Ticks}, {Guid.NewGuid()}, Got instance: {instance.ID}");
return instance;
}
```
But I have to say the truth... I'm not sure if it is correct (it should be), and explaining it is hard, and if anyone touches it in any way it will break.
The basic idea is to have a "low" ceiling for `crt` (we don't want to overflow, it would break everything... so we want to keep veeeeeery far from `int.MaxValue`, or you could use `uint`).
The maximum possible value is:
```
maxItemCount = (int.MaxValue - MaximumNumberOfThreads) / itemsCount * itemsCount;
```
The `/ itemsCount * itemsCount` is because we want the rounds to be equally distributed. In the example I give I use a probably much lower number (`itemsCount * 100`) because lowering this ceiling will only cause the reset more often, but the reset isn't so much slow that it is truly important (it depends on what you are doing on the threads. If they are very small threads that only use cpu then the reset is slow, but if not then it isn't).
Then when we overflow this ceiling we try to move it back to `-1` (our starting point). We know that at the same time other bad bad threads could `Interlocked.Increment` it and create a race on this reset. Thanks to the `Interlocked.CompareExchange` only one thread can successfully reset the counter, but the other racing threads will immediately see this and break from their attempts.
Mmmh... The `if` can be rewritten as:
```
if (newIndex >= itemsCount)
{
int newIndex2;
while (newIndex >= itemsCount && (newIndex2 = Interlocked.CompareExchange(ref crt, 0, newIndex)) != newIndex)
{
// If the Interlocked.CompareExchange is successfull, the while will end and so we won't be here,
// if it fails, newIndex2 is the current value of crt
newIndex = newIndex2;
}
continue;
}
``` | ~~No, the [`Interlocked`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked) class offers no mechanism that would allow you to restore an `Int32` value back to zero in case it overflows. The reason is that it is possible for two threads to invoke concurrently the `var newIndex = Interlocked.Increment(ref crt);` statement, in which case both with overflow the counter, and then none will succeed in updating the value back to zero. This functionality is just beyond the capabilities of the `Interlocked` class. To make such complex operations atomic you'll need to use some other synchronization mechanism, like a `lock`.~~
---
**Update:** xanatos's [answer](https://stackoverflow.com/a/66050998/11178549) proves that the above statement is wrong. It is also proven wrong by the answers of [this](https://stackoverflow.com/questions/10034289/how-should-i-increment-a-number-for-a-round-robin-threading-scenario-with-least "How should I increment a number for a round robin threading scenario with least contention?") 9-year old question. Below are two implementation of an `InterlockedIncrementRoundRobin` method. The first is a simplified version of [this](https://stackoverflow.com/questions/10034289/how-should-i-increment-a-number-for-a-round-robin-threading-scenario-with-least/41045356#41045356) answer, by Alex Sorokoletov:
```
public static int InterlockedRoundRobinIncrement(ref int location, int modulo)
{
// Arguments validation omitted (the modulo should be a positive number)
uint current = unchecked((uint)Interlocked.Increment(ref location));
return (int)(current % modulo);
}
```
This implementation is very efficient, but it has the drawback that the backing `int` value is not directly usable, since it circles through the whole range of the `Int32` type (including negative values). The usable information comes by the return value of the method itself, which is guaranteed to be in the range `[0..modulo]`. If you want to read the current value without incrementing it, you would need another similar method that does the same `int -> uint -> int` conversion:
```
public static int InterlockedRoundRobinRead(ref int location, int modulo)
{
uint current = unchecked((uint)Volatile.Read(ref location));
return (int)(current % modulo);
}
```
It also has the drawback that once every 4,294,967,296 increments, and unless the `modulo` is a power of 2, it returns a `0` value prematurely, before having reached the `modulo - 1` value. In other words the rollover logic is technically flawed. This may or may not be a big issue, depending on the application.
The second implementation is a modified version of xanatos's [algorithm](https://stackoverflow.com/a/66050998/11178549):
```
public static int InterlockedRoundRobinIncrement(ref int location, int modulo)
{
// Arguments validation omitted (the modulo should be a positive number)
while (true)
{
int current = Interlocked.Increment(ref location);
if (current >= 0 && current < modulo) return current;
// Overflow. Try to zero the number.
while (true)
{
int current2 = Interlocked.CompareExchange(ref location, 0, current);
if (current2 == current) return 0; // Success
current = current2;
if (current >= 0 && current < modulo)
{
break; // Another thread zeroed the number. Retry increment.
}
}
}
}
```
This is slightly less efficient (especially for small `modulo` values), because once in a while an `Interlocked.Increment` operation results to an out-of-range value, and the value is rejected and the operation repeated. It does have the advantage though that the backing `int` value remains in the `[0..modulo]` range, except for some very brief time spans, during some of this method's invocations. |
66,047,188 | So I am making a Discord bot that DMs mod-type roles when someone goes against the rules. This is my first discord bot, and have really just been going off the example on GitHub. I can't seem to find how to check a role or DM everyone in a role. I found stuff like
```
if message.author.server_privileges("kick_members"):
```
And stuff for checking the role. Although it always says "member has no attribute 'server\_privileges" or something like that. Anyways, I was hoping you guys could help me. These are the last things I need to finish. Here's my code:
```
class MyClient(discord.Client):
async def on_ready(self):
print("")
print('Logged on as', self.user)
async def on_message(self, message):
reasons = []
# don't respond to ourselves
if message.author == self.user:
return
if CheckBot.susCheck(self, message.content, susWords):
reasons.append("Being sus")
# DM staff, admins, and headstaff
report = "Caught " + str(message.author) + " being sus with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
if CheckBot.badCheck(self, message.content, badWords):
reasons.append("Saying bad words")
# DM staff, admins and headstaff
report = "Caught " + str(message.author) + " saying bad words with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
if #Check if message author has certain role:
if CheckBot.spamCheck(self, message.content, 100000000000000000):
reasons.append("Spam")
# DM staff, admins, and headstaff
report = "Caught " + str(message.author) + " spamming with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
else:
if CheckBot.spamCheck(self, message.content, 55):
reasons.append("Spam")
# DM staff, admins, owner, and headstaff
report = "Caught " + str(message.author) + "spamming with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
```
CheckBot is a class I made, that contains the functions that check if someone is going against the rules. Anything you recommend would be great, and helpful. | 2021/02/04 | [
"https://Stackoverflow.com/questions/66047188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15145476/"
] | ~~No, the [`Interlocked`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked) class offers no mechanism that would allow you to restore an `Int32` value back to zero in case it overflows. The reason is that it is possible for two threads to invoke concurrently the `var newIndex = Interlocked.Increment(ref crt);` statement, in which case both with overflow the counter, and then none will succeed in updating the value back to zero. This functionality is just beyond the capabilities of the `Interlocked` class. To make such complex operations atomic you'll need to use some other synchronization mechanism, like a `lock`.~~
---
**Update:** xanatos's [answer](https://stackoverflow.com/a/66050998/11178549) proves that the above statement is wrong. It is also proven wrong by the answers of [this](https://stackoverflow.com/questions/10034289/how-should-i-increment-a-number-for-a-round-robin-threading-scenario-with-least "How should I increment a number for a round robin threading scenario with least contention?") 9-year old question. Below are two implementation of an `InterlockedIncrementRoundRobin` method. The first is a simplified version of [this](https://stackoverflow.com/questions/10034289/how-should-i-increment-a-number-for-a-round-robin-threading-scenario-with-least/41045356#41045356) answer, by Alex Sorokoletov:
```
public static int InterlockedRoundRobinIncrement(ref int location, int modulo)
{
// Arguments validation omitted (the modulo should be a positive number)
uint current = unchecked((uint)Interlocked.Increment(ref location));
return (int)(current % modulo);
}
```
This implementation is very efficient, but it has the drawback that the backing `int` value is not directly usable, since it circles through the whole range of the `Int32` type (including negative values). The usable information comes by the return value of the method itself, which is guaranteed to be in the range `[0..modulo]`. If you want to read the current value without incrementing it, you would need another similar method that does the same `int -> uint -> int` conversion:
```
public static int InterlockedRoundRobinRead(ref int location, int modulo)
{
uint current = unchecked((uint)Volatile.Read(ref location));
return (int)(current % modulo);
}
```
It also has the drawback that once every 4,294,967,296 increments, and unless the `modulo` is a power of 2, it returns a `0` value prematurely, before having reached the `modulo - 1` value. In other words the rollover logic is technically flawed. This may or may not be a big issue, depending on the application.
The second implementation is a modified version of xanatos's [algorithm](https://stackoverflow.com/a/66050998/11178549):
```
public static int InterlockedRoundRobinIncrement(ref int location, int modulo)
{
// Arguments validation omitted (the modulo should be a positive number)
while (true)
{
int current = Interlocked.Increment(ref location);
if (current >= 0 && current < modulo) return current;
// Overflow. Try to zero the number.
while (true)
{
int current2 = Interlocked.CompareExchange(ref location, 0, current);
if (current2 == current) return 0; // Success
current = current2;
if (current >= 0 && current < modulo)
{
break; // Another thread zeroed the number. Retry increment.
}
}
}
}
```
This is slightly less efficient (especially for small `modulo` values), because once in a while an `Interlocked.Increment` operation results to an out-of-range value, and the value is rejected and the operation repeated. It does have the advantage though that the backing `int` value remains in the `[0..modulo]` range, except for some very brief time spans, during some of this method's invocations. | An alternative to using CompareExchange would be to simply let the values overflow.
I have tested this and could not prove it wrong (so far), but of course that does not mean that it isn't.
```
//this incurs some cost, but "should" ensure that the int range
// is mapped to the unit range (int.MinValue is mapped to 0 in the uint range)
static ulong toPositive(int i) => (uint)1 + long.MaxValue + (uint)i;
static A GetInstance()
{
//this seems to overflow safely without unchecked
var newCounter = Interlocked.Increment(ref crt);
//convert the counter to a list index, that is map the unsigned value
//to a signed range and get the value modulus the itemCount value
var newIndex = (int)(toPositive(newCounter) % (ulong)itemsCount);
var instance = Items[newIndex];
//Console.WriteLine($"{DateTime.Now.Ticks}, Got instance: {instance.ID}");
return instance;
}
```
PS: Another part of the xy problem part of my question: At a friend's suggestion I am currently investigating using a LinkedList or something similar (with locks) to achieve the same purpose. |
66,047,188 | So I am making a Discord bot that DMs mod-type roles when someone goes against the rules. This is my first discord bot, and have really just been going off the example on GitHub. I can't seem to find how to check a role or DM everyone in a role. I found stuff like
```
if message.author.server_privileges("kick_members"):
```
And stuff for checking the role. Although it always says "member has no attribute 'server\_privileges" or something like that. Anyways, I was hoping you guys could help me. These are the last things I need to finish. Here's my code:
```
class MyClient(discord.Client):
async def on_ready(self):
print("")
print('Logged on as', self.user)
async def on_message(self, message):
reasons = []
# don't respond to ourselves
if message.author == self.user:
return
if CheckBot.susCheck(self, message.content, susWords):
reasons.append("Being sus")
# DM staff, admins, and headstaff
report = "Caught " + str(message.author) + " being sus with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
if CheckBot.badCheck(self, message.content, badWords):
reasons.append("Saying bad words")
# DM staff, admins and headstaff
report = "Caught " + str(message.author) + " saying bad words with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
if #Check if message author has certain role:
if CheckBot.spamCheck(self, message.content, 100000000000000000):
reasons.append("Spam")
# DM staff, admins, and headstaff
report = "Caught " + str(message.author) + " spamming with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
else:
if CheckBot.spamCheck(self, message.content, 55):
reasons.append("Spam")
# DM staff, admins, owner, and headstaff
report = "Caught " + str(message.author) + "spamming with the following message: \n" + message.content
print("")
print("####################-END-####################")
print("")
print(report)
```
CheckBot is a class I made, that contains the functions that check if someone is going against the rules. Anything you recommend would be great, and helpful. | 2021/02/04 | [
"https://Stackoverflow.com/questions/66047188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15145476/"
] | You could probably:
```
static int crt = -1;
static readonly IReadOnlyList<A> Items = Enumerable.Range(1, 15).Select(i => new A()).ToList();
static readonly int itemsCount = Items.Count;
static readonly int maxItemCount = itemsCount * 100;
static A GetInstance()
{
int newIndex;
while (true)
{
newIndex = Interlocked.Increment(ref crt);
if (newIndex >= itemsCount)
{
while (newIndex >= itemsCount && Interlocked.CompareExchange(ref crt, -1, newIndex) != newIndex)
{
// There is an implicit memory barrier caused by the Interlockd.CompareExchange around the
// next line
// See for example https://afana.me/archive/2015/07/10/memory-barriers-in-dot-net.aspx/
// A full memory barrier is the strongest and interesting one. At least all of the following generate a full memory barrier implicitly:
// Interlocked class mehods
newIndex = crt;
}
continue;
}
break;
}
var instance = Items[newIndex % itemsCount];
//Console.WriteLine($"{DateTime.Now.Ticks}, {Guid.NewGuid()}, Got instance: {instance.ID}");
return instance;
}
```
But I have to say the truth... I'm not sure if it is correct (it should be), and explaining it is hard, and if anyone touches it in any way it will break.
The basic idea is to have a "low" ceiling for `crt` (we don't want to overflow, it would break everything... so we want to keep veeeeeery far from `int.MaxValue`, or you could use `uint`).
The maximum possible value is:
```
maxItemCount = (int.MaxValue - MaximumNumberOfThreads) / itemsCount * itemsCount;
```
The `/ itemsCount * itemsCount` is because we want the rounds to be equally distributed. In the example I give I use a probably much lower number (`itemsCount * 100`) because lowering this ceiling will only cause the reset more often, but the reset isn't so much slow that it is truly important (it depends on what you are doing on the threads. If they are very small threads that only use cpu then the reset is slow, but if not then it isn't).
Then when we overflow this ceiling we try to move it back to `-1` (our starting point). We know that at the same time other bad bad threads could `Interlocked.Increment` it and create a race on this reset. Thanks to the `Interlocked.CompareExchange` only one thread can successfully reset the counter, but the other racing threads will immediately see this and break from their attempts.
Mmmh... The `if` can be rewritten as:
```
if (newIndex >= itemsCount)
{
int newIndex2;
while (newIndex >= itemsCount && (newIndex2 = Interlocked.CompareExchange(ref crt, 0, newIndex)) != newIndex)
{
// If the Interlocked.CompareExchange is successfull, the while will end and so we won't be here,
// if it fails, newIndex2 is the current value of crt
newIndex = newIndex2;
}
continue;
}
``` | An alternative to using CompareExchange would be to simply let the values overflow.
I have tested this and could not prove it wrong (so far), but of course that does not mean that it isn't.
```
//this incurs some cost, but "should" ensure that the int range
// is mapped to the unit range (int.MinValue is mapped to 0 in the uint range)
static ulong toPositive(int i) => (uint)1 + long.MaxValue + (uint)i;
static A GetInstance()
{
//this seems to overflow safely without unchecked
var newCounter = Interlocked.Increment(ref crt);
//convert the counter to a list index, that is map the unsigned value
//to a signed range and get the value modulus the itemCount value
var newIndex = (int)(toPositive(newCounter) % (ulong)itemsCount);
var instance = Items[newIndex];
//Console.WriteLine($"{DateTime.Now.Ticks}, Got instance: {instance.ID}");
return instance;
}
```
PS: Another part of the xy problem part of my question: At a friend's suggestion I am currently investigating using a LinkedList or something similar (with locks) to achieve the same purpose. |
10,038,598 | Main question is what are the implications of allowing the this keyword to be modified in regards to usefulness and memory; and why is this allowed in the C# language specifications?
The other questions/subparts can be answered or not if choose to do so. I thought answers to them would help clarify the answer to the main question.
I ran across this as an answer to [What's the strangest corner case you've seen in C# or .NET?](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-sharp-or-net)
```
public struct Teaser
{
public void Foo()
{
this = new Teaser();
}
}
```
I've been trying to wrap my head around why the C# language specifications would even allow this. **Sub-part 1**. is there anything that would justify having **this** be modifiable? Is it every useful?
One of the comments to that answer was
>
> From CLR via C#: The reason they made this is because you
> can call the parameterless constructor of a struct in another
> constructor. If you only want to initialize one value of a struct and
> want the other values to be zero/null (default), you can write public
> Foo(int bar){this = new Foo(); specialVar = bar;}. This is not
> efficient and not really justified (specialVar is assigned twice), but
> just FYI. (That's the reason given in the book, I don't know why we
> shouldn't just do public Foo(int bar) : this())
>
>
>
**Sub-part 2.** I'm not sure I follow that reasoning. Can someone clarify what he meant? Maybe a concrete example of how it would be used?
EDIT (Disregard stack or heap main point is in regards to memory release or garbage collection. Instead of the int[] you could replace that with 262144 public int fields)
Also from my understanding structs are created on the stack as opposed to the heap if this struct were to have a 1 Mb byte array field initialized as so
```
public int[] Mb = new int[262144];
```
**Sub-part 3.** does this ever get removed from the stack when Foo is called? To me it seems since the struct never went out of scope it would not be removed from the stack. Don't have time tonight to create a test case but maybe I will for this one tomorrow.
In the below code
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
**Sub-part 4**. Are t1 and tPlaceHolder occupying the same or different address space?
Sorry to bring up a 3 year old post but this one has really got my head scratching.
FYI first question on stackoverflow so if I got something wrong with the question kindly post a comment and I will edit.
After 2 days I'll put a bounty of 50 on this question even if I have a winner chosen in my mind already as I think the answer will require a reasonable amount of work to explain the questions. | 2012/04/06 | [
"https://Stackoverflow.com/questions/10038598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246051/"
] | First of all, I think you should start by examining if you're even asking the right question. Perhaps we should be asking, "Why would C# **not** allow assignment to `this` in a struct?"
Assigning to the `this` keyword in a reference type is potentially dangerous: you are overwriting a reference to the object who's method you are running; you could even be doing so within the constructor that is initializing that reference. Its not clear what the behavior of that ought to be. To avoid having to figure that out, since it is not generally useful, it's not allowed by the spec (or compiler).
Assigning to the `this` keyword in a value type, however, is well defined. Assignment of value types is a copy operation. The value of each field is recursively copied over from right to left side of the assignment. This is a perfectly safe operation on a structure, even in a constructor, because the original copy of the structure is still present, you are just changing its data. It is exactly equivalent to manually setting each field in the struct. Why should the spec or compiler forbid an operation that is well-defined and safe?
This, by the way, answers one of your sub-questions. Value type assignment is a deep copy operation, not a reference copy. Given this code:
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
You have allocated two copies of your `Teaser` structure, and copied the values of the fields in the first into the fields in the second. This is the nature of value types: two types that have identical fields are identical, just like two `int` variables that both contain 10 are identical, regardless of where they are "in memory".
Also, this is important and worth repeating: careful making assumptions about what goes on "the stack" vs "the heap". Value types end up on the heap all the time, depending on the context in which they are used. Short-lived (locally scoped) structs that are not closed over or otherwise lifted out of their scope are quite likely to get allocated onto the stack. But that is an *unimportant [implementation detail](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx)* that you should neither care about nor rely on. The key is that they are value types, and behave as such.
As far as how useful assignment to `this` really is: not very. Specific use cases have been mentioned already. You can use it to mostly-initialize a structure with default values but specify a small number. Since you are required to set all fields before your constructor returns, this can save a lot of redundant code:
```
public struct Foo
{
// Fields etc here.
public Foo(int a)
{
this = new Foo();
this.a = a;
}
}
```
It can also be used to perform a quick swap operation:
```
public void SwapValues(MyStruct other)
{
var temp = other;
other = this;
this = temp;
}
```
Beyond that, its just an interesting side-effect of the language and the way that structures and value types are implemented that you will most likely never need to know about. | Having this assignable allows for 'advanced' corner cases with structs. One example i found was a swap method:
```
struct Foo
{
void Swap(ref Foo other)
{
Foo temp = this;
this = other;
other = temp;
}
}
```
I would strongly argue against this use since it violates the default 'desired' nature of a struct which is immutability. The reason for having this option around is arguably unclear.
Now when it comes to structs themselfs. They differ from classes in a few ways:
* They can live on the stack rather than the managed heap.
* They can be marshaled back to unmanaged code.
* They can not be assigned to a NULL value.
For a complete overview, see: <http://www.jaggersoft.com/pubs/StructsVsClasses.htm>
Relative to your question is whether your struct lives on the stack or the heap. This is determined by the allocation location of a struct. If the struct is a member of a class, it will be allocated on the heap. Else if a struct is allocated directly, it will be allocated on the heap (Actually this is only a part of the picture. This whole will get pretty complex once starting to talk about closures introduced in C# 2.0 but for now it's sufficient in order to answer your question).
An array in .NET is be default allocated on the heap (this behavior is not consistent when using unsafe code and the stackalloc keyword). Going back to the explanation above, that would indicate that the struct instances also gets allocated on the heap. In fact, an easy way of proving this is by allocating an array of 1 mb in size and observe how NO stackoverflow exception is thrown.
The lifetime for an instance on the stack is determined by it's scope. This is different from an instance on the manager heap which lifetime is determined by the garbage collector (and whether there are still references towards that instance). You can ensure that anything on the stack lives as long as it's within scope. Allocating an instance on the stack and calling a method wont deallocate that instance until that instance gets out of scope (by default when the method wherein that instance was declared ends).
A struct cant have managed references towards it (pointers are possible in unmanaged code). When working with structs on the stack in C#, you basically have a label towards an instance rather than a reference. Assigning one struct to another simply copies the underlying data. You can see references as structs. Naively put, a reference is nothing more than a struct containing a pointer to a certain part in memory. When assigning one reference to the other, the pointer data gets copied.
```
// declare 2 references to instances on the managed heap
var c1 = new MyClass();
var c2 = new MyClass();
// declare 2 labels to instances on the stack
var s1 = new MyStruct();
var s2 = new MyStruct();
c1 = c2; // copies the reference data which is the pointer internally, c1 and c2 both point to the same instance
s1 = s2; // copies the data which is the struct internally, c1 and c2 both point to their own instance with the same data
``` |
10,038,598 | Main question is what are the implications of allowing the this keyword to be modified in regards to usefulness and memory; and why is this allowed in the C# language specifications?
The other questions/subparts can be answered or not if choose to do so. I thought answers to them would help clarify the answer to the main question.
I ran across this as an answer to [What's the strangest corner case you've seen in C# or .NET?](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-sharp-or-net)
```
public struct Teaser
{
public void Foo()
{
this = new Teaser();
}
}
```
I've been trying to wrap my head around why the C# language specifications would even allow this. **Sub-part 1**. is there anything that would justify having **this** be modifiable? Is it every useful?
One of the comments to that answer was
>
> From CLR via C#: The reason they made this is because you
> can call the parameterless constructor of a struct in another
> constructor. If you only want to initialize one value of a struct and
> want the other values to be zero/null (default), you can write public
> Foo(int bar){this = new Foo(); specialVar = bar;}. This is not
> efficient and not really justified (specialVar is assigned twice), but
> just FYI. (That's the reason given in the book, I don't know why we
> shouldn't just do public Foo(int bar) : this())
>
>
>
**Sub-part 2.** I'm not sure I follow that reasoning. Can someone clarify what he meant? Maybe a concrete example of how it would be used?
EDIT (Disregard stack or heap main point is in regards to memory release or garbage collection. Instead of the int[] you could replace that with 262144 public int fields)
Also from my understanding structs are created on the stack as opposed to the heap if this struct were to have a 1 Mb byte array field initialized as so
```
public int[] Mb = new int[262144];
```
**Sub-part 3.** does this ever get removed from the stack when Foo is called? To me it seems since the struct never went out of scope it would not be removed from the stack. Don't have time tonight to create a test case but maybe I will for this one tomorrow.
In the below code
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
**Sub-part 4**. Are t1 and tPlaceHolder occupying the same or different address space?
Sorry to bring up a 3 year old post but this one has really got my head scratching.
FYI first question on stackoverflow so if I got something wrong with the question kindly post a comment and I will edit.
After 2 days I'll put a bounty of 50 on this question even if I have a winner chosen in my mind already as I think the answer will require a reasonable amount of work to explain the questions. | 2012/04/06 | [
"https://Stackoverflow.com/questions/10038598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246051/"
] | Having this assignable allows for 'advanced' corner cases with structs. One example i found was a swap method:
```
struct Foo
{
void Swap(ref Foo other)
{
Foo temp = this;
this = other;
other = temp;
}
}
```
I would strongly argue against this use since it violates the default 'desired' nature of a struct which is immutability. The reason for having this option around is arguably unclear.
Now when it comes to structs themselfs. They differ from classes in a few ways:
* They can live on the stack rather than the managed heap.
* They can be marshaled back to unmanaged code.
* They can not be assigned to a NULL value.
For a complete overview, see: <http://www.jaggersoft.com/pubs/StructsVsClasses.htm>
Relative to your question is whether your struct lives on the stack or the heap. This is determined by the allocation location of a struct. If the struct is a member of a class, it will be allocated on the heap. Else if a struct is allocated directly, it will be allocated on the heap (Actually this is only a part of the picture. This whole will get pretty complex once starting to talk about closures introduced in C# 2.0 but for now it's sufficient in order to answer your question).
An array in .NET is be default allocated on the heap (this behavior is not consistent when using unsafe code and the stackalloc keyword). Going back to the explanation above, that would indicate that the struct instances also gets allocated on the heap. In fact, an easy way of proving this is by allocating an array of 1 mb in size and observe how NO stackoverflow exception is thrown.
The lifetime for an instance on the stack is determined by it's scope. This is different from an instance on the manager heap which lifetime is determined by the garbage collector (and whether there are still references towards that instance). You can ensure that anything on the stack lives as long as it's within scope. Allocating an instance on the stack and calling a method wont deallocate that instance until that instance gets out of scope (by default when the method wherein that instance was declared ends).
A struct cant have managed references towards it (pointers are possible in unmanaged code). When working with structs on the stack in C#, you basically have a label towards an instance rather than a reference. Assigning one struct to another simply copies the underlying data. You can see references as structs. Naively put, a reference is nothing more than a struct containing a pointer to a certain part in memory. When assigning one reference to the other, the pointer data gets copied.
```
// declare 2 references to instances on the managed heap
var c1 = new MyClass();
var c2 = new MyClass();
// declare 2 labels to instances on the stack
var s1 = new MyStruct();
var s2 = new MyStruct();
c1 = c2; // copies the reference data which is the pointer internally, c1 and c2 both point to the same instance
s1 = s2; // copies the data which is the struct internally, c1 and c2 both point to their own instance with the same data
``` | You can take advantage of *this* and mutate an immutable structure
```
public struct ImmutableData
{
private readonly int data;
private readonly string name;
public ImmutableData(int data, string name)
{
this.data = data;
this.name = name;
}
public int Data { get => data; }
public string Name { get => name; }
public void SetName(string newName)
{
// this wont work
// this.name = name;
// but this will
this = new ImmutableData(this.data, newName);
}
public override string ToString() => $"Data={data}, Name={name}";
}
class Program
{
static void Main(string[] args)
{
var X = new ImmutableData(100, "Jane");
X.SetName("Anne");
Debug.WriteLine(X);
// "Data=100, Name=Anne"
}
}
```
This is advantageous as you can implement `IXmlSerializable` and maintain the robustness of immutable structures, while allowing serialization (that happens one property at a time).
Just two methods in the above example to achieve this:
```
public void ReadXml(XmlReader reader)
{
var data = int.Parse(reader.GetAttribute("Data"));
var name = reader.GetAttribute("Name");
this = new ImmutableData(data, name);
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("Data", data.ToString());
writer.WriteAttributeString("Name", name);
}
```
which creates the followng xml file
```
<?xml version="1.0" encoding="utf-8"?>
<ImmutableData Data="100" Name="Anne" />
```
and can be read with
```
var xs = new XmlSerializer(typeof(ImmutableData));
var fs = File.OpenText("Store.xml");
var Y = (ImmutableData)xs.Deserialize(fs);
fs.Close();
``` |
10,038,598 | Main question is what are the implications of allowing the this keyword to be modified in regards to usefulness and memory; and why is this allowed in the C# language specifications?
The other questions/subparts can be answered or not if choose to do so. I thought answers to them would help clarify the answer to the main question.
I ran across this as an answer to [What's the strangest corner case you've seen in C# or .NET?](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-sharp-or-net)
```
public struct Teaser
{
public void Foo()
{
this = new Teaser();
}
}
```
I've been trying to wrap my head around why the C# language specifications would even allow this. **Sub-part 1**. is there anything that would justify having **this** be modifiable? Is it every useful?
One of the comments to that answer was
>
> From CLR via C#: The reason they made this is because you
> can call the parameterless constructor of a struct in another
> constructor. If you only want to initialize one value of a struct and
> want the other values to be zero/null (default), you can write public
> Foo(int bar){this = new Foo(); specialVar = bar;}. This is not
> efficient and not really justified (specialVar is assigned twice), but
> just FYI. (That's the reason given in the book, I don't know why we
> shouldn't just do public Foo(int bar) : this())
>
>
>
**Sub-part 2.** I'm not sure I follow that reasoning. Can someone clarify what he meant? Maybe a concrete example of how it would be used?
EDIT (Disregard stack or heap main point is in regards to memory release or garbage collection. Instead of the int[] you could replace that with 262144 public int fields)
Also from my understanding structs are created on the stack as opposed to the heap if this struct were to have a 1 Mb byte array field initialized as so
```
public int[] Mb = new int[262144];
```
**Sub-part 3.** does this ever get removed from the stack when Foo is called? To me it seems since the struct never went out of scope it would not be removed from the stack. Don't have time tonight to create a test case but maybe I will for this one tomorrow.
In the below code
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
**Sub-part 4**. Are t1 and tPlaceHolder occupying the same or different address space?
Sorry to bring up a 3 year old post but this one has really got my head scratching.
FYI first question on stackoverflow so if I got something wrong with the question kindly post a comment and I will edit.
After 2 days I'll put a bounty of 50 on this question even if I have a winner chosen in my mind already as I think the answer will require a reasonable amount of work to explain the questions. | 2012/04/06 | [
"https://Stackoverflow.com/questions/10038598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246051/"
] | Having this assignable allows for 'advanced' corner cases with structs. One example i found was a swap method:
```
struct Foo
{
void Swap(ref Foo other)
{
Foo temp = this;
this = other;
other = temp;
}
}
```
I would strongly argue against this use since it violates the default 'desired' nature of a struct which is immutability. The reason for having this option around is arguably unclear.
Now when it comes to structs themselfs. They differ from classes in a few ways:
* They can live on the stack rather than the managed heap.
* They can be marshaled back to unmanaged code.
* They can not be assigned to a NULL value.
For a complete overview, see: <http://www.jaggersoft.com/pubs/StructsVsClasses.htm>
Relative to your question is whether your struct lives on the stack or the heap. This is determined by the allocation location of a struct. If the struct is a member of a class, it will be allocated on the heap. Else if a struct is allocated directly, it will be allocated on the heap (Actually this is only a part of the picture. This whole will get pretty complex once starting to talk about closures introduced in C# 2.0 but for now it's sufficient in order to answer your question).
An array in .NET is be default allocated on the heap (this behavior is not consistent when using unsafe code and the stackalloc keyword). Going back to the explanation above, that would indicate that the struct instances also gets allocated on the heap. In fact, an easy way of proving this is by allocating an array of 1 mb in size and observe how NO stackoverflow exception is thrown.
The lifetime for an instance on the stack is determined by it's scope. This is different from an instance on the manager heap which lifetime is determined by the garbage collector (and whether there are still references towards that instance). You can ensure that anything on the stack lives as long as it's within scope. Allocating an instance on the stack and calling a method wont deallocate that instance until that instance gets out of scope (by default when the method wherein that instance was declared ends).
A struct cant have managed references towards it (pointers are possible in unmanaged code). When working with structs on the stack in C#, you basically have a label towards an instance rather than a reference. Assigning one struct to another simply copies the underlying data. You can see references as structs. Naively put, a reference is nothing more than a struct containing a pointer to a certain part in memory. When assigning one reference to the other, the pointer data gets copied.
```
// declare 2 references to instances on the managed heap
var c1 = new MyClass();
var c2 = new MyClass();
// declare 2 labels to instances on the stack
var s1 = new MyStruct();
var s2 = new MyStruct();
c1 = c2; // copies the reference data which is the pointer internally, c1 and c2 both point to the same instance
s1 = s2; // copies the data which is the struct internally, c1 and c2 both point to their own instance with the same data
``` | I came across this when I was looking up how `System.Guid` was implemented, because I had a similar scenario.
Basically, it does this (simplified):
```
struct Guid
{
Guid(string value)
{
this = Parse(value);
}
}
```
Which I think is a pretty neat solution. |
10,038,598 | Main question is what are the implications of allowing the this keyword to be modified in regards to usefulness and memory; and why is this allowed in the C# language specifications?
The other questions/subparts can be answered or not if choose to do so. I thought answers to them would help clarify the answer to the main question.
I ran across this as an answer to [What's the strangest corner case you've seen in C# or .NET?](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-sharp-or-net)
```
public struct Teaser
{
public void Foo()
{
this = new Teaser();
}
}
```
I've been trying to wrap my head around why the C# language specifications would even allow this. **Sub-part 1**. is there anything that would justify having **this** be modifiable? Is it every useful?
One of the comments to that answer was
>
> From CLR via C#: The reason they made this is because you
> can call the parameterless constructor of a struct in another
> constructor. If you only want to initialize one value of a struct and
> want the other values to be zero/null (default), you can write public
> Foo(int bar){this = new Foo(); specialVar = bar;}. This is not
> efficient and not really justified (specialVar is assigned twice), but
> just FYI. (That's the reason given in the book, I don't know why we
> shouldn't just do public Foo(int bar) : this())
>
>
>
**Sub-part 2.** I'm not sure I follow that reasoning. Can someone clarify what he meant? Maybe a concrete example of how it would be used?
EDIT (Disregard stack or heap main point is in regards to memory release or garbage collection. Instead of the int[] you could replace that with 262144 public int fields)
Also from my understanding structs are created on the stack as opposed to the heap if this struct were to have a 1 Mb byte array field initialized as so
```
public int[] Mb = new int[262144];
```
**Sub-part 3.** does this ever get removed from the stack when Foo is called? To me it seems since the struct never went out of scope it would not be removed from the stack. Don't have time tonight to create a test case but maybe I will for this one tomorrow.
In the below code
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
**Sub-part 4**. Are t1 and tPlaceHolder occupying the same or different address space?
Sorry to bring up a 3 year old post but this one has really got my head scratching.
FYI first question on stackoverflow so if I got something wrong with the question kindly post a comment and I will edit.
After 2 days I'll put a bounty of 50 on this question even if I have a winner chosen in my mind already as I think the answer will require a reasonable amount of work to explain the questions. | 2012/04/06 | [
"https://Stackoverflow.com/questions/10038598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246051/"
] | First of all, I think you should start by examining if you're even asking the right question. Perhaps we should be asking, "Why would C# **not** allow assignment to `this` in a struct?"
Assigning to the `this` keyword in a reference type is potentially dangerous: you are overwriting a reference to the object who's method you are running; you could even be doing so within the constructor that is initializing that reference. Its not clear what the behavior of that ought to be. To avoid having to figure that out, since it is not generally useful, it's not allowed by the spec (or compiler).
Assigning to the `this` keyword in a value type, however, is well defined. Assignment of value types is a copy operation. The value of each field is recursively copied over from right to left side of the assignment. This is a perfectly safe operation on a structure, even in a constructor, because the original copy of the structure is still present, you are just changing its data. It is exactly equivalent to manually setting each field in the struct. Why should the spec or compiler forbid an operation that is well-defined and safe?
This, by the way, answers one of your sub-questions. Value type assignment is a deep copy operation, not a reference copy. Given this code:
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
You have allocated two copies of your `Teaser` structure, and copied the values of the fields in the first into the fields in the second. This is the nature of value types: two types that have identical fields are identical, just like two `int` variables that both contain 10 are identical, regardless of where they are "in memory".
Also, this is important and worth repeating: careful making assumptions about what goes on "the stack" vs "the heap". Value types end up on the heap all the time, depending on the context in which they are used. Short-lived (locally scoped) structs that are not closed over or otherwise lifted out of their scope are quite likely to get allocated onto the stack. But that is an *unimportant [implementation detail](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx)* that you should neither care about nor rely on. The key is that they are value types, and behave as such.
As far as how useful assignment to `this` really is: not very. Specific use cases have been mentioned already. You can use it to mostly-initialize a structure with default values but specify a small number. Since you are required to set all fields before your constructor returns, this can save a lot of redundant code:
```
public struct Foo
{
// Fields etc here.
public Foo(int a)
{
this = new Foo();
this.a = a;
}
}
```
It can also be used to perform a quick swap operation:
```
public void SwapValues(MyStruct other)
{
var temp = other;
other = this;
this = temp;
}
```
Beyond that, its just an interesting side-effect of the language and the way that structures and value types are implemented that you will most likely never need to know about. | You can take advantage of *this* and mutate an immutable structure
```
public struct ImmutableData
{
private readonly int data;
private readonly string name;
public ImmutableData(int data, string name)
{
this.data = data;
this.name = name;
}
public int Data { get => data; }
public string Name { get => name; }
public void SetName(string newName)
{
// this wont work
// this.name = name;
// but this will
this = new ImmutableData(this.data, newName);
}
public override string ToString() => $"Data={data}, Name={name}";
}
class Program
{
static void Main(string[] args)
{
var X = new ImmutableData(100, "Jane");
X.SetName("Anne");
Debug.WriteLine(X);
// "Data=100, Name=Anne"
}
}
```
This is advantageous as you can implement `IXmlSerializable` and maintain the robustness of immutable structures, while allowing serialization (that happens one property at a time).
Just two methods in the above example to achieve this:
```
public void ReadXml(XmlReader reader)
{
var data = int.Parse(reader.GetAttribute("Data"));
var name = reader.GetAttribute("Name");
this = new ImmutableData(data, name);
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("Data", data.ToString());
writer.WriteAttributeString("Name", name);
}
```
which creates the followng xml file
```
<?xml version="1.0" encoding="utf-8"?>
<ImmutableData Data="100" Name="Anne" />
```
and can be read with
```
var xs = new XmlSerializer(typeof(ImmutableData));
var fs = File.OpenText("Store.xml");
var Y = (ImmutableData)xs.Deserialize(fs);
fs.Close();
``` |
10,038,598 | Main question is what are the implications of allowing the this keyword to be modified in regards to usefulness and memory; and why is this allowed in the C# language specifications?
The other questions/subparts can be answered or not if choose to do so. I thought answers to them would help clarify the answer to the main question.
I ran across this as an answer to [What's the strangest corner case you've seen in C# or .NET?](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-sharp-or-net)
```
public struct Teaser
{
public void Foo()
{
this = new Teaser();
}
}
```
I've been trying to wrap my head around why the C# language specifications would even allow this. **Sub-part 1**. is there anything that would justify having **this** be modifiable? Is it every useful?
One of the comments to that answer was
>
> From CLR via C#: The reason they made this is because you
> can call the parameterless constructor of a struct in another
> constructor. If you only want to initialize one value of a struct and
> want the other values to be zero/null (default), you can write public
> Foo(int bar){this = new Foo(); specialVar = bar;}. This is not
> efficient and not really justified (specialVar is assigned twice), but
> just FYI. (That's the reason given in the book, I don't know why we
> shouldn't just do public Foo(int bar) : this())
>
>
>
**Sub-part 2.** I'm not sure I follow that reasoning. Can someone clarify what he meant? Maybe a concrete example of how it would be used?
EDIT (Disregard stack or heap main point is in regards to memory release or garbage collection. Instead of the int[] you could replace that with 262144 public int fields)
Also from my understanding structs are created on the stack as opposed to the heap if this struct were to have a 1 Mb byte array field initialized as so
```
public int[] Mb = new int[262144];
```
**Sub-part 3.** does this ever get removed from the stack when Foo is called? To me it seems since the struct never went out of scope it would not be removed from the stack. Don't have time tonight to create a test case but maybe I will for this one tomorrow.
In the below code
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
**Sub-part 4**. Are t1 and tPlaceHolder occupying the same or different address space?
Sorry to bring up a 3 year old post but this one has really got my head scratching.
FYI first question on stackoverflow so if I got something wrong with the question kindly post a comment and I will edit.
After 2 days I'll put a bounty of 50 on this question even if I have a winner chosen in my mind already as I think the answer will require a reasonable amount of work to explain the questions. | 2012/04/06 | [
"https://Stackoverflow.com/questions/10038598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246051/"
] | First of all, I think you should start by examining if you're even asking the right question. Perhaps we should be asking, "Why would C# **not** allow assignment to `this` in a struct?"
Assigning to the `this` keyword in a reference type is potentially dangerous: you are overwriting a reference to the object who's method you are running; you could even be doing so within the constructor that is initializing that reference. Its not clear what the behavior of that ought to be. To avoid having to figure that out, since it is not generally useful, it's not allowed by the spec (or compiler).
Assigning to the `this` keyword in a value type, however, is well defined. Assignment of value types is a copy operation. The value of each field is recursively copied over from right to left side of the assignment. This is a perfectly safe operation on a structure, even in a constructor, because the original copy of the structure is still present, you are just changing its data. It is exactly equivalent to manually setting each field in the struct. Why should the spec or compiler forbid an operation that is well-defined and safe?
This, by the way, answers one of your sub-questions. Value type assignment is a deep copy operation, not a reference copy. Given this code:
```
Teaser t1 = new Teaser();
Teaser tPlaceHolder = t1;
t1.Foo();
```
You have allocated two copies of your `Teaser` structure, and copied the values of the fields in the first into the fields in the second. This is the nature of value types: two types that have identical fields are identical, just like two `int` variables that both contain 10 are identical, regardless of where they are "in memory".
Also, this is important and worth repeating: careful making assumptions about what goes on "the stack" vs "the heap". Value types end up on the heap all the time, depending on the context in which they are used. Short-lived (locally scoped) structs that are not closed over or otherwise lifted out of their scope are quite likely to get allocated onto the stack. But that is an *unimportant [implementation detail](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx)* that you should neither care about nor rely on. The key is that they are value types, and behave as such.
As far as how useful assignment to `this` really is: not very. Specific use cases have been mentioned already. You can use it to mostly-initialize a structure with default values but specify a small number. Since you are required to set all fields before your constructor returns, this can save a lot of redundant code:
```
public struct Foo
{
// Fields etc here.
public Foo(int a)
{
this = new Foo();
this.a = a;
}
}
```
It can also be used to perform a quick swap operation:
```
public void SwapValues(MyStruct other)
{
var temp = other;
other = this;
this = temp;
}
```
Beyond that, its just an interesting side-effect of the language and the way that structures and value types are implemented that you will most likely never need to know about. | I came across this when I was looking up how `System.Guid` was implemented, because I had a similar scenario.
Basically, it does this (simplified):
```
struct Guid
{
Guid(string value)
{
this = Parse(value);
}
}
```
Which I think is a pretty neat solution. |
58,806,685 | I'm doing a "live preview" of the post you can post on my website and when you type in the content section the preview doesn't break the line, it just goes on and on. Live version you can test: <https://sponge.rip/post>
```
<script type="text/javascript">
function update_preview() {
document.getElementById('preview_title').innerHTML = document.getElementById('title').value;
}
function update_content() {
document.getElementById("preview_content").innerHTML = document.getElementsByTagName("textarea")[0].value;
}
function preview() {
if (document.getElementById("preview").checked == true) {
var row = document.querySelectorAll('#row');
} else {
}
}
</script>
<div class="col-md-6">
<div class="post-holder">
<div class="post-item">
<div class="post-header">
<div class="title">
<h2 id="preview_title">title</h2>
<span class="author"><a href="/Tobias">Tobias</a></span>
<?php
$date = date("y-m-d");
echo "<time>$date</time>";
?>
</div>
</div>
<div class="post-body">
<p id="preview_content">content</p>
</div>
</div>
</div>
</div>
.main {
margin-top: 20px;
padding-bottom: 90px;
}
.post-holder {
margin-bottom: 15px;
}
.post-item {
background-color: #ffffff;
border-radius: 5px;
padding: 12px 12px 0;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15);
}
.post-item .post-header {
display: flex;
flex-wrap: wrap;
padding-bottom: 11px;
margin-bottom: 11px;
border-bottom: 1px solid rgba(160, 160, 160, 0.15);
}
.post-item .post-header span {
font-size: 12px;
font-weight: 600;
line-height: 1;
margin-left: 2px;
}
.post-item .post-header .title {
width: 90%;
padding-top: 2px;
}
.post-item .post-header .title h2 {
font-weight: 700;
font-size: 18px;
letter-spacing: 3px;
margin-bottom: 0;
line-height: 1;
}
.post-item .post-header .title .author a {
color: rgba(38, 38, 38, 0.75);
}
.post-body {
position: relative;
}
.post-body p {
margin-bottom: 15px;
padding-bottom: 10px;
}
```
The result should look like the home page: <https://sponge.rip/>
You can see some posts there were the text doesn't overflow the div | 2019/11/11 | [
"https://Stackoverflow.com/questions/58806685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12356923/"
] | You need a rich text editor to add line breaks. A basic textarea doesn't add html tags. Check out something like `tinymce` or [summernote](https://summernote.org/) or any of the other hundreds of text editors available on the internet | You could always convert line breaks to an html `<br />`. Something like this:
```
document.getElementById("preview_content").innerHTML = document.getElementsByTagName("textarea")[0].value.replace(/\r?\n/g, '<br />');
``` |
58,806,685 | I'm doing a "live preview" of the post you can post on my website and when you type in the content section the preview doesn't break the line, it just goes on and on. Live version you can test: <https://sponge.rip/post>
```
<script type="text/javascript">
function update_preview() {
document.getElementById('preview_title').innerHTML = document.getElementById('title').value;
}
function update_content() {
document.getElementById("preview_content").innerHTML = document.getElementsByTagName("textarea")[0].value;
}
function preview() {
if (document.getElementById("preview").checked == true) {
var row = document.querySelectorAll('#row');
} else {
}
}
</script>
<div class="col-md-6">
<div class="post-holder">
<div class="post-item">
<div class="post-header">
<div class="title">
<h2 id="preview_title">title</h2>
<span class="author"><a href="/Tobias">Tobias</a></span>
<?php
$date = date("y-m-d");
echo "<time>$date</time>";
?>
</div>
</div>
<div class="post-body">
<p id="preview_content">content</p>
</div>
</div>
</div>
</div>
.main {
margin-top: 20px;
padding-bottom: 90px;
}
.post-holder {
margin-bottom: 15px;
}
.post-item {
background-color: #ffffff;
border-radius: 5px;
padding: 12px 12px 0;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15);
}
.post-item .post-header {
display: flex;
flex-wrap: wrap;
padding-bottom: 11px;
margin-bottom: 11px;
border-bottom: 1px solid rgba(160, 160, 160, 0.15);
}
.post-item .post-header span {
font-size: 12px;
font-weight: 600;
line-height: 1;
margin-left: 2px;
}
.post-item .post-header .title {
width: 90%;
padding-top: 2px;
}
.post-item .post-header .title h2 {
font-weight: 700;
font-size: 18px;
letter-spacing: 3px;
margin-bottom: 0;
line-height: 1;
}
.post-item .post-header .title .author a {
color: rgba(38, 38, 38, 0.75);
}
.post-body {
position: relative;
}
.post-body p {
margin-bottom: 15px;
padding-bottom: 10px;
}
```
The result should look like the home page: <https://sponge.rip/>
You can see some posts there were the text doesn't overflow the div | 2019/11/11 | [
"https://Stackoverflow.com/questions/58806685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12356923/"
] | Word break works fine. You can try it.
```
<p style="word-break: break-all;"></p>
```
<https://jsfiddle.net/dm6u4qra/> | You could always convert line breaks to an html `<br />`. Something like this:
```
document.getElementById("preview_content").innerHTML = document.getElementsByTagName("textarea")[0].value.replace(/\r?\n/g, '<br />');
``` |
130,546 | How to pro-actively notify search engines (Google and others) of removed pages 404s that are still indexed? | 2020/07/14 | [
"https://webmasters.stackexchange.com/questions/130546",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/37313/"
] | The XML sitemap is usually the best method to pro-actively notify search engines of anything, not just 404 pages. But I fail to understand why you would want to do that? Having 404 pages in Google's index isn't necessarily a bad thing, unless of course these 404 pages are still getting a lot of search hits, in which case you may want to 301 redirect them to some other relevant page. Google usually waits 24 hours before removing a 404 page from its index, but if you want to expedite the process I would suggest returning a 410 status code instead. | As suggested in other answers you can handle this issue with help of header status.
If you are still in real hurry and want it removed as fast as possible then you can use remove urls from your Google Webmaster Tools >> Search Console.
Usually it is advisable to allow it to get drop by itself but this is when your 404 page is hurting your rankings or business somehow. |
60,269,267 | I have two lists
```
List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)
```
Want to merge both the list as `(1, 4, 2, 5, 3, 6, 7, 8)` using java streams
First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end. | 2020/02/17 | [
"https://Stackoverflow.com/questions/60269267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3125890/"
] | ```
Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList())
``` | using java streams you can do it easily.
List1.stream().collect(Collectors.toList()).addAll(List2); |
60,269,267 | I have two lists
```
List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)
```
Want to merge both the list as `(1, 4, 2, 5, 3, 6, 7, 8)` using java streams
First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end. | 2020/02/17 | [
"https://Stackoverflow.com/questions/60269267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3125890/"
] | ```
Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList())
``` | Other answer has a link to a working solution, but here's another approach:
```
List<Integer> l1 = Arrays.asList(1, 2, 3);
List<Integer> l2 = Arrays.asList(4, 5, 6, 7, 8);
List<Integer> combined = IntStream.range(0, Math.max(l1.size(), l2.size()))
.boxed()
.flatMap(i -> {
if (i < Math.min(l1.size(), l2.size()))
return Stream.of(l1.get(i), l2.get(i));
else if (i < l1.size())
return Stream.of(l1.get(i));
return Stream.of(l2.get(i));
})
.collect(Collectors.toList());
System.out.println(combined);
``` |
60,269,267 | I have two lists
```
List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)
```
Want to merge both the list as `(1, 4, 2, 5, 3, 6, 7, 8)` using java streams
First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end. | 2020/02/17 | [
"https://Stackoverflow.com/questions/60269267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3125890/"
] | Other answer has a link to a working solution, but here's another approach:
```
List<Integer> l1 = Arrays.asList(1, 2, 3);
List<Integer> l2 = Arrays.asList(4, 5, 6, 7, 8);
List<Integer> combined = IntStream.range(0, Math.max(l1.size(), l2.size()))
.boxed()
.flatMap(i -> {
if (i < Math.min(l1.size(), l2.size()))
return Stream.of(l1.get(i), l2.get(i));
else if (i < l1.size())
return Stream.of(l1.get(i));
return Stream.of(l2.get(i));
})
.collect(Collectors.toList());
System.out.println(combined);
``` | using java streams you can do it easily.
List1.stream().collect(Collectors.toList()).addAll(List2); |
45,709,677 | I have user details from DB and print using blade loop with button for edit. now I want, if I click button I need user details for the button which is clicked for user.
i tried with hidden input filed `<input type="hidden" value="{{$user->email}}" name="email">`
in my controller I just print the value from form submit. but I am getting only last user.
See below, I hope you will understand..
```
<div class="content-wrapper">
<div class="flex-center position-ref full-height">
<form action="{!!url('/delete')!!}" method="post"> {!!csrf_field()!!}
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td> <input type="hidden" value="{{$user->email}}" name="email">
<td>{{$user->role}}</td>
<td>
<div class="btn-group">
<button type="submit" class="btn btn-primary btn-sm" name="edit" >Edit</button>
<button type="submit" class="btn btn-primary btn-sm" name="delete" >Delete</button>
<button type="submit" class="btn btn-primary btn-sm" name="make" >Make Admin</button>
</div>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</form>
</div>
</div>
``` | 2017/08/16 | [
"https://Stackoverflow.com/questions/45709677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8471568/"
] | You could simply do `ratio[mcap<100]<-NA`. | Another possibility is to use function `is.na<-`.
```
is.na(ratio) <- mcap < 100
``` |
2,137 | I'm having difficulty in creating a big post since the editor box is quite small. I want to make it bigger. Can I? | 2010/09/23 | [
"https://wordpress.stackexchange.com/questions/2137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/992/"
] | You have a couple of options. First, you can always click on the bottom right corner of the post edit box and drag to resize:

However, you can also make it so that the post box is larger by default. Go to Settings > Writing, and change the value for size of the post box:
 | You can also click on the blue square icon, second from right in your screenshot. That brings the edit box to full screen. |
1,332,914 | **Thanks for all suggestions. I have reinstalled ubuntu and put a single partition for all disk. I hope answers under this question helps someone else in future. For me, it was hard to understand as a newby Ubuntu user :) Thanks again.**
I have installed Ubuntu 20.04 LTS on my new internal SSD 240 GB.
I have created partitions manually when I start installation as:
swap 512MB,
root 40 GB ext4,
EFI 1 GB,
Other (around) 190 GB fat32.
When installation has enden I didn't see my "other" partition on file browser. Somehow it seen when I open Disks app or Gparted app.
I thought that it has happened because I partitioned as fat32. So I have deleted that partition by using Gparted and I create a new partition with same size as ext4.
After `sudo parted -l`, I get:
[](https://i.stack.imgur.com/nua92.png)
So the problem part is number 4
How can I see and write on my 198 GB partition?
TIA | 2021/04/21 | [
"https://askubuntu.com/questions/1332914",
"https://askubuntu.com",
"https://askubuntu.com/users/667999/"
] | I dont wanna sound stupid but did you try turning the ball like a big volume button?
I still use Bionic Beaver and its plug and play. | Yes, it's possible, you can use the `xinput` too to configure the behavior of `libinput`, the library used to handle input devices.
I run these two commands to enable scrolling for my Slimblade trackball using the back button:
```
xinput set-prop 'Kensington Slimblade Trackball' 'libinput Scroll Method Enabled' 0, 0, 1
xinput set-prop 'Kensington Slimblade Trackball' 'libinput Button Scrolling Button' 8
```
It will then behave like this: if you press and scroll it will only scroll, if you just click it it will work as back button.
The first command enables the scrolling behavior, and the second command tells it to use the back button (instead of button 2, the same used for middle-click -- which makes for an awkward position to click and scroll if you're using the Trackball right-handed).
In case your trackball isn't the same model, you can run the same commands replacing `'Kensington Slimblade Trackball'` by the corresponding id or name of your device you have that you can see when running `xinput list`.
See [`man libinput`](https://www.mankier.com/4/libinput) for more details. |
51,547,899 | I m trying to remove price from string via **preg\_replace with regular expression** but it is not working. i want to remove 202,00 from given string
```
<?php
$haystack = "4 x 3XS - € 202,00, L, 2XS, 4 x XS - € 202,00, S";
echo preg_replace('/^(?:0|[1-9]\d*)(?:\,\d{2})?$/','',$haystack);
?>
```
Expected result:
**4 x 3XS, L, 2XS, 4 x XS, S**
Any help will be appreciated. | 2018/07/26 | [
"https://Stackoverflow.com/questions/51547899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458871/"
] | With the information given (which is almost none), the only way I can think of to improve this is through a `dict comprehension`
```
{k:v for k,v in d.items() if 'XYZ' not in v}
``` | Use comprehensions:
`filtered = [(k, v) for (k, v) in dict(dictionary_notes).items() if 'XYZ' not in v]`
**EDIT**
As someone mentioned below, above statement actually produces a list. To get back a dict, use this instead:
`filtered = {k: v for (k, v) in dict(dictionary_notes).items() if 'XYZ' not in v}` |
51,547,899 | I m trying to remove price from string via **preg\_replace with regular expression** but it is not working. i want to remove 202,00 from given string
```
<?php
$haystack = "4 x 3XS - € 202,00, L, 2XS, 4 x XS - € 202,00, S";
echo preg_replace('/^(?:0|[1-9]\d*)(?:\,\d{2})?$/','',$haystack);
?>
```
Expected result:
**4 x 3XS, L, 2XS, 4 x XS, S**
Any help will be appreciated. | 2018/07/26 | [
"https://Stackoverflow.com/questions/51547899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458871/"
] | With the information given (which is almost none), the only way I can think of to improve this is through a `dict comprehension`
```
{k:v for k,v in d.items() if 'XYZ' not in v}
``` | ```
dictionary_notes = {'a': 'XYZ'}
{k:v for k, v in dict(dictionary_notes).items() if 'XYZ' not in v}
```
Returns: {} |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | **Simply**
1. Encrypting your home folder doesn't actually make your computer more secure - it simply makes all the files and folders in your home folder more secure from unauthorized viewing.
* Your computer is still "vulnerable" in a security standpoint - but it becomes very difficult for your content to be stolen (unless the attacker has your password).
2. You won't need to actually enter your password any more than you normally do - when you log in to your computer your files are seamlessly decrypted for just your session.
3. There is a possibility (depending on your computers hardware) that this will affect the performance on your machine. If you're worried about performance more than security (and you're on an older machine) you may wish to disable this feature.
**Technically**
Ubuntu uses "eCryptfs" which stores all the data in a directory (this case the home folders) as encrypted data. When a user is logged in that encrypted folder is mounted with second decryption mount (this is a temporary mount that works similar to tmpfs - it's created and run in RAM so the files are never stored in a decrypted state on the HD). The idea is - if your hard drive is stolen and the contents read those items aren't able to be read since Linux needs to be running with your authentication to create the successful mount and decryption ( The keys are SHA-512 encrypted data based of several user aspects - the keys are then stored in your encrypted key ring ). The end result is technically secure data (as long as your password isn't cracked or leaked).
You will not have to enter your password any more than usual. There is a slight increase of Disk I/O and CPU which (depending on your computer specs) may hinder performance - though it's quite seamless on most modern PCs | There's a nice article on the topic written by the Ubuntu developer himself, please see: <http://www.linux-mag.com/id/7568/1/>
### Summary:
* A combination of LUKS and dm-crypt are used for whole-disk encryption in Linux.
Ubuntu uses the Enterprise Cryptographic File System (ECryptfs) from version >= 9.10 to enable home drive encryption on login.
* An upper and lower directory are created, where the upper directory is stored unencrypted in RAM, granting access to the system and current user. The lower directory is passed atomic, encrypted units of data and stored in physical memory.
* File and directory names use a single, mount-wide fnek (file name encryption key). The header of each encrypted file contains an fek (file encryption key), wrapped with a separate, mount-wide fekek (file encryption key, encryption key). The Linux kernel keyring manages keys and provides encryption via its common ciphers.
* Using an eCryptfs PAM (Pluggable Authentication Module) does not break unattended reboots, unlike typical full-disk encryption solutions.
* The eCryptfs layered filesystem enables per-file, incremental, encrypted backups. |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | There's a nice article on the topic written by the Ubuntu developer himself, please see: <http://www.linux-mag.com/id/7568/1/>
### Summary:
* A combination of LUKS and dm-crypt are used for whole-disk encryption in Linux.
Ubuntu uses the Enterprise Cryptographic File System (ECryptfs) from version >= 9.10 to enable home drive encryption on login.
* An upper and lower directory are created, where the upper directory is stored unencrypted in RAM, granting access to the system and current user. The lower directory is passed atomic, encrypted units of data and stored in physical memory.
* File and directory names use a single, mount-wide fnek (file name encryption key). The header of each encrypted file contains an fek (file encryption key), wrapped with a separate, mount-wide fekek (file encryption key, encryption key). The Linux kernel keyring manages keys and provides encryption via its common ciphers.
* Using an eCryptfs PAM (Pluggable Authentication Module) does not break unattended reboots, unlike typical full-disk encryption solutions.
* The eCryptfs layered filesystem enables per-file, incremental, encrypted backups. | The security of your actual system isn't determined by the security of your files, folders, and documents...all it does is makes them slightly more secure from prying eyes.... |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | There's a nice article on the topic written by the Ubuntu developer himself, please see: <http://www.linux-mag.com/id/7568/1/>
### Summary:
* A combination of LUKS and dm-crypt are used for whole-disk encryption in Linux.
Ubuntu uses the Enterprise Cryptographic File System (ECryptfs) from version >= 9.10 to enable home drive encryption on login.
* An upper and lower directory are created, where the upper directory is stored unencrypted in RAM, granting access to the system and current user. The lower directory is passed atomic, encrypted units of data and stored in physical memory.
* File and directory names use a single, mount-wide fnek (file name encryption key). The header of each encrypted file contains an fek (file encryption key), wrapped with a separate, mount-wide fekek (file encryption key, encryption key). The Linux kernel keyring manages keys and provides encryption via its common ciphers.
* Using an eCryptfs PAM (Pluggable Authentication Module) does not break unattended reboots, unlike typical full-disk encryption solutions.
* The eCryptfs layered filesystem enables per-file, incremental, encrypted backups. | Less technically answer as requested by OP.
Security benefits of encrypted Home via ecryptfs as in Ubuntu:
* Will not require any additional passwords or keys to be remembered or entered.
* Does not make your computer more secure on a network, e.g. on the internet.
* If the computer is shared between several users, provides an additional barrier against other users accessing your files. (Difficult technical discussion.)
* If an attacker gains physical access to your computer, e.g. steals your notebook, this will protect your data from being read by the thief. (If the computer is off they cannot read your data without your password. If the computer is switched on and you are logged in, it's possible for a thief to steal your data, but requires a more advanced attack, is therefore less likely.) |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | There's a nice article on the topic written by the Ubuntu developer himself, please see: <http://www.linux-mag.com/id/7568/1/>
### Summary:
* A combination of LUKS and dm-crypt are used for whole-disk encryption in Linux.
Ubuntu uses the Enterprise Cryptographic File System (ECryptfs) from version >= 9.10 to enable home drive encryption on login.
* An upper and lower directory are created, where the upper directory is stored unencrypted in RAM, granting access to the system and current user. The lower directory is passed atomic, encrypted units of data and stored in physical memory.
* File and directory names use a single, mount-wide fnek (file name encryption key). The header of each encrypted file contains an fek (file encryption key), wrapped with a separate, mount-wide fekek (file encryption key, encryption key). The Linux kernel keyring manages keys and provides encryption via its common ciphers.
* Using an eCryptfs PAM (Pluggable Authentication Module) does not break unattended reboots, unlike typical full-disk encryption solutions.
* The eCryptfs layered filesystem enables per-file, incremental, encrypted backups. | What else you should know about encrypting your home folder is that the data in it is not accessible when you are not logged in. If you have some automated or external process (like a crontab) that tries to access this data, it will work great while you are watching it, but fail when you are not watching it. This is very frustrating to debug. |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | **Simply**
1. Encrypting your home folder doesn't actually make your computer more secure - it simply makes all the files and folders in your home folder more secure from unauthorized viewing.
* Your computer is still "vulnerable" in a security standpoint - but it becomes very difficult for your content to be stolen (unless the attacker has your password).
2. You won't need to actually enter your password any more than you normally do - when you log in to your computer your files are seamlessly decrypted for just your session.
3. There is a possibility (depending on your computers hardware) that this will affect the performance on your machine. If you're worried about performance more than security (and you're on an older machine) you may wish to disable this feature.
**Technically**
Ubuntu uses "eCryptfs" which stores all the data in a directory (this case the home folders) as encrypted data. When a user is logged in that encrypted folder is mounted with second decryption mount (this is a temporary mount that works similar to tmpfs - it's created and run in RAM so the files are never stored in a decrypted state on the HD). The idea is - if your hard drive is stolen and the contents read those items aren't able to be read since Linux needs to be running with your authentication to create the successful mount and decryption ( The keys are SHA-512 encrypted data based of several user aspects - the keys are then stored in your encrypted key ring ). The end result is technically secure data (as long as your password isn't cracked or leaked).
You will not have to enter your password any more than usual. There is a slight increase of Disk I/O and CPU which (depending on your computer specs) may hinder performance - though it's quite seamless on most modern PCs | The security of your actual system isn't determined by the security of your files, folders, and documents...all it does is makes them slightly more secure from prying eyes.... |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | **Simply**
1. Encrypting your home folder doesn't actually make your computer more secure - it simply makes all the files and folders in your home folder more secure from unauthorized viewing.
* Your computer is still "vulnerable" in a security standpoint - but it becomes very difficult for your content to be stolen (unless the attacker has your password).
2. You won't need to actually enter your password any more than you normally do - when you log in to your computer your files are seamlessly decrypted for just your session.
3. There is a possibility (depending on your computers hardware) that this will affect the performance on your machine. If you're worried about performance more than security (and you're on an older machine) you may wish to disable this feature.
**Technically**
Ubuntu uses "eCryptfs" which stores all the data in a directory (this case the home folders) as encrypted data. When a user is logged in that encrypted folder is mounted with second decryption mount (this is a temporary mount that works similar to tmpfs - it's created and run in RAM so the files are never stored in a decrypted state on the HD). The idea is - if your hard drive is stolen and the contents read those items aren't able to be read since Linux needs to be running with your authentication to create the successful mount and decryption ( The keys are SHA-512 encrypted data based of several user aspects - the keys are then stored in your encrypted key ring ). The end result is technically secure data (as long as your password isn't cracked or leaked).
You will not have to enter your password any more than usual. There is a slight increase of Disk I/O and CPU which (depending on your computer specs) may hinder performance - though it's quite seamless on most modern PCs | Less technically answer as requested by OP.
Security benefits of encrypted Home via ecryptfs as in Ubuntu:
* Will not require any additional passwords or keys to be remembered or entered.
* Does not make your computer more secure on a network, e.g. on the internet.
* If the computer is shared between several users, provides an additional barrier against other users accessing your files. (Difficult technical discussion.)
* If an attacker gains physical access to your computer, e.g. steals your notebook, this will protect your data from being read by the thief. (If the computer is off they cannot read your data without your password. If the computer is switched on and you are logged in, it's possible for a thief to steal your data, but requires a more advanced attack, is therefore less likely.) |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | **Simply**
1. Encrypting your home folder doesn't actually make your computer more secure - it simply makes all the files and folders in your home folder more secure from unauthorized viewing.
* Your computer is still "vulnerable" in a security standpoint - but it becomes very difficult for your content to be stolen (unless the attacker has your password).
2. You won't need to actually enter your password any more than you normally do - when you log in to your computer your files are seamlessly decrypted for just your session.
3. There is a possibility (depending on your computers hardware) that this will affect the performance on your machine. If you're worried about performance more than security (and you're on an older machine) you may wish to disable this feature.
**Technically**
Ubuntu uses "eCryptfs" which stores all the data in a directory (this case the home folders) as encrypted data. When a user is logged in that encrypted folder is mounted with second decryption mount (this is a temporary mount that works similar to tmpfs - it's created and run in RAM so the files are never stored in a decrypted state on the HD). The idea is - if your hard drive is stolen and the contents read those items aren't able to be read since Linux needs to be running with your authentication to create the successful mount and decryption ( The keys are SHA-512 encrypted data based of several user aspects - the keys are then stored in your encrypted key ring ). The end result is technically secure data (as long as your password isn't cracked or leaked).
You will not have to enter your password any more than usual. There is a slight increase of Disk I/O and CPU which (depending on your computer specs) may hinder performance - though it's quite seamless on most modern PCs | What else you should know about encrypting your home folder is that the data in it is not accessible when you are not logged in. If you have some automated or external process (like a crontab) that tries to access this data, it will work great while you are watching it, but fail when you are not watching it. This is very frustrating to debug. |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | Less technically answer as requested by OP.
Security benefits of encrypted Home via ecryptfs as in Ubuntu:
* Will not require any additional passwords or keys to be remembered or entered.
* Does not make your computer more secure on a network, e.g. on the internet.
* If the computer is shared between several users, provides an additional barrier against other users accessing your files. (Difficult technical discussion.)
* If an attacker gains physical access to your computer, e.g. steals your notebook, this will protect your data from being read by the thief. (If the computer is off they cannot read your data without your password. If the computer is switched on and you are logged in, it's possible for a thief to steal your data, but requires a more advanced attack, is therefore less likely.) | The security of your actual system isn't determined by the security of your files, folders, and documents...all it does is makes them slightly more secure from prying eyes.... |
37 | * Does encrypting my home folder make my computer more secure?
* Do I have to enter my password more if my home folder is encrypted?
* What else should I know about encrypting my home folder? | 2010/07/28 | [
"https://askubuntu.com/questions/37",
"https://askubuntu.com",
"https://askubuntu.com/users/56/"
] | What else you should know about encrypting your home folder is that the data in it is not accessible when you are not logged in. If you have some automated or external process (like a crontab) that tries to access this data, it will work great while you are watching it, but fail when you are not watching it. This is very frustrating to debug. | The security of your actual system isn't determined by the security of your files, folders, and documents...all it does is makes them slightly more secure from prying eyes.... |
53,879,891 | I had to modify a file in node modules. which get over written with npm install.
Can I keep modified file in my local src folder? then replace this from node\_module while ng serve/ng build.
please help me how can I achieve this. | 2018/12/21 | [
"https://Stackoverflow.com/questions/53879891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910641/"
] | The best way to handle this would be to fork the repo.
Here is the link : <https://help.github.com/articles/fork-a-repo/>.
Using This way, you have control of the contents of the package.
Then update your package.json with your repositpry address.
I also would recommend not pushing your packages to Git. Packages are already under version control (in their own repo) and pushing to Git just bloats your repo for no reason. | As you might already know, we have a package.json file in the project, in which all dependent and development dependent packages are mentioned. We do not push our node\_modules folder to the GitHub, instead of that whenever someone downloads our project he simply does npm i, and all the libraries mentioned in the package.json are installed in a new folder called node\_modules, even if you make any changes in the node\_modules folder it won't get updated on npm from where others will install the packages.
If you want to make any changes in the node\_modules folder it won't be saved, all you can do is make changes in your code, (e.g you want to override css of library you have imported, open dev tools look for its class, use host to override the css, or use elementRef (ViewChield) to add or remove class from the element) |
1,055,748 | I know that if (x)={0} then the if 0=r0 such that r belongs to R therefor it's a field.
Most likely I'm wrong but I need help with the second part if the ideal is R | 2014/12/07 | [
"https://math.stackexchange.com/questions/1055748",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/185728/"
] | Define the $n$th partial sum by
$$
S\_n = \frac{1}{x} + \frac{1}{x^2} + \frac{1}{x^3} + \dots + \frac{1}{x^n}
$$
Then
\begin{align\*}
x S\_n &= 1 + \frac{1}{x} + \frac{1}{x^2} + \frac{1}{x^3} + \dots + \frac{1}{x^{n-1}} \\
\implies x S\_n - S\_n &= 1 - \frac{1}{x^n} \iff S\_n = \frac{1- \frac{1}{x^n}}{x-1}, \; x \neq 1
\end{align\*}
Now assume $\left| \frac{1}{x} \right| < 1$. The limit $n \to \infty$ is then
\begin{align\*}
S := \lim\_{n \to \infty} S\_n = \lim\_{n \to \infty} \frac{1- \frac{1}{x^n}}{x-1} = \frac{1}{x-1},
\end{align\*}
because $(1/x)^n$ goes to $0$ if $|1/x| < 1$.
If $|1/x| > 1$ the limit is $ \pm \infty$ and the sum diverges. | If $|x|>1$, let $y=\frac{1}{x}$. Then, $|y|<1$, and your series is
$y+y^2+y^3+...$
This is a geometric series, for which the limit is known to be $\frac{y}{1-y}$, if $|y|<1$, and it diverges otherwise. Now, why is that?
Factorize $(1-y^{n+1})=(1-y)(1+y+y^2+...+y^n) \Rightarrow (1+y+y^2+...+y^n)=\frac{1-y^{n+1}}{1-y}$.
If $|y|<1$, then $y^{n+1} \to 0$, and the sum is $(1+y+y^2+...+y^n)=\frac{1}{1-y}$. Subtracting $1$ on both sides gives the result. If $y=-1$, then the sum constantly oscilates between $+1$ and $-1$ (assuming these are real numbers), and if $y<-1$ it oscilates even more, so the series can't converge. If $y\geq 1$, then the series diverges because you're adding increasingly bigger numbers.
Now, your method is half right. It does give the sum of the series, provided there is one. The problem is that you are assuming there is such a number right of the bat, which could be incorrect: try plugging $a=+\infty$ to see that you method arrives at an indeterminate expression $\infty - \infty$
EDIT: Oh, and I forgot, but $\frac{y}{1-y} = \frac{\frac{1}{x}}{1-\frac{1}{x}}=\frac{1}{x-1}$, which is the sought result. |
1,055,748 | I know that if (x)={0} then the if 0=r0 such that r belongs to R therefor it's a field.
Most likely I'm wrong but I need help with the second part if the ideal is R | 2014/12/07 | [
"https://math.stackexchange.com/questions/1055748",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/185728/"
] | Define the $n$th partial sum by
$$
S\_n = \frac{1}{x} + \frac{1}{x^2} + \frac{1}{x^3} + \dots + \frac{1}{x^n}
$$
Then
\begin{align\*}
x S\_n &= 1 + \frac{1}{x} + \frac{1}{x^2} + \frac{1}{x^3} + \dots + \frac{1}{x^{n-1}} \\
\implies x S\_n - S\_n &= 1 - \frac{1}{x^n} \iff S\_n = \frac{1- \frac{1}{x^n}}{x-1}, \; x \neq 1
\end{align\*}
Now assume $\left| \frac{1}{x} \right| < 1$. The limit $n \to \infty$ is then
\begin{align\*}
S := \lim\_{n \to \infty} S\_n = \lim\_{n \to \infty} \frac{1- \frac{1}{x^n}}{x-1} = \frac{1}{x-1},
\end{align\*}
because $(1/x)^n$ goes to $0$ if $|1/x| < 1$.
If $|1/x| > 1$ the limit is $ \pm \infty$ and the sum diverges. | Your edit with the proof that $a = \frac{1}{x-1}$ is very good. Some people mentioned that it only works if $\lvert x \rvert > 1$, and you indicated that you weren't sure about that, so maybe this might help:
Basically, what happens if $x = \frac{1}{2}$?
Then $\frac{1}{x} = \frac{1}{1/2} = 2$, so
$$
\frac{1}{x} + \frac{1}{x^2} + \frac{1}{x^3} +\frac{1}{x^4}+ \ldots = 2 + 4 + 8 + 16 +\ldots
$$
It's probably clear that if you add all these numbers together, you should get infinity. This is an example of a "divergent" series; the series isn't approaching a single number.
Anyway, when $x = \frac{1}{2}$, your formula predicts that
$$
2 + 4 + 8 + 16 + \ldots = \frac{1}{1/2 - 1} = \frac{1}{-1/2} = -2,
$$
which doesn't seem right. So your formula $a = \frac{1}{x-1}$, which works very well when $x> 1$, does not seem to work for $x = \frac{1}{2}$.
This is not your fault! Your formula is the "right" one. But there are good reasons why your formula only works if $\lvert x \rvert > 1$. (Some other things to try: what if $x = 1$? What if $x = -1$? What if $x = 0$? What if $x = -\frac{1}{2}$?)
To learn more, you might want to study Geometric Series:
<http://en.wikipedia.org/wiki/Geometric_series> |
9,718,514 | I am trying to query an api through JSON / REST using Ruby.
```
require 'rubygems'
require 'rest-client'
require 'json'
###Request Build#####
url = 'http://site_name'
request ={
"format"=>'json',
"foo"=> {"first"=>1.1,"second"=>2.2},
"foo_1"=>300,
"foo_2"=>"speed",
"foo_3"=>[
{"id"=> "abc123", "first"=> 1.8, "second"=> 2.8},
{"id"=> "abc456", "first"=> -1.5, "second"=> 1.2}
]
}.to_json
### go go go ###
response = RestClient.post(url,request, :content_type => :json, :accept => :json)
puts response
```
The above works, it will query the api just fine. However the API documentation I am using says I should have ":" instead of "=>" like this
```
"format":'json',
"foo":{"first":1.1,"second":2.2},
"foo_1":300,
"foo_2":"speed",
"foo_3":[
{"id":"abc123", "first":1.8, "second":2.8},
{"id":"abc456", "first":-1.5, "second":1.2}
]
}
```
when I do use them I get this error:
```
new.rb:10: syntax error, unexpected ':', expecting tASSOC
"format":'json',
```
I was wondering why this was? Does ruby not like hashes with ":" ? The reason I ask is that on foo\_3 I have a json file I would like to put in that is formatted like:
```
[{"id":"abc123","first":1.8, "second": 2.8},
{"id":"abc456","first":-1.5, "second": 1.2}]
```
So when I try and use it also get the:
```
new.rb:10: syntax error, unexpected ':', expecting tASSOC
```
There are around 2000 id's - so I cant change all : to => manually and this will be dynamic as well. So I am a little stuck!
SO either I have to find a way to change all ":" to "=>" before I send the array or, I am doing something stupid and very wrong.
Thanks | 2012/03/15 | [
"https://Stackoverflow.com/questions/9718514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877106/"
] | This is the new hash syntax from Ruby 1.9. These two forms are identical
```
{foo: 1, bar: 2}
{:foo => 1, :bar => 2}
```
After formatting to JSON, symbols become strings, so
```
{foo: 1, bar: 2}.to_json
{:foo => 1, :bar => 2}.to_json
{"foo" => 1, "bar" => 2}.to_json
```
all produce the same output.
Summary: don't bother changing your hashes to the new syntax. It's working just fine.
### Update
I just re-read your question and noticed that you mention a "JSON file" that you want to insert into ruby hash. I don't know what code you use for this, but it's not gonna fly. JSON spec requires quoted key names, and Ruby hash syntaxes (both of them) are **not** JSON-compatible. So you can't just take some JSON and pretend that it's a Ruby hash. You can parse it, though.
```
require 'json'
json_string = "{\"id\":\"abc123\",\"first\":1.8, \"second\": 2.8}"
ruby_hash = JSON.parse json_string
# {"id"=>"abc123", "first"=>1.8, "second"=>2.8}
```
### Update 2
Since ruby 2.2, there is a third variant of hash syntax which IS json compatible. So you can take a json string and simple eval it.
```
json_string = '{"id":"abc123","first":1.8, "second": 2.8}'
eval(json_string) # => {:id=>"abc123", :first=>1.8, :second=>2.8}
```
Don't eval it, though. If it's a JSON string, use `JSON.parse` on it. | I think it is from Ruby `1.9` version(not sure), but anyway syntax should be as following,
```
> [{id: "abc123",first: 1.8, second: 2.8},{id: "abc456", first: -1.5, second: 1.2}]
=> [{:id=>"abc123", :first=>1.8, :second=>2.8}, {:id=>"abc456", :first=>-1.5, :second=>1.2}]
``` |
9,718,514 | I am trying to query an api through JSON / REST using Ruby.
```
require 'rubygems'
require 'rest-client'
require 'json'
###Request Build#####
url = 'http://site_name'
request ={
"format"=>'json',
"foo"=> {"first"=>1.1,"second"=>2.2},
"foo_1"=>300,
"foo_2"=>"speed",
"foo_3"=>[
{"id"=> "abc123", "first"=> 1.8, "second"=> 2.8},
{"id"=> "abc456", "first"=> -1.5, "second"=> 1.2}
]
}.to_json
### go go go ###
response = RestClient.post(url,request, :content_type => :json, :accept => :json)
puts response
```
The above works, it will query the api just fine. However the API documentation I am using says I should have ":" instead of "=>" like this
```
"format":'json',
"foo":{"first":1.1,"second":2.2},
"foo_1":300,
"foo_2":"speed",
"foo_3":[
{"id":"abc123", "first":1.8, "second":2.8},
{"id":"abc456", "first":-1.5, "second":1.2}
]
}
```
when I do use them I get this error:
```
new.rb:10: syntax error, unexpected ':', expecting tASSOC
"format":'json',
```
I was wondering why this was? Does ruby not like hashes with ":" ? The reason I ask is that on foo\_3 I have a json file I would like to put in that is formatted like:
```
[{"id":"abc123","first":1.8, "second": 2.8},
{"id":"abc456","first":-1.5, "second": 1.2}]
```
So when I try and use it also get the:
```
new.rb:10: syntax error, unexpected ':', expecting tASSOC
```
There are around 2000 id's - so I cant change all : to => manually and this will be dynamic as well. So I am a little stuck!
SO either I have to find a way to change all ":" to "=>" before I send the array or, I am doing something stupid and very wrong.
Thanks | 2012/03/15 | [
"https://Stackoverflow.com/questions/9718514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877106/"
] | I think it is from Ruby `1.9` version(not sure), but anyway syntax should be as following,
```
> [{id: "abc123",first: 1.8, second: 2.8},{id: "abc456", first: -1.5, second: 1.2}]
=> [{:id=>"abc123", :first=>1.8, :second=>2.8}, {:id=>"abc456", :first=>-1.5, :second=>1.2}]
``` | I think you have it right. the `to_json` method takes care of the formatting for you.
```
>> require 'json'
=> true
>> request ={
?> "format"=>'json',
?> "foo"=> {"first"=>1.1,"second"=>2.2},
?> "foo_1"=>300,
?> "foo_2"=>"speed",
?> "foo_3"=>[
?> {"id"=> "abc123", "first"=> 1.8, "second"=> 2.8},
?> {"id"=> "abc456", "first"=> -1.5, "second"=> 1.2}
>> ]
>> }.to_json
=> {"format":"json","foo":{"first":1.1,"second":2.2},"foo_1":300,"foo_2":"speed","foo_3":[{"id":"abc123","first":1.8,"second":2.8},{"id":"abc456","first":-1.5,"second":1.2}]}
>>
``` |
9,718,514 | I am trying to query an api through JSON / REST using Ruby.
```
require 'rubygems'
require 'rest-client'
require 'json'
###Request Build#####
url = 'http://site_name'
request ={
"format"=>'json',
"foo"=> {"first"=>1.1,"second"=>2.2},
"foo_1"=>300,
"foo_2"=>"speed",
"foo_3"=>[
{"id"=> "abc123", "first"=> 1.8, "second"=> 2.8},
{"id"=> "abc456", "first"=> -1.5, "second"=> 1.2}
]
}.to_json
### go go go ###
response = RestClient.post(url,request, :content_type => :json, :accept => :json)
puts response
```
The above works, it will query the api just fine. However the API documentation I am using says I should have ":" instead of "=>" like this
```
"format":'json',
"foo":{"first":1.1,"second":2.2},
"foo_1":300,
"foo_2":"speed",
"foo_3":[
{"id":"abc123", "first":1.8, "second":2.8},
{"id":"abc456", "first":-1.5, "second":1.2}
]
}
```
when I do use them I get this error:
```
new.rb:10: syntax error, unexpected ':', expecting tASSOC
"format":'json',
```
I was wondering why this was? Does ruby not like hashes with ":" ? The reason I ask is that on foo\_3 I have a json file I would like to put in that is formatted like:
```
[{"id":"abc123","first":1.8, "second": 2.8},
{"id":"abc456","first":-1.5, "second": 1.2}]
```
So when I try and use it also get the:
```
new.rb:10: syntax error, unexpected ':', expecting tASSOC
```
There are around 2000 id's - so I cant change all : to => manually and this will be dynamic as well. So I am a little stuck!
SO either I have to find a way to change all ":" to "=>" before I send the array or, I am doing something stupid and very wrong.
Thanks | 2012/03/15 | [
"https://Stackoverflow.com/questions/9718514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877106/"
] | This is the new hash syntax from Ruby 1.9. These two forms are identical
```
{foo: 1, bar: 2}
{:foo => 1, :bar => 2}
```
After formatting to JSON, symbols become strings, so
```
{foo: 1, bar: 2}.to_json
{:foo => 1, :bar => 2}.to_json
{"foo" => 1, "bar" => 2}.to_json
```
all produce the same output.
Summary: don't bother changing your hashes to the new syntax. It's working just fine.
### Update
I just re-read your question and noticed that you mention a "JSON file" that you want to insert into ruby hash. I don't know what code you use for this, but it's not gonna fly. JSON spec requires quoted key names, and Ruby hash syntaxes (both of them) are **not** JSON-compatible. So you can't just take some JSON and pretend that it's a Ruby hash. You can parse it, though.
```
require 'json'
json_string = "{\"id\":\"abc123\",\"first\":1.8, \"second\": 2.8}"
ruby_hash = JSON.parse json_string
# {"id"=>"abc123", "first"=>1.8, "second"=>2.8}
```
### Update 2
Since ruby 2.2, there is a third variant of hash syntax which IS json compatible. So you can take a json string and simple eval it.
```
json_string = '{"id":"abc123","first":1.8, "second": 2.8}'
eval(json_string) # => {:id=>"abc123", :first=>1.8, :second=>2.8}
```
Don't eval it, though. If it's a JSON string, use `JSON.parse` on it. | I think you have it right. the `to_json` method takes care of the formatting for you.
```
>> require 'json'
=> true
>> request ={
?> "format"=>'json',
?> "foo"=> {"first"=>1.1,"second"=>2.2},
?> "foo_1"=>300,
?> "foo_2"=>"speed",
?> "foo_3"=>[
?> {"id"=> "abc123", "first"=> 1.8, "second"=> 2.8},
?> {"id"=> "abc456", "first"=> -1.5, "second"=> 1.2}
>> ]
>> }.to_json
=> {"format":"json","foo":{"first":1.1,"second":2.2},"foo_1":300,"foo_2":"speed","foo_3":[{"id":"abc123","first":1.8,"second":2.8},{"id":"abc456","first":-1.5,"second":1.2}]}
>>
``` |
117,181 | Dan Brtolotti [CFP CIM B.A. English University of Waterloo - St. Jerome's University](Https://www.linkedin.com/in/dan-bortolotti-8a482310/?originalSubdomain=ca) wrote [this article](https://www.moneysense.ca/save/investing/rrsp/rrsp-vs-tfsa-which-is-right-for-you). I don't fathom third row. RRSP is taxed at withdrawal. Thus how is tax refunded when you deposit in RRSP? What's the "Tax refund on RRSP contribution"?
[](https://i.stack.imgur.com/XjfRP.jpg) | 2019/11/23 | [
"https://money.stackexchange.com/questions/117181",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/-1/"
] | Yes, it is a scam. No one needs your bank password to make a deposit. | it’s a scam. she can text you the check image and you can deposit it electronically. or she can mail you the check. or she can Zelle transfer you the money via phone number or email these days! |
49,106 | I have a Hamilton Beach 6 qt Set 'N Forget Programmable slow cooker, and I keep having the same problem-- when I try to make beef stew, the beef comes out almost inedibly tough, and the veggies don't soften. I can't for the life of me figure out what's wrong!
My cooking method:
>
> Put in 1.5ish lbs stew beef-- the stuff that comes from the store
> already cut up into pieces.
>
>
> Add carrots and celery, chopped about 1/2 - 1 inch long.
>
>
> Add splash worsterchire sauce and cajun spices.
>
>
> Add enough water to fill the crock pot halfway (I did this because
> last time I didn't use as much and thought that might be the source of
> the problem-- but apparently not.)
>
>
> Set crock pot on low until it reaches 160\* (within about an hour and a half), and then leave on warm through the rest of the night (it maintained the temperature at 160\*),
> for a total of 11 hours.
>
>
>
I've read that acidic ingredients can prevent vegetables from getting soft, but that wouldn't explain the beef. Anyone have an idea what the problem might be?
And on that note... does anyone have any suggestions for what to do with a couple pounds of tough, cooked beef, hard carrots, and celery?
Thanks! | 2014/10/20 | [
"https://cooking.stackexchange.com/questions/49106",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/28794/"
] | Try cooking on low instead of warm (or at a higher temperature, maybe 185-195F, with your fancy crock pot), and make sure you really got good stew meat.
I would expect the beef to have been reasonably tender after that long if it were the right kind of cut - certainly not inedibly tough, even if it weren't all the way done due to the lower temperature. But it's unfortunately possible that the beef for stew that you got isn't actually good for this purpose; sometimes stores will sell things under that label expecting (I guess) that people will cook them briefly in their stew. Make sure that what you buy has a lot of connective tissue that will break down as it cooks. See also [What is the best cut of beef to use for stews?](https://cooking.stackexchange.com/questions/20645/what-is-the-best-cut-of-beef-to-use-for-stews)
If you *did* have a good cut of beef for long slow cooking, it's possible that 160F is still just too low (or that 11 hours isn't long enough) for the meat you got. See [What is the lowest possible temperature for stewing meat?](https://cooking.stackexchange.com/questions/24737/what-is-the-lowest-possible-temperature-for-stewing-meat?lq=1) - apparently the collagen -> gelatin breakdown can happen even down to 130F, but it's much faster at higher temperatures.
It's likely that one way or another the low temperatures also messed with your vegetables. I'm not sure if that's actually hot enough to soften them. And for some vegetables, cooking them at a lower temperature for a while will cause them to stay firm even if they're subsequently cooked at a higher temperature!
There's a blurb about this in On Food and Cooking, which I'll find and add into my answer when I can. In the meantime, I found this in [a Serious Eats article about carrots](http://www.seriouseats.com/2010/06/how-to-sous-vide-carrots-vegetables.html):
>
> Unlike meat proteins which are fully cooked anywhere between 140 and 165°F or so, vegetables contain pectin—a kind of glue that holds its cells together and keeps it firm. Pectin doesn't break down until 183°F, which means that no matter what vegetable you cook sous-vide, you have to set your water oven to at least 183°F if you would like the end results to be tender ...
>
>
> | Beef is generally a pretty hard meat to break down compared to other meats. Takes longer to chew, longer to digest, and requires more heat to make it tender during the cooking process. So while a crock pot is fine for most of the operation, you'll meet with the desired success if you'll instead braise your cut of beef in a covered pot (not a pan) on the stove top.
Make sure your pot is of the stainless steel variety, as you'll be going at it pretty aggressively with your metal spatula. And absolutely make sure it has a heavy bottom. Invariably they're a separate piece welded on to the lining of the pot. The bottom of the pot really needs to be able to hold and evenly distribute heat, which is simply not true for pots which by definition are bowl-shaped pieces of sheet metal. Remember, part of what the term "evenly distribute" means is that a balance is struck between the burner and the bottom of the pan. If that bottom is almost non-existent then there's no back-and-forth between the two. The heat just leaps straight from burner to food surface and makes it impossible to do much more than sauté or stir fry.
Add to the pot a thin layer of olive oil, thin meaning just a bit more than one sixteenth of an inch. Set the burner up in the range of medium high to high. (Not high, not medium high, but squarely in between those two.) Just before the oil reaches its smoke point drop in your piece of beef. Your goal is to sear the beef on that side, which will take about 80 seconds. (Do not apply additional pressure to the meat.) Even at that short of a time span it will want to stick to the bottom of the pan. You want to separate the two, but not at the expense of tearing the meat. (Otherwise there's no sense in searing it.) So flip your spatula over (underside facing the ceiling), slide it under an available lip, and then rock it from side to side while gradually pushing it further and further underneath the cut of beef. This means that the flat edge of the spatula retains contact with the bottom of the pot the whole time. Rocking, here, does not mean teetering.
Once the beef is loose, grab a pair of kitchen tongs and stand it up on one side (whichever side is most convenient). You're now going to sear that side. In fact, you're goal is to sear *each* side of the cut of meat. Generally that would be six sides: two broad, two narrow, and two ends. But trust me, this will make all the difference in outcome. The searing creates much more of a "closed system\*, by which the cut of meat is able to stew from the *inside out* rather, that is, than from the outside in. Stewing from the outside in is synonymous with boiling. Boiling beef draws all the moisture out and leaves behind a mass of tissue. So that's never what you want to do. You want to force the moisture to stay *in* the beef while it's cooking, at least as much as humanly possible. Searing makes that possible.
*Now* the meat needs to be braised. It's beef. It needs to be braised. You can accomplish this one of two ways. You can leave it in the pot you started with on your stove top. Or you can transfer it to your crock pot. If you do the latter though, it's imperative that you bring it's temperature way up first. Just add about a quarter cup of water (or beef stock) to it and bring that to a roiling boil. Yes, a quarter cup (not a misprint). Not only is this all you'll need, this is one of those situations where more is literally less. So if you're going to add Worcestershire sauce, make sure that's *part of* this quarter cup of liquid. Also, when you add the beef you'll want to make sure and include all of the oil (flavors) produced in the first step.
Now, if you're going with the standard stove top approach, while the heat's still up (as before) you just add that quarter cup of water and cover. You'll need a clear lid, because braising by definition entails just *barely* keeping things at a boil, in which case you'll be needing to *see* what's happening without *changing* what's happening. As steam rises and contacts the lid it eventually trickles back down and keeps the level the same. It's this equilibrium you're after. Meanwhile, as the meat slowly releases it's own juices, (emphasis on *slowly*), that added amount of liquid is sufficient to compensate for any incidental, low-level evaporation. Same thing with the crock pot. When you drop the meat in it'll temporarily stunt that roiling broil. Here's the time you should be cranking the dial down. Your goal, again, is to get it as low as possible without losing sight of slight movement in the water. And then your goal is to keep it that way.
There's no reason to expect this stage to take any less than a couple hours to accomplish, though closer to four is even better. Remember, the beef is being broken down. And I know from experience that patience at this stage reaps a huge dividend in tenderness. You won't have to cut the meat. Nor will anyone to whom you serve it. It'll simply pull right apart.
Now, the vegetables. Always add first the ones that take longest to cook. Remember, you're going to stay here with low temps (just enough to boil water). So *gauging* what you add (meaning when) can be a bit nuanced compared, that is, to just throwing everything in together into a high heat environment. I always go with celery first. Then carrots and onions. Then potatoes. (You may find it more practical to lightly oil your pieces of potato and then salt and pepper them *before* adding them to the stew.) And remember, this is the diametric opposite of stir fry. Once the braising process commences, at no point ever will you be doing any stirring. You just add what needs to be added, cover, and allow the process to bring itself to completion. The vegetables will release all of their water. You won't have to add any more. (If you do favor a particularly soupy stew, adding preheated beef stock should suffice, but no sooner than a half hour before serve time.)
With a half hour's prep work and searing, three hours braising, and a final hour to hour-and-a-half for the vegetables to slow cook, your stew should take about six hours to make. But this is not the kind of thing you can crank up like a machine and then come home to after a day at the office. A good stew has to be fussed over in a very present and very hands-on sort of way. A crock pot can work. But it's really just one more step in an already ample repertoire. |
49,106 | I have a Hamilton Beach 6 qt Set 'N Forget Programmable slow cooker, and I keep having the same problem-- when I try to make beef stew, the beef comes out almost inedibly tough, and the veggies don't soften. I can't for the life of me figure out what's wrong!
My cooking method:
>
> Put in 1.5ish lbs stew beef-- the stuff that comes from the store
> already cut up into pieces.
>
>
> Add carrots and celery, chopped about 1/2 - 1 inch long.
>
>
> Add splash worsterchire sauce and cajun spices.
>
>
> Add enough water to fill the crock pot halfway (I did this because
> last time I didn't use as much and thought that might be the source of
> the problem-- but apparently not.)
>
>
> Set crock pot on low until it reaches 160\* (within about an hour and a half), and then leave on warm through the rest of the night (it maintained the temperature at 160\*),
> for a total of 11 hours.
>
>
>
I've read that acidic ingredients can prevent vegetables from getting soft, but that wouldn't explain the beef. Anyone have an idea what the problem might be?
And on that note... does anyone have any suggestions for what to do with a couple pounds of tough, cooked beef, hard carrots, and celery?
Thanks! | 2014/10/20 | [
"https://cooking.stackexchange.com/questions/49106",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/28794/"
] | Try cooking on low instead of warm (or at a higher temperature, maybe 185-195F, with your fancy crock pot), and make sure you really got good stew meat.
I would expect the beef to have been reasonably tender after that long if it were the right kind of cut - certainly not inedibly tough, even if it weren't all the way done due to the lower temperature. But it's unfortunately possible that the beef for stew that you got isn't actually good for this purpose; sometimes stores will sell things under that label expecting (I guess) that people will cook them briefly in their stew. Make sure that what you buy has a lot of connective tissue that will break down as it cooks. See also [What is the best cut of beef to use for stews?](https://cooking.stackexchange.com/questions/20645/what-is-the-best-cut-of-beef-to-use-for-stews)
If you *did* have a good cut of beef for long slow cooking, it's possible that 160F is still just too low (or that 11 hours isn't long enough) for the meat you got. See [What is the lowest possible temperature for stewing meat?](https://cooking.stackexchange.com/questions/24737/what-is-the-lowest-possible-temperature-for-stewing-meat?lq=1) - apparently the collagen -> gelatin breakdown can happen even down to 130F, but it's much faster at higher temperatures.
It's likely that one way or another the low temperatures also messed with your vegetables. I'm not sure if that's actually hot enough to soften them. And for some vegetables, cooking them at a lower temperature for a while will cause them to stay firm even if they're subsequently cooked at a higher temperature!
There's a blurb about this in On Food and Cooking, which I'll find and add into my answer when I can. In the meantime, I found this in [a Serious Eats article about carrots](http://www.seriouseats.com/2010/06/how-to-sous-vide-carrots-vegetables.html):
>
> Unlike meat proteins which are fully cooked anywhere between 140 and 165°F or so, vegetables contain pectin—a kind of glue that holds its cells together and keeps it firm. Pectin doesn't break down until 183°F, which means that no matter what vegetable you cook sous-vide, you have to set your water oven to at least 183°F if you would like the end results to be tender ...
>
>
> | I always leave my crocpot on low, not warm. The meat and potatoes are always tender. |
49,106 | I have a Hamilton Beach 6 qt Set 'N Forget Programmable slow cooker, and I keep having the same problem-- when I try to make beef stew, the beef comes out almost inedibly tough, and the veggies don't soften. I can't for the life of me figure out what's wrong!
My cooking method:
>
> Put in 1.5ish lbs stew beef-- the stuff that comes from the store
> already cut up into pieces.
>
>
> Add carrots and celery, chopped about 1/2 - 1 inch long.
>
>
> Add splash worsterchire sauce and cajun spices.
>
>
> Add enough water to fill the crock pot halfway (I did this because
> last time I didn't use as much and thought that might be the source of
> the problem-- but apparently not.)
>
>
> Set crock pot on low until it reaches 160\* (within about an hour and a half), and then leave on warm through the rest of the night (it maintained the temperature at 160\*),
> for a total of 11 hours.
>
>
>
I've read that acidic ingredients can prevent vegetables from getting soft, but that wouldn't explain the beef. Anyone have an idea what the problem might be?
And on that note... does anyone have any suggestions for what to do with a couple pounds of tough, cooked beef, hard carrots, and celery?
Thanks! | 2014/10/20 | [
"https://cooking.stackexchange.com/questions/49106",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/28794/"
] | Try cooking on low instead of warm (or at a higher temperature, maybe 185-195F, with your fancy crock pot), and make sure you really got good stew meat.
I would expect the beef to have been reasonably tender after that long if it were the right kind of cut - certainly not inedibly tough, even if it weren't all the way done due to the lower temperature. But it's unfortunately possible that the beef for stew that you got isn't actually good for this purpose; sometimes stores will sell things under that label expecting (I guess) that people will cook them briefly in their stew. Make sure that what you buy has a lot of connective tissue that will break down as it cooks. See also [What is the best cut of beef to use for stews?](https://cooking.stackexchange.com/questions/20645/what-is-the-best-cut-of-beef-to-use-for-stews)
If you *did* have a good cut of beef for long slow cooking, it's possible that 160F is still just too low (or that 11 hours isn't long enough) for the meat you got. See [What is the lowest possible temperature for stewing meat?](https://cooking.stackexchange.com/questions/24737/what-is-the-lowest-possible-temperature-for-stewing-meat?lq=1) - apparently the collagen -> gelatin breakdown can happen even down to 130F, but it's much faster at higher temperatures.
It's likely that one way or another the low temperatures also messed with your vegetables. I'm not sure if that's actually hot enough to soften them. And for some vegetables, cooking them at a lower temperature for a while will cause them to stay firm even if they're subsequently cooked at a higher temperature!
There's a blurb about this in On Food and Cooking, which I'll find and add into my answer when I can. In the meantime, I found this in [a Serious Eats article about carrots](http://www.seriouseats.com/2010/06/how-to-sous-vide-carrots-vegetables.html):
>
> Unlike meat proteins which are fully cooked anywhere between 140 and 165°F or so, vegetables contain pectin—a kind of glue that holds its cells together and keeps it firm. Pectin doesn't break down until 183°F, which means that no matter what vegetable you cook sous-vide, you have to set your water oven to at least 183°F if you would like the end results to be tender ...
>
>
> | Start the pot on HIGH until it is all hot and bubbly to get it started, around 15 to 30 minutes while you are cleaning up the kitchen. Then turn to LOW to cook. The WARM setting it just to hold the meal until you are ready to serve the meal. WARM setting is designed to NOT COOK the meal. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.