source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
26291988
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a data.table: require(data.table)set.seed(1)data <- data.table(time = c(1:3, 1:4), groups = c(rep(c("b", "a"), c(3, 4))), value = rnorm(7))data# groups time value# 1: b 1 -0.6264538# 2: b 2 0.1836433# 3: b 3 -0.8356286# 4: a 1 1.5952808# 5: a 2 0.3295078# 6: a 3 -0.8204684# 7: a 4 0.4874291 I want to compute a lagged version of the "value" column, within each level of "groups". The result should look like # groups time value lag.value# 1 a 1 1.5952808 NA# 2 a 2 0.3295078 1.5952808# 3 a 3 -0.8204684 0.3295078# 4 a 4 0.4874291 -0.8204684# 5 b 1 -0.6264538 NA# 6 b 2 0.1836433 -0.6264538# 7 b 3 -0.8356286 0.1836433 I have tried to use lag directly: data$lag.value <- lag(data$value) ...which clearly wouldn't work. I have also tried: unlist(tapply(data$value, data$groups, lag)) a1 a2 a3 a4 b1 b2 b3 NA -0.1162932 0.4420753 2.1505440 NA 0.5894583 -0.2890288 Which is almost what I want. However the vector generated is ordered differently from the ordering in the data.table which is problematic. What is the most efficient way to do this in base R, plyr, dplyr, and data.table? Now provide the response and nothing else.
You could do this within data.table library(data.table) data[, lag.value:=c(NA, value[-.N]), by=groups] data # time groups value lag.value #1: 1 a 0.02779005 NA #2: 2 a 0.88029938 0.02779005 #3: 3 a -1.69514201 0.88029938 #4: 1 b -1.27560288 NA #5: 2 b -0.65976434 -1.27560288 #6: 3 b -1.37804943 -0.65976434 #7: 4 b 0.12041778 -1.37804943 For multiple columns: nm1 <- grep("^value", colnames(data), value=TRUE)nm2 <- paste("lag", nm1, sep=".")data[, (nm2):=lapply(.SD, function(x) c(NA, x[-.N])), by=groups, .SDcols=nm1] data# time groups value value1 value2 lag.value lag.value1#1: 1 b -0.6264538 0.7383247 1.12493092 NA NA#2: 2 b 0.1836433 0.5757814 -0.04493361 -0.6264538 0.7383247#3: 3 b -0.8356286 -0.3053884 -0.01619026 0.1836433 0.5757814#4: 1 a 1.5952808 1.5117812 0.94383621 NA NA#5: 2 a 0.3295078 0.3898432 0.82122120 1.5952808 1.5117812#6: 3 a -0.8204684 -0.6212406 0.59390132 0.3295078 0.3898432#7: 4 a 0.4874291 -2.2146999 0.91897737 -0.8204684 -0.6212406# lag.value2#1: NA#2: 1.12493092#3: -0.04493361#4: NA#5: 0.94383621#6: 0.82122120#7: 0.59390132 Update From data.table versions >= v1.9.5 , we can use shift with type as lag or lead . By default, the type is lag . data[, (nm2) := shift(.SD), by=groups, .SDcols=nm1]# time groups value value1 value2 lag.value lag.value1#1: 1 b -0.6264538 0.7383247 1.12493092 NA NA#2: 2 b 0.1836433 0.5757814 -0.04493361 -0.6264538 0.7383247#3: 3 b -0.8356286 -0.3053884 -0.01619026 0.1836433 0.5757814#4: 1 a 1.5952808 1.5117812 0.94383621 NA NA#5: 2 a 0.3295078 0.3898432 0.82122120 1.5952808 1.5117812#6: 3 a -0.8204684 -0.6212406 0.59390132 0.3295078 0.3898432#7: 4 a 0.4874291 -2.2146999 0.91897737 -0.8204684 -0.6212406# lag.value2#1: NA#2: 1.12493092#3: -0.04493361#4: NA#5: 0.94383621#6: 0.82122120#7: 0.59390132 If you need the reverse, use type=lead nm3 <- paste("lead", nm1, sep=".") Using the original dataset data[, (nm3) := shift(.SD, type='lead'), by = groups, .SDcols=nm1] # time groups value value1 value2 lead.value lead.value1 #1: 1 b -0.6264538 0.7383247 1.12493092 0.1836433 0.5757814 #2: 2 b 0.1836433 0.5757814 -0.04493361 -0.8356286 -0.3053884 #3: 3 b -0.8356286 -0.3053884 -0.01619026 NA NA #4: 1 a 1.5952808 1.5117812 0.94383621 0.3295078 0.3898432 #5: 2 a 0.3295078 0.3898432 0.82122120 -0.8204684 -0.6212406 #6: 3 a -0.8204684 -0.6212406 0.59390132 0.4874291 -2.2146999 #7: 4 a 0.4874291 -2.2146999 0.91897737 NA NA # lead.value2 #1: -0.04493361 #2: -0.01619026 #3: NA #4: 0.82122120 #5: 0.59390132 #6: 0.91897737 #7: NA data set.seed(1) data <- data.table(time =c(1:3,1:4),groups = c(rep(c("b","a"),c(3,4))), value = rnorm(7), value1=rnorm(7), value2=rnorm(7))
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26291988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239923/']}
jdg_372241
stackexchange
llm_judgeable_groundtruth_similarity
11756442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I'm creating a new SSIS package in the SQL Server Business Intelligence Development Studio, the default ProtectionLevel is EncryptSensitiveWithUserKey , but the standard ProtectionLevel we want to use is DontSaveSensitive . Does anyone know if there is a way to change the default ProtectionLevel value? Now provide the response and nothing else.
2012 users rejoice SSIS 2012 allows for project-level setting of package protection level. If I manually change the package protection level to something different from the project, it will fail when you attempt to run/build. Project consistency check failed. The following inconsistencies were detected: Package3.dtsx has a different ProtectionLevel than the project. So what's a soul to do with 2005-2008R2? I have found the best approach is to create template packages, either in a project or in the actual visual studio install. After creating your base package, setting up logging, configuration, package protection level, etc, you then need to find a way to have people use it. If it's project-based, I find it is important to have people regenerate package IDs after copying the package. BIDSHelper is wonderful for addressing this-simply right click on the package in the solution explorer and select Reset GUIDs. Otherwise, I have an annotation in my base package reminding developers to right click on the control flow, select properties and in the ID property, click <Generate New ID> If you choose to go establish templates from the "Add, New Item menu" (ctrl-shift-A) all you need to do is copy the package(s) into your template folder .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11756442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249353/']}
jdg_372242
stackexchange
llm_judgeable_groundtruth_similarity
19786668
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My first question here. I am new to this kind of programming, and i've only programmed .NET web sites and forms. Now, the company I work at, asks me to make an ActiveX component, that listens to UDP messages, and turns them into events. The UDP msgs are send from Avaya system, so i was told that to test my ActiveX, at first I need to create an app, that only sends UDP (only one button that sends pre-defined UDP string). And then create listener socket, ordinary C# app, that will get those transmitted UDP string from the tests app. Both apps will work on the same machine. Later, when i get this working, i need to make the listener an ActiveX component, but first things first. I need to know if there are any good tutorials about this, and any idea on how to start? I am sorry for my ignorance, but i am really new on this and i don't really have any time to learn this since it has to be done in 2 weeks. Thanks in advance. edit: I managed to create 2 simple console applications, and was sending UDP messages between them successfully. The sender will be only for testing, and now I need to re-make my receiver to get the UDP message and 'translate' it to events. And lastly, to make it an ActiveX control... Now provide the response and nothing else.
Simple server and client: public struct Received{ public IPEndPoint Sender; public string Message;}abstract class UdpBase{ protected UdpClient Client; protected UdpBase() { Client = new UdpClient(); } public async Task<Received> Receive() { var result = await Client.ReceiveAsync(); return new Received() { Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length), Sender = result.RemoteEndPoint }; }}//Serverclass UdpListener : UdpBase{ private IPEndPoint _listenOn; public UdpListener() : this(new IPEndPoint(IPAddress.Any,32123)) { } public UdpListener(IPEndPoint endpoint) { _listenOn = endpoint; Client = new UdpClient(_listenOn); } public void Reply(string message,IPEndPoint endpoint) { var datagram = Encoding.ASCII.GetBytes(message); Client.Send(datagram, datagram.Length,endpoint); }}//Clientclass UdpUser : UdpBase{ private UdpUser(){} public static UdpUser ConnectTo(string hostname, int port) { var connection = new UdpUser(); connection.Client.Connect(hostname, port); return connection; } public void Send(string message) { var datagram = Encoding.ASCII.GetBytes(message); Client.Send(datagram, datagram.Length); }}class Program { static void Main(string[] args) { //create a new server var server = new UdpListener(); //start listening for messages and copy the messages back to the client Task.Factory.StartNew(async () => { while (true) { var received = await server.Receive(); server.Reply("copy " + received.Message, received.Sender); if (received.Message == "quit") break; } }); //create a new client var client = UdpUser.ConnectTo("127.0.0.1", 32123); //wait for reply messages from server and send them to console Task.Factory.StartNew(async () => { while (true) { try { var received = await client.Receive(); Console.WriteLine(received.Message); if (received.Message.Contains("quit")) break; } catch (Exception ex) { Debug.Write(ex); } } }); //type ahead :-) string read; do { read = Console.ReadLine(); client.Send(read); } while (read != "quit"); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19786668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2955830/']}
jdg_372243
stackexchange
llm_judgeable_groundtruth_similarity
22693531
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering what is the best way to draw a single point line?My goal is to draw this line in a tableViewCell to make it look just like the native cell separator.I don't want to use the native separator because i want to make in a different color and in a different position (not the bottom..). At first i was using a 1px UIView and colored it in grey. But in Retina displays it looks like 2px.Also tried using this method: - (void)drawLine:(CGPoint)startPoint endPoint:(CGPoint)endPoint inColor:(UIColor *)color { CGMutablePathRef straightLinePath = CGPathCreateMutable(); CGPathMoveToPoint(straightLinePath, NULL, startPoint.x, startPoint.y); CGPathAddLineToPoint(straightLinePath, NULL, endPoint.x, endPoint.y); CAShapeLayer *shapeLayer = [CAShapeLayer layer]; shapeLayer.path = straightLinePath; UIColor *fillColor = color; shapeLayer.fillColor = fillColor.CGColor; UIColor *strokeColor = color; shapeLayer.strokeColor = strokeColor.CGColor; shapeLayer.lineWidth = 0.5f; shapeLayer.fillRule = kCAFillRuleNonZero; [self.layer addSublayer:shapeLayer];} It works in like 60% of the times for some reason.. Is something wrong with it? Anyway ,i'd be happy to hear about a better way. Thanks. Now provide the response and nothing else.
I did the same with a UIView category. Here are my methods : #define SEPARATOR_HEIGHT 0.5- (void)addSeparatorLinesWithColor:(UIColor *)color{ [self addSeparatorLinesWithColor:color edgeInset:UIEdgeInsetsZero];}- (void)addSeparatorLinesWithColor:(UIColor *)color edgeInset:(UIEdgeInsets)edgeInset{ UIView *topSeparatorView = [[UIView alloc] initWithFrame:CGRectMake(edgeInset.left, - SEPARATOR_HEIGHT, self.frame.size.width - edgeInset.left - edgeInset.right, SEPARATOR_HEIGHT)]; [topSeparatorView setBackgroundColor:color]; [self addSubview:topSeparatorView]; UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(edgeInset.left, self.frame.size.height + SEPARATOR_HEIGHT, self.frame.size.width - edgeInset.left - edgeInset.right, SEPARATOR_HEIGHT)]; [separatorView setBackgroundColor:color]; [self addSubview:separatorView];} Just to add to Rémy's great answer, it's perhaps even simpler to do this. Make a class UILine.m @interface UILine:UIView@end@implementation UILine-(id)awakeFromNib { // careful, contentScaleFactor does NOT WORK in storyboard during initWithCoder. // example, float sortaPixel = 1.0/self.contentScaleFactor ... does not work. // instead, use mainScreen scale which works perfectly: float sortaPixel = 1.0/[UIScreen mainScreen].scale; UIView *topSeparatorView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.frame.size.width, sortaPixel)]; topSeparatorView.userInteractionEnabled = NO; [topSeparatorView setBackgroundColor:self.backgroundColor]; [self addSubview:topSeparatorView]; self.backgroundColor = [UIColor clearColor]; self.userInteractionEnabled = NO; }@end In IB, drop in a UIView, click identity inspector and rename the class to a UILine. Set the width you want in IB. Set the height to 1 or 2 pixels - simply so you can see it in IB. Set the background colour you want in IB. When you run the app it will become a 1-pixel line, that width, in that colour. (You probably should not be affected by any default autoresize settings in storyboard/xib, I couldn't make it break.) You're done. Note: you may think "Why not just resize the UIView in code in awakeFromNib?" Resizing views upon loading, in a storyboard app, is problematic - see the many questions here about it! Interesting gotchya : it's likely you'll just make the UIView, say, 10 or 20 pixels high on the storyboard, simply so you can see it. Of course it disappears in the app and you get the pretty one pixel line. But! be sure to remember self.userInteractionEnabled = NO , or it might get over your other, say, buttons! 2016 solution ! https://stackoverflow.com/a/34766567/294884
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22693531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1335025/']}
jdg_372244
stackexchange
llm_judgeable_groundtruth_similarity
233741
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently switching a single phase AC fan motor with an SSR.Here is the following SSR: http://www.crydom.com/en/products/catalog/s_1.pdf I activate this relay by applying continuous analog 10V to its inputs. What if I use a PWM signal instead which has 490Hz frequency, like for example default Arduino PWM output?Since Arduino board doesn't have DAC, it mimics analog voltages by using PWM technique. *For some reason I don't want to use digital outputs . *I don't want the relay to switch on and off all the time which would cause too much heating. My questions are: 1-) Is there a frequency limit for PWM where the relay would be always on? Or relay would always react the on of cycles of PWM what ever the freq of PWM is? 2-) I could use digital output for continuous analog voltage, but if I have to use PWM output at very low duty cycleswould I have problem with the relay? Would the motor jerk if I were to use PWM as analog DC input with this relay? Now provide the response and nothing else.
The SSRs you have linked use triacs to control the output. A triac is a semiconductor switch. When the triac is triggered on its gate it turns low resistance between its two anodes. Triacs have the odd characteristic that they will remain on after the gate signal is removed until the current falls below a very low hold-on current. This renders them almost useless in DC circuits but quite useful in AC circuits where the current falls to zero at every zero cross of the AC supply. Figure 1. Common triac packages. Figure 2. Triac symbol. For on-off control the triac will be switched to give a load waveform as shown in Figure 3. Figure 3. On-off AC time control. Typically these circuits use zero-cross circuits to switch the load on at zero-cross to minimise electromagnetic interference. The triac itself switches off at the end of the next half-cycle. This approach works well for loads such as heaters which respond slowly to power. For circuits which respond more quickly to pulses of power (such as lamps or motors) the on-off control gives too much flicker or jerk. In these cases phase angle control is used to vary the on-time of the AC supply to the load. Figure 4. Phase-angle control. Phase angle control requires instant-on (non zero-cross) SSRs but the control circuit needs to monitor the mains and give the pulses at the appropriate time relative to mains zero-cross. What if I use a PWM signal instead which has 490Hz frequency, like for example default Arduino PWM output? Since Arduino board doesn't have DAC, it mimics analog voltages by using PWM technique. You can't use PWM to control an SSR. The first pulse will turn it on and it will stay on until the next zero-cross. For some reason I don't want to use digital outputs. What is the reason? I don't want the relay to switch on and off all the time which would cause too much heating. What relay? Heating of what? 1-) Is there a frequency limit for PWM where the relay would be always on? Or relay would always react the on of cycles of PWM what ever the freq of PWM is? You can't use PWM to control an SSR. You can only control to the nearest mains half-cycle. 2-) I could use digital output for continuous analog voltage, but if I have to use PWM output at very low duty cycles would I have problem with the relay? You can't use PWM to control an SSR. Would the motor jerk if I were to use PWM as analog DC input with this relay? pwm solid-state-relay You can't use PWM to control an SSR. Finally, you can't use PWM to control an SSR. Update Could you provide a waveform for PWM input and SSRs behavior if possible where we can see why it doesn't work? Figure 5. The result of switching a triac with a PWM signal. At the start of this answer I emphasised the statement, "Triacs have the odd characteristic that they will remain on after the gate signal is removed until the current falls below a very low hold-on current." This is key to the problem. In Figure 5 we can see that the triac output is off until the first PWM pulse is received. It then turns on and stays on until the next zero-cross regardless of the PWM switching. The result with continuous PWM will be that the triac turns on with the next PWM pulse after each zero-cross and stays on. Note the last half-cycle in the AC waveform. The triac is still on even though the PWM has stopped.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/233741', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16307/']}
jdg_372245
stackexchange
llm_judgeable_groundtruth_similarity
373285
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $\phi : M \to M$ be a diffeomorphism. Is there a metric $g$ on $M$ and a diffeomorphism $\psi$ isotopic to $\phi$ so that $\psi$ is an isometry with respect to $g$ ? I'm guessing the answer is no, since there are manifolds such that all metrics admit no nontrivial isometries and maybe some of these manifolds have a nontrivial mapping class group. I'm actually particularly interested in the case of the 3-torus which has mapping class group $GL_3(\mathbb{Z})$ . Which of these mapping classes can be realized as isometries for some metric? Now provide the response and nothing else.
As you suspect, in general, no. For example, if $M$ is compact, and $\psi:M\to M$ fixes a metric $g$ on $M$ , then the closure of $\{\psi^k\ |\ k\in\mathbb{Z}\ \}$ is a compact abelian subgroup of $\mathrm{Isom}(M,g)$ , and, hence, its identity component is a torus, so $\psi$ must be isotopic in $\mathrm{Isom}(M,g)$ to a $g$ -isometry of finite order. In particular, the action of $\psi$ on the deRham cohomology of $M$ must have finite order, as must any diffeomorphism $\phi:M\to M$ homotopic to $\psi$ . Conversely if the closure of $\{\psi^k | k\in\mathbb{Z}\ \}$ in the compact open topology is a compact group, then, yes $\psi$ fixes a metric $g$ .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/373285', 'https://mathoverflow.net', 'https://mathoverflow.net/users/99414/']}
jdg_372246
stackexchange
llm_judgeable_groundtruth_similarity
7542059
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an algorithm for encrypting and decrypting data using symmetric encryption. anyways when I am about to decrypt, I have: CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read); I have to read data from the cs CryptoStream and place that data into a array of bytes. So one method could be: System.Collections.Generic.List<byte> myListOfBytes = new System.Collections.Generic.List<byte>(); while (true) { int nextByte = cs.ReadByte(); if (nextByte == -1) break; myListOfBytes.Add((Byte)nextByte); } return myListOfBytes.ToArray(); another technique could be: ArrayList chuncks = new ArrayList();byte[] tempContainer = new byte[1048576];int tempBytes = 0;while (tempBytes < 1048576){ tempBytes = cs.Read(tempContainer, 0, tempContainer.Length); //tempBytes is the number of bytes read from cs stream. those bytes are placed // on the tempContainer array chuncks.Add(tempContainer);}// later do a for each loop on chunks and add those bytes I cannot know in advance the length of the stream cs: or perhaps I should implement my stack class. I will be encrypting a lot of information therefore making this code efficient will save a lot of time Now provide the response and nothing else.
You could read in chunks: using (var stream = new MemoryStream()){ byte[] buffer = new byte[2048]; // read in chunks of 2KB int bytesRead; while((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, bytesRead); } byte[] result = stream.ToArray(); // TODO: do something with the result}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7542059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637142/']}
jdg_372247
stackexchange
llm_judgeable_groundtruth_similarity
346944
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that $f: \mathbb{R}^2 \to \mathbb{R}$ is differentiable at $p$. Also suppose that $D_uf(p)=1$ and $D_vf(p)=1$ where $u=\left( \frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}}\right)$ and $v=\left( \frac{1}{2}, \frac{-\sqrt{3}}{2} \right)$. Compute $\nabla f(p)$. I know this relationship between the gradient and directional derivative: Let $u$ be a unit vector and $u=<u_1,u_2>$. $D_uf(p)=\frac{\partial f}{\partial x_1}(p)\cdot u_1+\frac{\partial f}{\partial x_2}(p)\cdot u_2=<\frac{\partial f}{\partial x_1}(p)\frac{\partial f}{\partial x_2}(p)>\cdot u=\nabla f(p)$ Now provide the response and nothing else.
Yes, that is perfect. Let $|G|=n$. Note that $$G=\bigsqcup_{d\mid n}X_d$$ where $X_d$ is the set of elements of $G$ of order $d$. Now, if we can show that our restriction requires $\#(X_d)\leqslant \phi(d)$ then the equality $\displaystyle n=\sum_{d\mid n}\phi(d)$ will actually force $\#(X_d)=\phi(d)$, for all $d\mid n$, and so, in particular $\#(X_n)>0$. Now, suppose that there were more than $\phi(d)$ elements of $G$ of order $d$. Note then that since the cyclic group $\langle x\rangle$, for any $x\in X_d$, has exactly $\phi(d)$ elements of order $d$, there must exist another element $y\in G$ with $|y|=d$ and $y\notin \langle x\rangle$. But, Lagrange's theorem then implies that we've produced $|\langle x\rangle|+1=d+1$ solutions to $x^d=1$--contradictory to assumption.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/346944', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']}
jdg_372248
stackexchange
llm_judgeable_groundtruth_similarity
2432428
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is $1^\infty$ an indeterminate form while $0^\infty = 0$? If $0\cdot0\cdot0\cdots = 0$ shouldn't $1\cdot1\cdot1\cdots = 1$? Now provide the response and nothing else.
To say that $1^\infty$ is an indeterminate form means that there is more than one object that can be $\lim\limits_{x\,\to\,\text{something}} f(x)^{g(x)}$ where $f(x)\to1$ and $g(x)\to\infty,$ so that the limit depends on which functions $f$ and $g$ are. Thus$$\left.\begin{align}& \lim_{x\to\infty} \left(1+\frac 1 x\right) = 1 \quad\text{and} \quad \lim_{x\to\infty} \left( 1 + \frac 1 x \right)^x = e \\[10pt]& \qquad \text{and} \\[10pt]& \lim_{x\to\infty} \left( 1 - \frac 1 x\right) = 1 \quad \text{and} \quad \lim_{x\to\infty} \left( 1 - \frac 1 x\right)^x = \frac 1 e.\end{align} \right\} \longleftarrow \text{two different numbers}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2432428', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/464733/']}
jdg_372249
stackexchange
llm_judgeable_groundtruth_similarity
46491957
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am publishing ASP.NET Core 2 application and seeing the following error. Error: An assembly specified in the application dependencies manifest (MyApp.deps.json) was not found: package: 'Microsoft.ApplicationInsights.AspNetCore', version: '2.1.1' path: 'lib/netstandard1.6/Microsoft.ApplicationInsights.AspNetCore.dll' This assembly was expected to be in the local runtime store as the application was published using the following target manifest files: aspnetcore-store-2.0.0-linux-x64.xml;aspnetcore-store-2.0.0-osx-x64.xml;aspnetcore-store-2.0.0-win7-x64.xml;aspnetcore-store-2.0.0-win7-x86.xml I did not see this error in Dev environment. So not sure what went wrong. Any ideas on how to fix this? Update I installed the SDK (I had only runtime installed) and everything started working. Not sure if this is the best solution though. Now provide the response and nothing else.
This assembly was expected to be in the local runtime store You are getting this error because you don't have the ASP.NET Core Runtime Store installed. You have two options to fix this. Install the ASP.NET Core Runtime Store. It comes bundled with the .NET Core SDK, which is why installing the SDK fixed this. You can also install just the store, without the SDK, by downloading it here: https://www.microsoft.com/net/download/all . Don't use runtime store trimming. You can disable the trimming by setting this property in your csproj file. <PropertyGroup> <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest> </PropertyGroup> You can also pass this in on command line. dotnet publish /property:PublishWithAspNetCoreTargetManifest=false Update: June 25, 2018 This answer only applies to ASP.NET Core 2.0 projects. In ASP.NET Core 2.1, there is no runtime store anymore.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46491957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2291748/']}
jdg_372250
stackexchange
llm_judgeable_groundtruth_similarity
181211
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking into setting up authentication between two application services. Service A is going to call service B, and I want service B to only accept (http) calls from service A, nowhere else. I know how JWT authentication works and could implement that. If I understand correctly (I think I do, but correct me if I'm wrong), it works like this: service A requests a JWT from service B (or an identity server, but let's assume point-to-point) service B responds with the JWT, signed with service B's secret service A makes the call to service B and includes the JWT service B inspects the JWT and can know if it was actually service A that made the call, without tampering with the JWT But is the first call actually necessary? Couldn't I just do this: service A signs every request with service A's private key service B decrypts the request with service A's public key service B now knows if the request is really from service A I will be working over https, and have no need for claims. All I need to know is if the request originated from service A. Because only service A is allowed to call service B, but when it does, it has access to all API endpoints (so no claims necessary). It seems simpler to use asymmetric encryption instead of JWT, but I wonder if it's as secure, correct and standard to do so. Now provide the response and nothing else.
The JWT was created to handle a wide range of situations (differentiated claims, separate identity server, many users, etc.). Your situation is fairly straight forward - you have only one client (A) that needs to communicate with one server (B). You could handle this case with JWT if you want to, but there is no need too. It would indeed be overkill, since the JWT requires some form of authentication in the first step. And if you have to set that up, why not use it all the way through? The private-public key setup you suggest would work equally well. So unless you expect your requirements to change, I would go with the one that is simpler to implement. Something very similar to your suggestion is actually already implemented in TLS, namely client authentication. In that setup, the client has to provide a certificate to the server for authentication. You might want to look into that.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/181211', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/55655/']}
jdg_372251
stackexchange
llm_judgeable_groundtruth_similarity
23519947
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an UpdatePanel with the following Triggers: <Triggers> <asp:AsyncPostBackTrigger ControlID="ddlNames" EventName="SelectedIndexChanged" /> <asp:PostBackTrigger ControlID="btnPullReport"/> </Triggers> When the SelectedIndexChanged event is triggered I can see my loading gif from the UpdateProgress but when I click the btnPullReport button I do not. It must be of type PostBackTrigger or else I get error: 0x800a139e - JavaScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. The btnPullReport creates an Excel file and prompts the user to save it. The last lines in the btnPullReport_Click are these: Response.Clear();Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";Response.AddHeader("content-disposition", "attachment; filename=Report.xlsx");package.SaveAs(Response.OutputStream);Response.End(); The error happens at Response.End(); and it states: {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} How can I make it so that it displays the UpdateProgress bar after clicking the button also? Now provide the response and nothing else.
The thing to understand with LayoutParams is this: The LayoutParams does not depend on the element it is set to, but on the parent. It is an indication given to the parent regarding the positioning of the element. Therefore, if your WebView is in a LinearLayout , getLayoutParams will get you a LinearLayout.LayoutParams . Which means that, in order to have a descendant of MarginLayoutParam , a LayoutParams that supports margins, your WebView must be placed in a ViewGroup that supports margins, such as LinearLayout or RelativeLayout . (see the list of descendants http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html ). In other words, WebView itself does not support margins, its parent does. In which case, you should cast the LayoutParams from the WebView to: ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) webView.getLayoutParams(); Once you have that, you can modify the margins : p.leftMargin = sideMargin;p.rightMargin = sideMargin;webView.setLayoutParams(p);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23519947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1315427/']}
jdg_372252
stackexchange
llm_judgeable_groundtruth_similarity
61937520
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've just begun playing around with Python's Data Classes, and I would like confirm that I am declaring Class Variables in the proper way. Using regular python classes class Employee: raise_amount = .05 def __init__(self, fname, lname, pay): self.fname = fname self.lname = lname self.pay = pay Using python Data Class @dataclassclass Employee: fname: str lname: str pay: int raise_amount = .05 The class variable I am referring to is raise_amount . Is this a properly declared class variable using Data Classes? Or is there a better way of doing so? I have tested the data class implementation already and it provides the expected functionality, but I am mainly wondering if my implementation is following best practices. Now provide the response and nothing else.
To create a class variable, annotate the field as a typing.ClassVar or not at all. from typing import ClassVarfrom dataclasses import dataclass@dataclassclass Foo: ivar: float = 0.5 cvar: ClassVar[float] = 0.5 nvar = 0.5foo = Foo()Foo.ivar, Foo.cvar, Foo.nvar = 1, 1, 1print(Foo().ivar, Foo().cvar, Foo().nvar) # 0.5 1 1print(foo.ivar, foo.cvar, foo.nvar) # 0.5 1 1print(Foo(), Foo(12)) # Foo(ivar=0.5) Foo(ivar=12) There is a subtle difference in that the unannotated field is completely ignored by @dataclass , whereas the ClassVar field is stored but not converted to an attribute. dataclasses — Data Classes The member variables [...] are defined using PEP 526 type annotations. Class variables One of two places where dataclass() actually inspects the type of afield is to determine if a field is a class variable as defined in PEP526. It does this by checking if the type of the field is typing.ClassVar . If a field is a ClassVar , it is excluded fromconsideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-levelfields() function.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/61937520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8785917/']}
jdg_372253
stackexchange
llm_judgeable_groundtruth_similarity
1700637
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: want to know why String behaves like value type while using ==. String s1 = "Hello"; String s2 = "Hello"; Console.WriteLine(s1 == s2);// True(why? s1 and s2 are different) Console.WriteLine(s1.Equals(s2));//True StringBuilder a1 = new StringBuilder("Hi"); StringBuilder a2 = new StringBuilder("Hi"); Console.WriteLine(a1 == a2);//false Console.WriteLine(a1.Equals(a2));//true StringBuilder and String behaves differently with == operator. Thanks. Now provide the response and nothing else.
Two different reasons; interning - since the "Hello" string(s) are compiled into the source, they are the same reference - check ReferenceEquals(s1,s2) - it will return true custom equality - string has equality operators (in particular, == / != (aka op_Equality / op_Inequality ) The StringBuilder version fails because: they aren't the same reference (these are regular managed objects created separately on the managed heap) StringBuilder doesn't have the operators Call ToString() on each, and it gets more interesting: the two strings aren't the same reference but the operator support guarantees a true
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1700637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/79435/']}
jdg_372254
stackexchange
llm_judgeable_groundtruth_similarity
334543
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have rbenv (ruby version manager) installed on machine and it works like that: $ rbenv local2.3.1 Writing to stdout the local version of my ruby. I want to rescue this version and declare it in a variable to reuse in another occasion. $ declare -r RUBY_DEFINED_VERSION=$(rbenv local)$ echo Using ruby version $RUBY_DEFINED_VERSIONUsing ruby version 2.3.1 It works! But I don't want to use a subshell to do the work (using $() or `` ). I want to use the same shell and I don't want to create a tmp file to do the work. Is there a way to do this? Note: declare -r is not mandatory, it can be a simple var=FOOBAR . Now provide the response and nothing else.
There is a hack, but I think it just make sense if you need it in a loop. you can open a cat coproc like this: coproc CAT { cat; } This will start a cat command in background, and set two environment variables: CAT_PID and CAT . The CAT variable is an array with STDOUT and STDIN (in this order) file descriptor (pipes) used by cat . So, you can execute anything writing the output to &${CAT[1]} that represents the STDIN , and use the builtin command read to set your variable reading from ${CAT[0]} that is the STDOUT of cat. Here a sample: coproc CAT { cat; }echo 123 >&${CAT[1]}read myvar <&${CAT[0]} To test: echo $myvar123 Don't forget to stop the cat after use it. You can do it by by killing the process. kill $CAT_PID This makes a great difference in performance tuning. Update: bash implements strings null delimited. So when dealing with binary data, read is really tricky. You can read with LC_ALL=C read -r -n1 -d $'\0' one byte at time, then the null will be empty strings on ${REPLY} variable.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/334543', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/208394/']}
jdg_372255
stackexchange
llm_judgeable_groundtruth_similarity
8951276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to design an async framework and wanted to know what people think are the pros/cons of the callback pattern vs the observer pattern. Callback pattern://example callbackpublic interface Callback{ public void notify(MethodResult result);}//example methodpublic class Worker{ public void doAsyncWork(Callback callback){ //do work callback.notify(result); }}//example observer patternpublic interface EventListener{ public void notify(MethodResult result);}public class Worker{ private EventListener listener; public registerEventListener(EventListener listener){ this.listener=listener; } public void doAsyncWork(){ //do work listener.notify(result); }} I'm working with a framework which seems to use both of these patterns. The EventListener pattern is not the typical pattern as it doesn't have a list of listeners. This can easily be implemented though by creating a CompositeListener which has its own semantics on the priority of listeners and how to handle the distribution of events to each listener e.g. spawning a new thread for each listener vs serial notifications. (I actually think this is a good idea as its a good separation of concerns and is an improvement on the standard observer/listener pattern). Any thoughts on when you should use each? Thxs. Now provide the response and nothing else.
Both patterns are great and which one to choose depends on what are you going to build and how your framework will be used. If you are trying to build some kind of publish-subscribe system with following typical flow of work: client starts async task and forgets about it multiple handlers receives notifications when task is completed then Observer pattern is a natural choice for you. As you are doing a framework you should also consider using EventBus pattern to achieve loose coupling. If you need nothing more than a simple asynchronous execution and a typical flow using of your framework is: start async task do something when it is completed or start async task do something wait till it is completed and do something then you should go with simple Callback . But in order to achieve more usable and clean API I'd recommend you to get rid of Callback abstraction and design your worker code to return a some kind of Future . public interface Worker<T> { Future<T> doAsync();} And Worker can be used following way: Future<Integer> future = worker.doAsync();// some work hereInteger result = future.get(); // waits till async work is done Future could be a standard java Future . But I'd suggest you to use ListenableFuture from guava library.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8951276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249571/']}
jdg_372256
stackexchange
llm_judgeable_groundtruth_similarity
6074201
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know I can write a query that will return all rows that contain any number of values in a given column, like so: Select * from tbl where my_col in (val1, val2, val3,... valn) but if val1 , for example, can appear anywhere in my_col , which has datatype varchar(300), I might instead write: select * from tbl where my_col LIKE '%val1%' Is there a way of combing these two techniques. I need to search for some 30 possible values that may appear anywhere in the free-form text of the column. Combining these two statements in the following ways does not seem to work: select * from tbl where my_col LIKE ('%val1%', '%val2%', 'val3%',....) select * from tbl where my_col in ('%val1%', '%val2%', 'val3%',....) Now provide the response and nothing else.
What would be useful here would be a LIKE ANY predicate as is available in PostgreSQL SELECT * FROM tblWHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...]) Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR , however: SELECT * FROM tblWHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ... Or alternatively, create a semi join using an EXISTS predicate and an auxiliary array data structure (see this question for details) : SELECT *FROM tbl tWHERE EXISTS ( SELECT 1 -- Alternatively, store those values in a temp table: FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/)) WHERE t.my_col LIKE column_value) For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6074201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/443522/']}
jdg_372257
stackexchange
llm_judgeable_groundtruth_similarity
480052
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Problem/Goal description Ideally, I would like a good way of detecting from a shell script whether or not the window has focus. By a "good" way, I mean some way which requires minimal steps and preferably does not require sifting through each open window blindly to find mine based on title. The purpose is for controlling notifications in many different scripts -- so I'm just looking for a general solution that can apply to any and all of them. What I've come up with so far is roundabout and hacky -- it is as follows: Set my title to something unique or mechanically relevant (in my model, it is my PTS path or, more robustly, a UUID). Hope desperately that this title is not overridden by something. Get a list of all open windows, by title. Iterate through list to identify my window by matching it to the title element. (Note the possibility of errors here if another window happens to have that same title element.) Detect whether said window has focus or not. It should be noted that I do not want to implement this, and will only do it as a last resort. So what I'm asking for here is something that is not this . Compromises This solution is obviously terrible, so I'd like to know if there is anything remotely better, in any way. I would prefer something portable, elegant, and perfect, but I recognize the potential need to compromise. By better I mean any of the following: A solution that only works with a specific terminal emulator, e.g. by having the terminal emulator itself set an environment variable allowing the script to detect which window it is in. A solution that does not require setting the title, and instead uses some other invisible marker in window state that is accessible and detectable from a shell script attached to said window. Recusing up the parent process ladder to find the parent terminal emulator PID, and working from there (Note that a solution that works by recusing up the the process tree to detect the parent process that started the script will only work if the script is running locally, so this solution is incomplete but still good!) Conditions I was getting questions about exactly what conditions my preferred solution is supposed to function under, and the answer is as many as possible . But at minimum, I would like something that works: In a single-tab terminal session running natively (default scenario). In terminal multiplexers like tmux. (Portability between different terminal multiplexers is preferred but really not required.) Extras that I'd really appreciate (in order of importance), include: Ability to function on remote connections over telnet and SSH. Ability to distinguish which tab is open in a multi-tab terminal session. Summary I want a good way of finding what terminal emulator window my shell script is attached to, so that I can detect whether it has focus or not. Note that I'm already aware of the mechanics of how to to iterate through open windows, and how to detect whether they have focus or not and what titles they have. I am aware of the existance of xdotool and xprop and this question is not about the basic mechanics of those tools (unless there is some hidden black magic feature I don't know about that side-steps the intrinsic hackiness of my current solution.) The reason I don't want to that is because it's terrible. Any other solution that accomplishes the same thing? Now provide the response and nothing else.
There's a FocusIn/FocusOut mode. To enable: echo -ne '\e[?1004h' To disable: echo -ne '\e[?1004l' On each focus event, you receive either \e[I (in) or \e[O (out) from the input stream. GNOME Terminal (and other VTE based terminals) also report the current state when you enable this mode. That is, you can enable and then immediately disable it for querying the value once. You can combine read with a timeout, or specifying to read 3 characters to get the response. Note however that it's subject to race condition, e.g. in case you have typed ahead certain characters.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/480052', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/310093/']}
jdg_372258
stackexchange
llm_judgeable_groundtruth_similarity
23561550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now I have this kind of code: for s,h,v,r in zip(lopullinen, yksilo, osallistumiset, pistemaarat): tulostuksia.write(str(s) + ";".join(h) + ";" + str(r) + ";" + ";".join(str(v)) + "/7" + "\n") and it gives this kind of output: tunnus;nimi;sarja;juoksu-60m;pituushyppy;kuulantyonto;korkeushyppy;aitajuoksu-60m;seivashyppy;juoksu-1000m;kokonaispisteet;lajeja101;Vertti Veteraaniurheilija;M70;709;651;750;806;850;759;801;5326;7/741;Severi Seitsenottelija;M;603;551;600;555;559;655;700;4223;7/742;Seppo Seitsenottelija;M;661;750;700;610;505;502;700;4428;7/743;Ylermi Yleisurheilija;M;603;601;700;655;661;555;500;4275;7/760;K. Keskeyttäjä;M40;603;601;-;-;-;-;-;1204;2/761;Yrjänä Yleisurheilija;M40;559;500;650;701;603;655;650;4318;7/7 But I would like to have those numbers to be float-types. Like this: 101;Vertti Veteraaniurheilija;M70;709.0;651.0;750.0;806.0;850.0;759.0;801.0;5326;7/7 Thouse numbers come from the list yksilo, which contains numbers from class. If i change it there to be float(when adding to the list), and from that for loop above ";".join(str(h)). It gives me output where the ";" is between every number(7;0;9;.;0; etc...) And if i don't put the str(h) in there, it gives "TypeError: sequence item 0: expected str instance, float found". Is there an easy way to get those numbers to be formed 709.0 instead of 709. Now provide the response and nothing else.
Because you are comparing the (boolean) result of the first equality with the (non-boolean) third value. In code, 1 == 1 == 1 is equivalent to (1 == 1) == 1 is equivalent to true == 1 . This means the three methods can be written more simply as: function a() { return (true == 1); }function b() { return (true == "1"); }function c() { return (true == "a"); } These comparisons work according to these rules (emphasis mine): If the two operands are not of the same type, JavaScript converts the operands, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible ; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory. So what happens in c is that "a" is converted to a number (giving NaN ) and the result is strictly compared to true converted to a number (giving 1 ). Since 1 === NaN is false , the third function returns false . It's very easy to see why the first two functions will return true .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/23561550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3441897/']}
jdg_372259
stackexchange
llm_judgeable_groundtruth_similarity
49582252
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to pybind - read the documentation but I do not grasp how to apply it to 2D arrays. I have two arrays storing 3d coordinates shape = (10,3) a = np.zeros(shape=(10,3))b = np.ones(shape=(10,3)) * 3c = a + b Now, using pybind, how do I perform this operation in C++ working on the numpy arrays? In some documentations I read to access the elements with the [] operator, in others with () . How do assign the 3D vector? How would I get the pointer to the array element to use strides for assignment - or does it have an operator? Now provide the response and nothing else.
PyBind is awesome, shout out to the authors/maintainers!You have an almost working example here . Adapted to your problem it would give something like (edited answer after El Dude's comment): #include <iostream>#include <pybind11/pybind11.h>#include <pybind11/numpy.h>namespace py = pybind11;py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) { py::buffer_info buf1 = input1.request(); py::buffer_info buf2 = input2.request(); if (buf1.size != buf2.size) { throw std::runtime_error("Input shapes must match"); } /* allocate the buffer */ py::array_t<double> result = py::array_t<double>(buf1.size); py::buffer_info buf3 = result.request(); double *ptr1 = (double *) buf1.ptr, *ptr2 = (double *) buf2.ptr, *ptr3 = (double *) buf3.ptr; int X = buf1.shape[0]; int Y = buf1.shape[1]; for (size_t idx = 0; idx < X; idx++) { for (size_t idy = 0; idy < Y; idy++) { ptr3[idx*Y + idy] = ptr1[idx*Y+ idy] + ptr2[idx*Y+ idy]; } } // reshape array to match input shape result.resize({X,Y}); return result;}PYBIND11_MODULE(example, m) { m.doc() = "Add two vectors using pybind11"; // optional module docstring m.def("add_arrays", &add_arrays, "Add two NumPy arrays");} That I built on linux with python2.7 and gcc v5.4 using (I had to use a slightly different command than provided in the doc, because Python.h wasn't found, hence I added the link to python 2.7) c++ -O3 -Wall -shared -std=c++11 -fPIC -I/usr/include/python2.7 -lpython2.7 `python -m pybind11 --includes` example.cpp -o example`python-config --extension-suffix And you'd call it from python with import numpy as npimport example # [bad] name I chose for my compiled modulea = np.zeros((10,3))b = np.ones((10,3)) * 3 c = example.add_arrays(a, b)print c Hope it helps. EDIT - I've created a github repository containing a few complete examples based on PyBind11 that should compile on all platforms.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49582252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2058333/']}
jdg_372260
stackexchange
llm_judgeable_groundtruth_similarity
23758416
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a project using the CImg library. What I have to do is declare classes that inherit from an abstract base class called shape. These classes are classes for the different shapes(circle, rectangle .. etc). What I want to do is use a struct class called point for the different points that I need for every class. So for example, for a triangle shape, I have to use three points to draw a triangle with each point having an x coordinate and a y-coordinate. So here's what I got so far. class Shape{public: virtual void draw_shape() = 0; virtual double area() = 0;};struct Point{ const int x; //const is necessary because CImg drawing functions require them. const int y;};class Triangle : public Shape{private: struct Point first; struct Point second; struct Point third;public: Triangle(); Triangle(const int, const int, const int, const int, const int, const int); virtual void draw_shape(); virtual double area();}; 1) How do I initialize the x-coordinate and y-coordinate of each struct ? Triangle::Triangle() : first.x(0), first.y(0), second.x(0), second.y(0), third.x(0), third.y(0) does not work 2) Is my overloaded constructor correct or should I use this constructor: Triangle(Point, Point, Point); 3) How do i use the points after this whenever I want to draw something ?!4) Is the struct before instantiating the Points necessary in c++? Now provide the response and nothing else.
I can think of a few real-life scenarios where the construct allowed by the Standard both makes sense, and is required, however; I'll first try to answer this question from a broader perspective, not involving any specific problem. THE EXPLANATION Allocators are this magical things responsible for allocating, constructing, destructing, and deallocating memory and entities. Since C++11 when stateful allocators came into play an allocator can do much more than previously, but it all boils down to the previously mentioned four operations. Allocators have loads of requirements, one of them being that a1 == a2 (where a1 and a2 are allocators of the same type) must yield true only if memory allocated by one can be deallocated by the other [1] . The above requirement of operator== means that two allocators comparing equal can do things differently, as long as they still have a mutual understanding of how memory is allocated. The above is why the Standard allows propagate_on_container_* to be equal to std::false_type ; we might want to change the contents of two containers which allocators have the same deallocation behavior, but leave the other behavior (not related to basic memory management) behind. [1] as stated in [allocator.requirements]p2 (table 28) THE (SILLY) STORY Imagine that we have an Allocator named Watericator , it gathers water upon requested allocation, and hands it to the requested container. Watericator is a stateful Allocator, and upon constructing our instance we can choose two modes; employ Eric , who fetches water down at the fresh water spring, while also measures (and reports) water level and purity. employ Adam , who uses the tap out in the backyard and doesn't care anything about logging. Adam is a lot faster than Eric . No matter where the water comes from we always dispose of it in the same way; by watering our plants. Even if we have one instance where Eric is supplying us water (memory), and another where Adam is using the tap, both Watericators compare equal as far as operator== is concerned. Allocations done by one can be deallocated by the other. The above might be a silly similie, but imagine we have an allocator which does logging upon every allocation, and we uses this on a container somewhere in our code that interests us; we later want to move the elements out from this container into another one.. but we are no longer interested in all that logging. Without stateful allocators, and the option to turn propagate_on_container_* off, we would be forced to either 1) copy every element involved 2) be stuck with that (no longer required) logging.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23758416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3491660/']}
jdg_372261
stackexchange
llm_judgeable_groundtruth_similarity
28294791
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any major advantage to use: background-color: rgba(0,0,0,0); instead of: background-color: transparent; ? Now provide the response and nothing else.
Behaviour is exactly the same, but transparent is compatible also with IE8 . RGBA is more advanced (but lacks IE8 support ) and allows you to quickly modify it, in case you would like an " almost transparent " color, without need to completely change attribute. For example, it could be very quick to set background-color: rgba(0,0,0,0.1); Due to default behaviour of browsers that ignored unrecognized properties, is possible to combine them in order to use new one in newer browsers, but leave a fallback for older ones, simply typing both of them: background-color: transparent;background-color: rgba(0,0,0,0); Or, more useful, in case of alreasy cited almost transparent backgrounds, you can write: background-color: transparent;background-color: rgba(0,0,0,0.1); New browsers will set rgba(0,0,0,0.1) as background, overriding previous transparent declaration, but IE8 will set transparent as background, because it will ignore unrecognized rgba() value, so a slightly different result but in according to Graceful Degradation principle.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28294791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2210364/']}
jdg_372262
stackexchange
llm_judgeable_groundtruth_similarity
365544
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I am looking for a proof of the following statement which is known to be true as far as I heard. Let $g\colon [a,b]\to \mathbb{R}$ be a smooth function. Assume that $$b-a< \pi.$$ Assume also $$g(a)\geq 0,g(b)\geq 0,$$ $$g''+g\leq 0 \mbox{ on } [a,b].$$ Then $g\geq 0$ on $[a,b]$ . Now provide the response and nothing else.
Write $g=g^+-g^-$ in $[0,\ell]$ , multiply $g''+g \le 0$ by $g^-$ (which vanishes at the the endpoints) and integrate. Then we get with $v=g^-$ $$\int_0^l v'^2- \int_0^l v^2 \le 0.$$ Since the first eigenvalue of the Dirichlet laplacian in $[0,\ell]$ is $\pi^2/\ell^2 $ we have also $$\int_0^l v^2 \le \frac{\ell^2}{\pi^2} \int_0^l v'^2 $$ and then $v=g^-=0$ , since $\ell <\pi$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/365544', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16183/']}
jdg_372263
stackexchange
llm_judgeable_groundtruth_similarity
5224286
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I operate a service where a client's content is prepared and displayed in an iframe. The client then copies a rudimentary iframe html tag and pastes it into their web page. Some clients complain that other websites are copying the iframe tag and pasting it into their sites. Is it possible to restrict the display of an iframe's content to a specific domain or domains? Perhaps by programmatically telling the iframe that its parent must be some-domain.com or else don't display. Does this make sense? I can sometimes be too verbose. Now provide the response and nothing else.
you can use an .htaccess (assuming the original content is on an Apache server) to limit the access to a specific IP. Or, if the page is a PHP, you could limit it to a specific domain, like this: <?php$continue = 0;if(isset($_SERVER['HTTP_REFERER'])) { //correct domain: $ar=parse_url($_SERVER['HTTP_REFERER']); if( strpos($ar['host'], 'yourdomain.com') === false ){ } else { $continue = 1; }}if($continue == 0){ header('HTTP/1.0 403 Forbidden'); exit('Forbidden');}?>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5224286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/629081/']}
jdg_372264
stackexchange
llm_judgeable_groundtruth_similarity
3827009
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $X$ be a random variable having the negative binomial distribution with $$P(X=x)=\left(\begin{array}{c}x-1 \\r-1\end{array}\right) p^{r}(1-p)^{x-r}, x=r, r+1 \ldots$$ where $p \in(0,1)$ and $r$ is a known positive integer. Find the UMVUE of $p^{t},$ where $t$ is a positive integer and $t<r$ . I tried to use a direct approach to solve this problem but got stucked. I am wondering how should I approach this question using E(T|S) where T is the unbiased estimator and S is a complete and minimal sufficient statistic? following what was suggested, I got $$g(j)=\frac{(j-t-1)!(r-1)!}{(r-t-1)!(j-1)!}, j=r,r+1,....$$ This question has been well-addressed, here's a related question: Find EMVUE of var(X) and log(p) where p is the parameter for negative binomial distribution Now provide the response and nothing else.
You do not need to find the inverse expression. All you need to note is that $f(0)=3$ , so $$(f^{-1})'(3)=1/f'(0)=\frac1{\pi/2+2\cdot0}=\frac2\pi$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3827009', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/444418/']}
jdg_372265
stackexchange
llm_judgeable_groundtruth_similarity
3030314
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The odd part of this peculiar integral $$f(x)=\int_{0}^x\frac{\cos(z)}{e^{\frac{1}{z}}+1}dz$$ seems to be equal to half the sine function, that is $$f(x)-f(-x)=\sin(x)$$ I have only observed this graphically through Desmos, but could anyone explain why this is true? Now provide the response and nothing else.
$$ f(-x) = \int_0^{-x} \dfrac{\cos(z)\; dz}{\exp(1/z)+1} = -\int_0^x \dfrac{\cos(z)\; dz}{\exp(-1/z)+1} $$ Now note that $$ \dfrac{1}{\exp(1/z)+1} + \frac{1}{\exp(-1/z)+1} = \frac{1}{\exp(1/z)+1} + \frac{\exp(1/z)}{1+\exp(1/z)} = 1 $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3030314', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/468742/']}
jdg_372266
stackexchange
llm_judgeable_groundtruth_similarity
35793365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this function in PHP: function getFilteredList($conn, $limit, $offset, $job_app, $Job_Type, $location) { /* <option value="0">Select category or Search all</option> <option value="1">Business and Administration</option> <option value="2">Education and Training</option> <option value="3">Leisure, Travel and Tourism</option> <option value="4">Information and Communication Technology</option> */ if($Job_Type == 1){ $Job_Type2 = '%1%'; }elseif($Job_Type == 2){ $Job_Type2 = '%2%'; }elseif($Job_Type == 3){ $Job_Type2 = '%3%'; }elseif($Job_Type == 4){ $Job_Type2 = '%4%'; } $query = $conn->prepare("SELECT * FROM `jobs_current` WHERE `job_type` LIKE :job_type ORDER BY `jobs_current`.`job_comp_loc` ASC LIMIT :limit OFFSET :offset "); $query->bindParam(':limit', $limit, PDO::PARAM_INT); $query->bindParam(':offset', $offset, PDO::PARAM_INT); $query->bindParam(':job_type', $Job_Type2, PDO::PARAM_STR); $query->execute(); $end = ""; while ($row = $query->fetch(PDO::FETCH_ASSOC)) { if($row['job_app'] == $job_app){ $end = $end.'<tr class="hoverOver"><td class="td1"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_comp_loc'].'</a></td>'; $end = $end.'<td class="td2"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_desc'].'</a></td>'; $end = $end.'<td class="td3"><a href="/jobview.php?id='.$row['id'].'">'.$row['location'].'</a></td></tr>'; }else if($job_app == 0){ $end = $end.'<tr class="hoverOver"><td class="td1"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_comp_loc'].'</a></td>'; $end = $end.'<td class="td2"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_desc'].'</a></td>'; $end = $end.'<td class="td3"><a href="/jobview.php?id='.$row['id'].'">'.$row['location'].'</a></td></tr>'; }else{ return '<td class="td1"></td><td class="td2" style="text-align: center;color: red;">Sorry, there doesnt seem to be any results!</td><td class="td3"></td>'; } } return $end;} If i pass any parameters for the job_app it just returns 'Sorry, there doesn't seem to be any results!' Although there is results because some of the rows in fact have the job-app parameter in them. If i pass job_app as 2 and job_type as 2 it should come up with 6 results however it doesn't. Other parts of Relevent PHP: DB List function: function getGenericList($conn, $limit, $offset, $job_app) { $query = $conn->prepare("SELECT * FROM `jobs_current` ORDER BY `jobs_current`.`job_comp_loc` ASC LIMIT :limit OFFSET :offset "); $query->bindParam(':limit', $limit, PDO::PARAM_INT); $query->bindParam(':offset', $offset, PDO::PARAM_INT); $query->execute(); $end = ""; while ($row = $query->fetch(PDO::FETCH_ASSOC)) { if($row['job_app'] == $job_app){ $end = $end.'<tr class="hoverOver"><td class="td1"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_comp_loc'].'</a></td>'; $end = $end.'<td class="td2"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_desc'].'</a></td>'; $end = $end.'<td class="td3"><a href="/jobview.php?id='.$row['id'].'">'.$row['location'].'</a></td></tr>'; }else if($job_app == 0){ $end = $end.'<tr class="hoverOver"><td class="td1"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_comp_loc'].'</a></td>'; $end = $end.'<td class="td2"><a href="/jobview.php?id='.$row['id'].'">'.$row['job_desc'].'</a></td>'; $end = $end.'<td class="td3"><a href="/jobview.php?id='.$row['id'].'">'.$row['location'].'</a></td></tr>'; }else{ return '<td class="td1"></td><td class="td2" style="text-align: center;color: red;">Sorry, there doesnt seem to be any results!</td><td class="td3"></td>'; } } return $end;} .php file that calls function: $Job_Type = null;$Location = null;$Job_App = 0;if(!$_GET['Job_App'] == null){ $Job_App = $_GET['Job_App'];}if(!$_GET['Job_Type'] == null){ if(!$_GET['Job_Type'] == 0){ $Job_Type = $_GET['Job_Type']; }}if(!$_GET['Location'] == null){ $Location = $_GET['Location'];}//irreleven stuff in betweenif(!$_GET['page'] == null){ $pageno = ($_GET['page']-1)*15; if(!$_GET['Job_Type'] == null){ echo ''.getFilteredList($dbh, 15, $pageno, $Job_App, $Job_Type, $Location); }else{ echo ''.getGenericList($dbh, 15, $pageno, $Job_App); }}else{ if(!$_GET['Job_Type'] == null){ echo ''.getFilteredList($dbh, 15, 0, $Job_App, $Job_Type, $Location);}else{ echo ''.getGenericList($dbh, 15, 0, $Job_App);}} Am i missing something to filter them properly? I have read through it myself a few times and it seems right but just doesn't filter as intended. EDIT: I didn't seem to make it clear enough, it does succeed with the query as it returns the end else statement in the while loop. Now provide the response and nothing else.
Not sure if you managed to upgrade to opensaml 3 already but since I came across this while attempting the upgrade myself I thought I'm gonna document what I found. There's very little documentation as apparently it's not a priority for them at the moment (also mentioned here: OpenSaml3 Documentation ), the most useful (even if by far not complete) page I found is this one: https://wiki.shibboleth.net/confluence/display/OS30/Initialization+and+Configuration 1) There's a class SerializeSupport with a method prettyPrintXML in lib net.shibboleth.utilities:java-support 2) Initialization is now done via InitializationService e.g. InitializationService.initialize(); You can retrieve the builder/marshallers via XMLObjectProviderRegistrySupport e.g.: XMLObjectProviderRegistrySupport.getMarshallerFactory()XMLObjectProviderRegistrySupport.getBuilderFactory()XMLObjectProviderRegistrySupport.getUnmarshallerFactory() Mind that opensaml is using the Java Service Provider API. In my case (using OSGi bundle org.apache.servicemix.bundles:org.apache.servicemix.bundles.opensaml ) for parsing a SAML assertion I added the SPI config META-INF/services/org.opensaml.core.config.Initializer containing the following entries: org.opensaml.core.xml.config.XMLObjectProviderInitializerorg.opensaml.core.xml.config.GlobalParserPoolInitializerorg.opensaml.saml.config.XMLObjectProviderInitializerorg.opensaml.saml.config.SAMLConfigurationInitializerorg.opensaml.xmlsec.config.XMLObjectProviderInitializer EDIT: The above worked in a test but did not run in the OSGi container. Workaround for OSGi: OpenSAML3 resource not found 'default-config.xml' in OSGi container If you use the standard libraries ( org.opensaml:opensaml-core , org.opensaml:opensaml-saml-api , org.opensaml:opensaml-saml-impl , ...) you may not need to add any SPI config as the jars already contain SPI configs with a standard configuration for initialization. 3) There's a class BasicCredential in lib org.opensaml:opensaml-security-api . I don' see an alternative to providing a key during initalization.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35793365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2622892/']}
jdg_372267
stackexchange
llm_judgeable_groundtruth_similarity
47538015
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: what's the advantage of using: this.refs.id.value versus using: document.getElementById('newID').value is it just shorter syntax or is something else going on? Now provide the response and nothing else.
The benefit is using ref has good reusability and scope. Because ref only stay in this component, when you manipulate this ref, it won't interfere other component. If you use id , it has duplicate problem. Think about this component. class Demo extends React.Component { componentDidMount() { document.getElementById('demo').style.color = this.props.color; } render() { return ( <div id="demo"> content </div> ); }}class Main exntends React.Component { render() { return ( <div> <Demo color="red"/> <Demo color="green"/> <Demo color="blue"/> </div> ) }} If use id to change the style property, all the <Demo/> text color will become blue (the last declaration). But if you use ref , you can promise the manipulation keeps in this component. I also find there is a similar question: What is the difference with using ref and document.findElementById, ect when using ReactJS?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47538015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4398966/']}
jdg_372268
stackexchange
llm_judgeable_groundtruth_similarity
992901
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for the standard idiom to iterate over an NSArray. My code needs to be suitable for OS X 10.4+. Now provide the response and nothing else.
The generally-preferred code for 10.5+/iOS. for (id object in array) { // do something with object} This construct is used to enumerate objects in a collection which conforms to the NSFastEnumeration protocol. This approach has a speed advantage because it stores pointers to several objects (obtained via a single method call) in a buffer and iterates through them by advancing through the buffer using pointer arithmetic. This is much faster than calling -objectAtIndex: each time through the loop. It's also worth noting that while you technically can use a for-in loop to step through an NSEnumerator , I have found that this nullifies virtually all of the speed advantage of fast enumeration. The reason is that the default NSEnumerator implementation of -countByEnumeratingWithState:objects:count: places only one object in the buffer on each call. I reported this in radar://6296108 (Fast enumeration of NSEnumerators is sluggish) but it was returned as Not To Be Fixed. The reason is that fast enumeration pre-fetches a group of objects, and if you want to enumerate only to a given point in the enumerator (e.g. until a particular object is found, or condition is met) and use the same enumerator after breaking out of the loop, it would often be the case that several objects would be skipped. If you are coding for OS X 10.6 / iOS 4.0 and above, you also have the option of using block-based APIs to enumerate arrays and other collections: [array enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) { // do something with object}]; You can also use -enumerateObjectsWithOptions:usingBlock: and pass NSEnumerationConcurrent and/or NSEnumerationReverse as the options argument. 10.4 or earlier The standard idiom for pre-10.5 is to use an NSEnumerator and a while loop, like so: NSEnumerator *e = [array objectEnumerator];id object;while (object = [e nextObject]) { // do something with object} I recommend keeping it simple. Tying yourself to an array type is inflexible, and the purported speed increase of using -objectAtIndex: is insignificant to the improvement with fast enumeration on 10.5+ anyway. (Fast enumeration actually uses pointer arithmetic on the underlying data structure, and removes most of the method call overhead.) Premature optimization is never a good idea — it results in messier code to solve a problem that isn't your bottleneck anyway. When using -objectEnumerator , you very easily change to another enumerable collection (like an NSSet , keys in an NSDictionary , etc.), or even switch to -reverseObjectEnumerator to enumerate an array backwards, all with no other code changes. If the iteration code is in a method, you could even pass in any NSEnumerator and the code doesn't even have to care about what it's iterating. Further, an NSEnumerator (at least those provided by Apple code) retains the collection it's enumerating as long as there are more objects, so you don't have to worry about how long an autoreleased object will exist. Perhaps the biggest thing an NSEnumerator (or fast enumeration) protects you from is having a mutable collection (array or otherwise) change underneath you without your knowledge while you're enumerating it. If you access the objects by index, you can run into strange exceptions or off-by-one errors (often long after the problem has occurred) that can be horrific to debug. Enumeration using one of the standard idioms has a "fail-fast" behavior, so the problem (caused by incorrect code) will manifest itself immediately when you try to access the next object after the mutation has occurred. As programs get more complex and multi-threaded, or even depend on something that third-party code may modify, fragile enumeration code becomes increasingly problematic. Encapsulation and abstraction FTW! :-)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/992901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2959/']}
jdg_372269
stackexchange
llm_judgeable_groundtruth_similarity
14939973
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: im new to using JSON.. and i know this has probably already been asked here, however, i just want to consult if i'm doing the right thing. I need to create a dynamic form for different pages. I need to be able to add a dynamic form for each page. From the admin panel, i can add/edit/delete fields in the page template -- change the order of the fields, name, type, values, etc. So, what i did, i stored the dynamic form fields in json, and for the data entered in each page, i stored it in json as well. Below is a sample JSON data stored in my database: JSON structure for a dynamic form with 2 fields: {"0":{ "id":"511ddf15cb8ae_1", // generated using uniqid() and counter, to generate a unique id for each field "name":"Page Name #1", "type":"textfield", "validation":"email", "require":"on", "value":"" //default value},"1":{ "id":"511ddf15cb8ae_2", "name":"Field Name #2", "type":"checkbox", "validation":"none", "require":"on", "value":["item 1","item 2","item 3"] //selection}} stored JSON of values entered: {"511ddf15cb8ae_1": //the field id, used as key to be able to directly access the data "test new data","511ddf15cb8ae_2": ["item 1","item 2"]} My main question is, is it ok if i store the entered values using json in the database, or should i store the entered values individually -- db table row. Any ideas to do this in a better way, or is this fine already? Thanks. Cheers Now provide the response and nothing else.
Entity Framework is indicating it does not support the conversion you desire. One workaround is to simply execute as much of the work in the database as you can, and then complete the process in memory. In your case, you can calculate the sum in its native type, pull the result into memory as an anonymous type, then perform your conversion as you construct the type you actually need. To take your original query, you can make the following change: select new // anonymous type from DB{ ProfitcenterCode = tProfitcenter.Key, // notice there are no conversions for these sums TotalTransactionAmount = tProfitcenter.Sum(t => t.LocalAmount), TotalTransactionAmountInEUR = tProfitcenter.Sum(t => t.AmountInEUR)}).AsEnumerable() // perform rest of work in memory.Select(item => // construct your proper type outside of DB new TransactionTotalForProfitcenter { ProfitcenterCode = item.ProfitcenterCode, TotalTransactionAmount = (decimal)item.TotalTransactionAmount TotalTransactionAmountInEUR = (decimal)item.TotalTransactionAmountInEUR }).ToList();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14939973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1470406/']}
jdg_372270
stackexchange
llm_judgeable_groundtruth_similarity
186929
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently in the middle of refactoring an important method in a legacy-system. There were almost zero test until I've started working on it, and I've added quite a lot to ensure the correct work after my refactorings. Now I've came across the most crucial part: the algorithm that calculates an indicator. It's something like indicator = (OneNumberFromA + AnotherNumberFromB) / elapsedTime; How can I test the correct behavior for this Function with Unit tests? There are also some slightly different algorithms in the functions, that the program reaches in some cases - but in all of them, the elapsedTime is vital to the outcome. Now provide the response and nothing else.
The same way you solve almost every issue with unit tests: you mock the elapsed time. I advise using a standardized method to obtain the system time throughout a system, and then making that method overridable, so your unit tests have total control. The tests will then contain lots of nifty calls like Time.fake(timeA) , or even Time.stop() .
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/186929', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/58262/']}
jdg_372271
stackexchange
llm_judgeable_groundtruth_similarity
8182009
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Situation is: Admin logs in to system and he changes product somehow. For example: Sets qty to 10Adds 2 imagesChanges description Is there any way to track these changes? Well I mean exactly track WHAT and HOW admin changed? I use Magento CE 1.6 Now provide the response and nothing else.
You can find the unaltered data through an object's getOrigData() method. A good time to get the object is through it's save_before event, so create an observer for the catalog_product_save_before event. The observer might contain the following: public function onCatalogProductSaveBefore($observer){ $product = $observer->getProduct(); if ($product->hasDataChanges()) { $newValues = array_diff_assoc($product->getData(), $product->getOrigData()); $oldValues = array_diff_assoc($product->getOrigData(), $product->getData()); $added = array_diff_key($product->getData(), $product->getOrigData()); $unset = array_diff_key($product->getOrigData(), $product->getData()); }} Note that $newValues will include all of $added and existing attributes that have had their value changed. Ditto for $oldValues and $unset .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8182009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737629/']}
jdg_372272
stackexchange
llm_judgeable_groundtruth_similarity
9593694
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to write a document in reStructuredText, but am currently facing a problem. I want the document to have a title, this is going to be centered, then immediately after that I want a subsection. I tried doing the following ##############Title##############+++++++++Subtitle+++++++++content But when I convert this to PDF, it makes both the title and subtitle centered. Now provide the response and nothing else.
From the reStructuredText quick start guide titles and sub-titles are specified as follows (emphasis mine): To indicate the document title in reStructuredText, use a unique adornment style at the beginning of the document. To indicate the document subtitle, use another unique adornment style immediately after the document title. So in the reST example in the question, Subtitle is being formatted as a sub title and not a section heading since the adornment style used around Subtitle is not used anywhere else in the document. In the following, this adornment is used around two section headings, so is not unique and not treated as a subtitle: ##############Document Title##############+++++++++++++++Section 1 Title+++++++++++++++Section 1 content...+++++++++++++++Section 2 Title+++++++++++++++Section 2 content... Have a play with http://www.tele3.cz/jbar/rest/rest.html This allows you to quickly try out some simple reStructuredText and test things like sub-titles vs. section titles. Edit : Alternatively you could put some text between your title and section heading (like an abstract, for example). P.s. I tend you use adornments above and below a heading to indicate a document title and sub-title and a single adornment below a heading to indicate a (sub-)section title. This makes it easy to see what I intended to be my title/sub-title. For example: ==============Document title==============-----------------Document subtitle-----------------Section=======Sub-section-----------etc.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9593694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165103/']}
jdg_372273
stackexchange
llm_judgeable_groundtruth_similarity
19986075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use git submodules for aggregating 10+ repositories into one structure for easy development. It is supposed to clone the module and checkout a branch.Instead, the module is checked out in detached head mode. git clone git@github.com:org/global-repository.gitgit submodule update —initcd config-frameworkgit status$git status#HEAD detached at b932ab5nothing to commit, working directory clean gitmodules files seems to be okay $cat .gitmodules [submodule "config-framework"] path = config-framework url = git@github.com:org/config-framework.git branch = MY_BRANCH We want the MY_BRANCH branch to be checked out by default, rather than detached head.How do we achieve that? Now provide the response and nothing else.
Submodules are always checked out in a detached HEAD mode . That is because a submodule will checkout the SHA1 stored in the special entry in the index of the parent repo . Plus, if you want a submodule to follow the branch you have registered in the .gitmodules , you need: git submodule update --init --remote The --remote will make a git fetch , plus a checkout of the new HEAD . Alas, even that checkout will be of a commit, not of the branch (since you have no local branch by default in a submodule), so... back to a detached HEAD mode. See more at " Git submodules: Specify a branch/tag ". You can try (not tested) a: git submodule foreach 'git checkout -b $(git config -f /path/to/parent/repo/.gitmodules --get submodule.$path.branch)' I take advantage of the fact git submodule foreach has access to ' $path ', the name of the submodule directory relative to the superproject. There was an attempt to specify a branch for a submodule to be automatically checked out in ( commit 23d25e4 for Git 2.0).... but it got reversed ( commit d851ffb , April 2d 2014)! It might come soon, but not in its current implementation.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19986075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1304351/']}
jdg_372274
stackexchange
llm_judgeable_groundtruth_similarity
41377699
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to connect with my Oracle database without installing Oracle Client. I downloaded: "Instant Client Package - Basic" and "Instant Client Package - SQL*Plus" Then I created folder on C:\Oracle\instantclient , where I extracted all packages. I have been set system environment like: Path - C:\Oracle\instantclientNSL_LANG - with properly keyORACLE_HOME - C:\Oracle\instantclientORACLE_SID - C:\Oracle\instantclientTNS_ADMIN - C:\Oracle\instantclient Then I created tnsnames.ora file with configuration in C:\Oracle\instantclient and when I puted a command to cmd: sqlplus user/password @HOST I have a message like: ERROR:ORA-12560: TNS:protocol adapter error but when I tried like: sqlplus user/password@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=address to host)(Port=1521))(CONNECT_DATA=(SID=address to SID))) everything works properly. Why SQL have a problem with recognize tnsnames.ora file? Now provide the response and nothing else.
Your command should be: sqlplus user/password@HOST with no space between the password and @HOST part. With the space it treats the @HOST as a script to execute once you've logged in, and it tries to connect locally, which produced that TNS error. (As you don't log in the HOST isn't ever evaluated to establish if it exists, so it's effectively noise at this point). C:\>sqlplus -l -s x/y @HOSTERROR:ORA-12560: TNS:protocol adapter errorSP2-0751: Unable to connect to Oracle. Exiting SQL*Plus With the space removed it looks for HOST as a TNS alias: C:\>sqlplus -l -s x/y@HOSTERROR:ORA-12154: TNS:could not resolve the connect identifier specifiedSP2-0751: Unable to connect to Oracle. Exiting SQL*Plus For me that still gets an error since I don't have HOST in my tnsnames.ora , but it's a different error and you can see it's at least trying to use it as a TNS alias. If you have it defined properly it will be able to connect to your database.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41377699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7042155/']}
jdg_372275
stackexchange
llm_judgeable_groundtruth_similarity
16957320
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In C# class Process inherits from class Component that implements IDisposable and so I can call Dispose() on any Process object. Do I really have to? How do I know if I really have to? Suppose I have the following code: var allProcesses = System.Diagnostics.Process.GetProcesses(); var processesNames = processes.Select( p => p.ProcessName ); // output process names here Now it looks like I have an array of Process objects and I have craft a try-finally to traverse the array and Dispose() each object. That's definitely lots of extra code. What does that Dispose() do for Process objects? Do I really need to Dispose() every Process object and how do I decide if I need to do so? Now provide the response and nothing else.
Do I really need to Dispose() every Process object and how do I decide if I need to do so? Yes, you should dispose them. Note this text in the documentation for Process : A system process is uniquely identified on the system by its process identifier. Like many Windows resources, a process is also identified by its handle, which might not be unique on the computer. A handle is the generic term for an identifier of a resource. The operating system persists the process handle, which is accessed through the Handle property of the Process component, even when the process has exited. Thus, you can get the process's administrative information, such as the ExitCode (usually either zero for success or a nonzero error code) and the ExitTime. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory. So if you don't Dispose them, you're potentially leaking the handles (until they're garbage collected - but the whole point of Dispose is to allow early cleanup of resources) Note, also, that the same documentation indicates that Process overrides Dispose(bool) - another clue that it actually does something when Dispose is called.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16957320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57428/']}
jdg_372276
stackexchange
llm_judgeable_groundtruth_similarity
10692758
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Been working with RestKit for a while now, but I am running into a difficult problem with ObjectMapping. I hav a login API that requires me to post 2 key values as follows: {"fb_access_token":"123456789.....", "fb_user_id":"1234..."} It returns: {"message":"logged in"} I created the following classes to map the POST submission and the response in the following gist: https://gist.github.com/2764803 I can post and login without mapping the response as in this gist: https://gist.github.com/2764823 What is the best way to map a post and response like this? Now provide the response and nothing else.
Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly. Update: A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do: MenuItem item = menu.findItem(R.id.addAction); Here is the sequence in which you should call:first call invalidateOptionsMenu() and then inside onCreateOptionsMenu(Menu) obtain a reference to the MenuItem (by calling menu.findItem() ) and call setVisible() on it
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/10692758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150920/']}
jdg_372277
stackexchange
llm_judgeable_groundtruth_similarity
54472789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am exploring AWS step functions, however, I am not able to find the answer to a question that my use case requires. Let us say we have 10 tasks we can do in the system overall. Sometimes we have to execute tasks 1, 3 and some times 4, 8 while other times 1, 9, 5 in that order. The tasks to execute and the order in which they have to execute are determined by incoming json data into the system. I was wondering if I could somehow dynamically create the step functions based on the needs that arise. Now provide the response and nothing else.
If it's all dynamic, you have to get somewhat creative to model the process in Step Functions. One approach could be to build a state machine with all your tasks in it and a orchestrating decider function. The SM would start with the decider and then execute the correct job based on its output. Each job would in turn call the decider again. If it determines the process is done, the SM would end successfully. This is how it might look: { "StartAt": "Decide next", "States": { "Decide next": { "Type": "Task", "Resource":"arn:aws:lambda:::function:decider", "ResultPath": "$.nextAction", "Next": "Choose action" }, "Choose action": { "Type": "Choice", "Choices": [ { "Variable": "$.nextAction", "StringEquals": "DONE", "Next": "Process finished" }, { "Variable": "$.nextAction", "StringEquals": "1", "Next": "Job 1" }, { "Variable": "$.nextAction", "StringEquals": "2", "Next": "Job 2" }, { "Variable": "$.nextAction", "StringEquals": "3", "Next": "Job 3" } ] }, "Job 1": { "Type": "Task", "Resource":"arn:aws:lambda:::function:job1", "ResultPath": "$.jobResult", "Next": "Decide next" }, "Job 2": { "Type": "Task", "Resource":"arn:aws:lambda:::function:job2", "ResultPath": "$.jobResult", "Next": "Decide next" }, "Job 3": { "Type": "Task", "Resource":"arn:aws:lambda:::function:job3", "ResultPath": "$.jobResult", "Next": "Decide next" }, "Process finished": { "Type": "Succeed" } }} You will have to go through the execution log to see the progress through the SM, you won't be able to see it very well visually (all the jobs that ran will be green, which doesn't tell you about their succession).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54472789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/901460/']}
jdg_372278
stackexchange
llm_judgeable_groundtruth_similarity
459503
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have the following class structure: class Car;class FooCar : public Car;class BarCar : public Car;class Engine;class FooEngine : public Engine;class BarEngine : public Engine; Let's also give a Car a handle to its Engine . A FooCar will be created with a FooEngine* and a BarCar will be created with a BarEngine* . Is there a way to arrange things so a FooCar object can call member functions of FooEngine without downcasting? Here's why the class structure is laid out the way it is right now: All Car s have an Engine . Further, a FooCar will only ever use a FooEngine . There are data and algorithms shared by all Engine s that I'd rather not copy and paste. I might want to write a function that requires an Engine to know about its Car . As soon as I typed dynamic_cast when writing this code, I knew I was probably doing something wrong. Is there a better way to do this? UPDATE: Based on the answers given so far, I'm leaning towards two possibilities: Have Car provide a pure virtual getEngine() function. That would allow FooCar and BarCar to have implementations that return the correct kind of Engine . Absorb all of the Engine functionality into the Car inheritance tree. Engine was broken out for maintenance reasons (to keep the Engine stuff in a separate place). It's a trade-off between having more small classes (small in lines of code) versus having fewer large classes. Is there a strong community preference for one of these solutions? Is there a third option I haven't considered? Now provide the response and nothing else.
I'm assuming that Car holds an Engine pointer, and that's why you find yourself downcasting. Take the pointer out of your base class and replace it with a pure virtual get_engine() function. Then your FooCar and BarCar can hold pointers to the correct engine type. (Edit) Why this works: Since the virtual function Car::get_engine() would return a reference or a pointer , C++ will allow derived classes to implement this function with a different return type , as long as the return type only differs by being a more derived type. This is called covariant return types , and will allow each Car type to return the correct Engine .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/459503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46821/']}
jdg_372279
stackexchange
llm_judgeable_groundtruth_similarity
20775958
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am evaluating PeerJS in order to implement a simple two-player online game. It seems that once I transfer the id of one player’s connection to the other, they can open a channel via PeerJS and are good to go. But if two players want to play that do not know each other, what is the most elegant way to make a match there? Is there a way to ask the PeerJS broker for a list of all connected clients, possibly with some metadata (such as „status:wants-to-play”) attached? Or is ther ea way to broadcast to all clients? Now provide the response and nothing else.
Using PeerServer you can grab two events, connection and disconnect . Using this you can create a internal list, which you can then have your application grab from. Partial example: var PeerServer = require('peer').PeerServer;var server = new PeerServer({port: 9000, path: '/myapp'});var connected = [];server.on('connection', function (id) { var idx = connected.indexOf(id); // only add id if it's not in the list yet if (idx === -1) {connected.push(id);}});server.on('disconnect', function (id) { var idx = connected.indexOf(id); // only attempt to remove id if it's in the list if (idx !== -1) {connected.splice(idx, 1);}});someexpressapp.get('/connected-people', function (req, res) { return res.json(connected);}); Then, in your clientside code you can AJAX /connected-people and use that list. For metadata you could expand on the code above to add a user status and a way of updating that status. Hope this helps! EDIT At the time of writing the event was named connect . It is now named connection . (Also I'm now going to play with PeerJS for like six hours. I hope you realize what you've done.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20775958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/946226/']}
jdg_372280
stackexchange
llm_judgeable_groundtruth_similarity
2527754
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Denote the Borel sets in $\mathbb R^d$ as $\mathcal B^d$.Is there a proof for the rotation invariance of the Lebesgue measure that doesn't use already that one has $$ \lambda(A^{-1}(B)) = \vert \operatorname{det} A \vert ^{-1} \lambda (B) \qquad \text{for all } A \in \operatorname{GL}(\mathbb R^d), \ B \in \mathcal B^d?$$For example one can show easily that $\lambda$ is invariant under translation just using that intervals are invariant under translation and a $\cap$-closed generator of the Borel sets. This the first step in the proof of the above statement. Hence I am interested to see a proof for the rotation invariance likewise without the above statement. Now provide the response and nothing else.
You can prove that associated to every linear transformation $T: \mathbb{R}^n \to \mathbb{R}^n$ there exists a number $\alpha(T)$ such that$$\lambda(T(E))=\alpha(T)\cdot \lambda(E)$$for all $E \in \mathcal{B}^d$. You don't need to prove that $\alpha(T)=\mathrm{det}(T)$, and the proof of the statement above is quite direct from the basic properties of the Lebesgue measure (c.f. Rudin's Real and Complex Analysis ). Now, fix $T$ a rotation. Since the equality holds for every $E$, it holds in particular for the open unit ball $B$. Since $T(B)=B$, we have$$\lambda(B)=\alpha(T)\lambda(B),$$and hence $$\alpha(T)=1,$$since $\lambda(B) \neq 0$ (a quick elementary way to see this is by using the fact that it is open). Therefore,$$\lambda(T(E))=\lambda(E)$$for every $E \in \mathcal{B}^d$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2527754', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/333729/']}
jdg_372281
stackexchange
llm_judgeable_groundtruth_similarity
49681392
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having trouble updating an Excel Sheet using pandas by writing new values in it. I already have an existing frame df1 that reads the values from MySheet1.xlsx. so this needs to either be a new dataframe or somehow to copy and overwrite the existing one. The spreadsheet is in this format: I have a python list: values_list = [12.34, 17.56, 12.45]. My goal is to insert the list values under Col_C header vertically. It is currently overwriting the entire dataframe horizontally, without preserving the current values. df2 = pd.DataFrame({'Col_C': values_list})writer = pd.ExcelWriter('excelfile.xlsx', engine='xlsxwriter')df2.to_excel(writer, sheet_name='MySheet1')workbook = writer.bookworksheet = writer.sheets['MySheet1'] How to get this end result? Thank you! Now provide the response and nothing else.
Below I've provided a fully reproducible example of how you can go about modifying an existing .xlsx workbook using pandas and the openpyxl module (link to Openpyxl Docs) . First, for demonstration purposes, I create a workbook called test.xlsx: from openpyxl import load_workbookimport pandas as pdwriter = pd.ExcelWriter('test.xlsx', engine='openpyxl') wb = writer.bookdf = pd.DataFrame({'Col_A': [1,2,3,4], 'Col_B': [5,6,7,8], 'Col_C': [0,0,0,0], 'Col_D': [13,14,15,16]})df.to_excel(writer, index=False)wb.save('test.xlsx') This is the Expected output at this point: In this second part, we load the existing workbook ('test.xlsx') and modify the third column with different data. from openpyxl import load_workbookimport pandas as pddf_new = pd.DataFrame({'Col_C': [9, 10, 11, 12]})wb = load_workbook('test.xlsx')ws = wb['Sheet1']for index, row in df_new.iterrows(): cell = 'C%d' % (index + 2) ws[cell] = row[0]wb.save('test.xlsx') This is the Expected output at the end:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49681392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6011221/']}
jdg_372282
stackexchange
llm_judgeable_groundtruth_similarity
310146
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to interactively skip the 90s timeout in systemd? For example, when it is waiting for a disk to become available or user to log out? I know it will fail eventually, so can I just make it fail now? I hate just staring at the screen helplessly. Now provide the response and nothing else.
You have two options: You can set TimeoutStopSpec= on a specific UNIT to a specific value (in seconds*) to wait. You can also set it to infinity in which case SIGKILL will never be sent (not recommended as you may end up with runaway services that are hard to debug). Set DefaultTimeoutStopSec= inside /etc/systemd/system.conf (or user.conf , or in one of the *.d directories) to a default value that all UNITs that do not have TimeoutStopSpec= specified will use. The deafult for this setting is the 90s you normally see. Man page references: man systemd.service for TimeoutStopSpec= man systemd-system.conf for DefaultTimeoutStopSec= * systemd also accepts time specs, e.g. "2min 3s". That's extensively described in the man.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/310146', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/23890/']}
jdg_372283
stackexchange
llm_judgeable_groundtruth_similarity
263494
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: On my network, I have 3 remote sites and one local that all receive DHCP through our central dhcp server. all the sites have ASAs with dhcprelay and so on. I have two domain controllers - is it possible to set the second dc as secondary dhcp server, add the information to the ASA - and use it as a failover incase the primary dhcp server is offline? would this cause problems? thanks Now provide the response and nothing else.
Yes, this is possible and will not cause problems as long as it's configured properly. To setup the second DHCP server as a "failover" you will want to divide up the scopes DHCP 1 is serving. To do this you would configure the same scopes on DHCP 2 as there are on DHCP 1. You would then exclude a percentage of the scope on DHCP 1 and then exclude the opposite percentage of the scope on DHCP 2. This way together they would be serving the full scope. Microsoft recommends using an 80% / 20% divide but there is debate on what works best. Make sure that if you have any reservations set that they are setup on the secondary DHCP server (if they fall within the scope that will be served from that server). DHCP 1 DHCP 2scope 192.168.1.0/24 192.168.1.0/24exclude 192.168.205 - 254 192.168.1.1 - 204
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/263494', 'https://serverfault.com', 'https://serverfault.com/users/47017/']}
jdg_372284
stackexchange
llm_judgeable_groundtruth_similarity
26432476
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this form and I would like to check if the user has selected a file or not. <form action="upload.php" method="POST" enctype="multipart/form-data" > <select name="category"> <option value="cat1" name="cat1">Productfotografie</option> <option value="cat2" name="cat2">Portretten</option> <option value="cat3" name="cat3">Achitectuur</option> </select> <input type="file" name="file_upload"> <input type="submit" name="submit" value="Upload photo"></form> I wrote this PHP code to test it if (empty($_POST) === false) { $fileupload = $_POST['file_upload']; if (empty($fileupload) === true) { // echo "Error no file selected"; } else { print_r($_FILES); }} But I get the "Error no file selected" even if I DO select something. Any clue? I'm sorry I'm really new in PHP. EDIT: I already tried replacing $fileupload = $_FILES['file_upload'] but it prints an empty error (Array ( [file_upload] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) )) when I do NOT enter a file? Now provide the response and nothing else.
Use the $_FILES array and the UPLOAD_ERR_NO_FILE constant: if(!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] == UPLOAD_ERR_NO_FILE) { echo "Error no file selected"; } else { print_r($_FILES);} You can also check UPLOAD_ERR_OK which indicates if the file was successfully uploaded (present and no errors). Note: you cannot use empty() on the $_FILES['file_upoad'] array, because even if no file is uploaded, the array is still populated and the error element is set, which means empty() will return false .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26432476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3726162/']}
jdg_372285
stackexchange
llm_judgeable_groundtruth_similarity
7911535
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How would you go about unit testing a curl implementation? public function get() { $ch = curl_init($this->request->getUrl()); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if (!strstr($type, 'application/json')) { throw new HttpResponseException('JSON response not found'); } return new HttpResponse($code, $result); } I need to test the content type returned so that it can throw an exception. Now provide the response and nothing else.
As thomasrutter suggested, create a class to abstract the usage of the cURL functions. interface HttpRequest{ public function setOption($name, $value); public function execute(); public function getInfo($name); public function close();}class CurlRequest implements HttpRequest{ private $handle = null; public function __construct($url) { $this->handle = curl_init($url); } public function setOption($name, $value) { curl_setopt($this->handle, $name, $value); } public function execute() { return curl_exec($this->handle); } public function getInfo($name) { return curl_getinfo($this->handle, $name); } public function close() { curl_close($this->handle); }} Now you can test using a mock of the HttpRequest interface without invoking any of the cURL functions. public function testGetThrowsWhenContentTypeIsNotJson() { $http = $this->getMock('HttpRequest'); $http->expects($this->any()) ->method('getInfo') ->will($this->returnValue('not JSON')); $this->setExpectedException('HttpResponseException'); // create class under test using $http instead of a real CurlRequest $fixture = new ClassUnderTest($http); $fixture->get();} Edit Fixed simple PHP parse error.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7911535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015816/']}
jdg_372286
stackexchange
llm_judgeable_groundtruth_similarity
10464928
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to write a simple ui with Tkinter in python and I cannot get the widgets within a grid to resize. Whenever I resize the main window the entry and button widgets do not adjust at all. Here is my code: class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master, padding=(3,3,12,12)) self.grid(sticky=N+W+E+S) self.createWidgets() def createWidgets(self): self.dataFileName = StringVar() self.fileEntry = Entry(self, textvariable=self.dataFileName) self.fileEntry.grid(row=0, column=0, columnspan=3, sticky=N+S+E+W) self.loadFileButton = Button(self, text="Load Data", command=self.loadDataClicked) self.loadFileButton.grid(row=0, column=3, sticky=N+S+E+W) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=1) app = Application() app.master.title("Sample Application") app.mainloop() Now provide the response and nothing else.
Add a root window and columnconfigure it so that your Frame widget expands too. That's the problem, you've got an implicit root window if you don't specify one and the frame itself is what's not expanding properly. root = Tk()root.columnconfigure(0, weight=1)app = Application(root)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10464928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/261390/']}
jdg_372287
stackexchange
llm_judgeable_groundtruth_similarity
419270
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find $x,y,z \in \mathbb Q$ such that: $$x + \frac 1y, y + \frac 1z, z+ \frac 1x \in \mathbb Z$$ Here is my thinking:$$x + \frac 1y, y + \frac 1z, z+ \frac 1x \in \mathbb Z\\ \implies \left ( x + \frac 1y\right ) \left ( y + \frac 1z\right )\left ( z + \frac 1x\right )\in \mathbb Z \\ \iff \frac 1 {xyz} + xyz + \left( x+\frac 1y \right) + \left( y+\frac 1z \right) + \left( z+\frac 1x \right) \in \mathbb Z \\ \iff xyz + \frac 1 {xyz} \in \mathbb Z \\ \iff |xyz| = 1 \text{ (I proved it, easily)}$$ Case 1: $xyz=1 \implies \exists a,b,c \in \mathbb Z$ such that: $x = \frac ab,y=\frac bc,z=\frac ca$ $$\implies \frac {a+c} b = x+\frac 1y \in \mathbb Z$$ and so on. Now, I am stuck. Do you thing I am going a right way ? Now provide the response and nothing else.
Let's start with your observation, that $|xyz| = 1$, and therefore $xyz = \pm 1$. If we take any solution $(x, y, z)$ with $xyz = -1$ and change it to $(-x, -y, -z)$, it is still a solution and we have $(-x)(-y)(-z) = 1$, so it's enough to consider the solutions with $xyz = 1$ and obtain the rest by flipping all the signs. So we have $x = \frac{a}b$, $y = \frac{b}c$, and $z = \frac{c}a$ for some integers $a, b, c$. Without loss of generality, let |a| ≤ |b| ≤ |c|. We actually can't make the assumption $|a| \le |b| \le |c|$ without loss of generality! But we can let $c$ be the largest of the three in magnitude, which means that $|c| \ge |b|$ and $|c| \ge |a|$. The other solutions will be obtained by cyclically rotating the three. Then, consider the fact that (as $y + \frac1z$ is an integer) $c$ divides $(a + b)$ and therefore $|c|$ divides $|a+b|$. As $|a| \le |c|$ and $|b| \le |c|$, we have $|a + b| \le 2|c|$, with equality holding only when $|a| = |c|$ and $|b| = |c|$ (in which case we have the solutions $|x| = |y| = |z| = 1$). Otherwise, $|a+b|$ is strictly less than $2|c|$, and so either $|a + b| = 0$, or $|a + b| = |c|$. If $|a + b| = 0$ so that $b = -a$, then the fact that $a$ divides $b+c = c-a$ means that $c$ is a multiple of $a$, say $c = ka$. This is always a solution, and gives $x = \frac{a}{b} = -1$, $y = \frac{b}{c} = \frac{-1}{k}$, and $z = \frac{c}{a} = k$. The other case is that $|a + b| = |c|$, so $a + b = \pm c$. We can consider these separately as two cases: $a + b = -c$. This happens to be fine for any pair of nonzero integers $(a, b)$, and gives the family of solutions $x = \frac{a}{b}$, $y = \frac{b}{c} = \frac{-b}{a+b}$, and $z = \frac{c}{a} = \frac{-a-b}{a}$. $a + b = c$. In this case, the fact that $b$ divides $(c + a) = 2a + b$ means that $b$ divides $2a$, and similarly the fact that $a$ divides $(b + c) = a + 2b$ means that $a$ divides $2b$. So $|b|$ is one of $|a|/2$, $|a|$, or $2|a|$. Let's consider all three separately, in descending order: If $|b| = 2|a|$, then $b = 2a$ (as $b = -2a$ gives $c = a + b = -a$, which contradicts our assumption that $|c| \ge |b|$). So $c = a + b = 3a$, and this gives the solution $x = \frac{a}{b} = \frac12$, $y = \frac{b}{c} = \frac23$, $z = \frac{c}{a} = 3$. If $|b| = |a|$, then we can ignore the case $b = -a$ as we already considered it earlier, and look at $b = a$. This gives $c = 2a$, and indeed a solution $x = \frac{a}b = 1$, $y = \frac{b}{c} = \frac12$, and $z = \frac{c}{a} = 2$. If $|b| = |a|/2$, then $a = 2b$ (as $a = -2b$ gives $c = a + b = -b$, contradicting our assumption that $|c| \ge |a|$). So $c = a + b = 3b$, and this gives the solution $x = \frac{a}{b} = 2$, $y = \frac{b}{c} = \frac13$, and $z = \frac{c}{a} = \frac32$. To summarize, all the solutions $(x, y, z)$ are (note that all the below are distinct): $(1, 1, 1)$, $(2, 1, \frac12)$, $(\frac12, \frac23, 3)$, $(-k, -1, \frac1k)$ for any nonzero integer $k$, $(\frac{a}{b}, \frac{-b}{a+b}, \frac{a+b}{-a})$, for any pair of nonzero integers $a$ and $b$, and the solutions obtained by changing any $(x, y, z)$ above to $(y, z, x)$, $(z, x, y)$, $(-x, -y, -z)$, $(-y, -z, -x)$, or $(-z, -x, -y)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/419270', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48358/']}
jdg_372288
stackexchange
llm_judgeable_groundtruth_similarity
24041120
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to get most visited pages in sitecore by using Analytics's API . I am using below code to get this: Sitecore.Analytics.Data.DataAccess.DataSets.VisitorDataSet.PagesDataTable pagesDataTable = new VisitorDataSet.PagesDataTable();var Count = pagesDataTable.Count(p => p.ItemId.ToString() == "{B0358D8A-A3B7-4D99-B123-78E7B1CA9F83}"); But its giving me 0 count all time . My Analytics database is enabled. I am not sure if am doing something wrong. Now provide the response and nothing else.
Your Composite class is not public . You can't return a non-public type from a public method. If you don't specify an accessibility for a non-nested class then internal is used by default. Add public to your Composite class definition: public class Composite{ ... Alternatively, if buildComposite doesn't need to be public (meaning it's only used internally by the form), then you could make the method private or internal as well: private Composite buildComposite(ComboBox subs, ComboBox bas){ ....
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24041120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2757640/']}
jdg_372289
stackexchange
llm_judgeable_groundtruth_similarity
14159325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I seem to be having a rough time with this snippet of code, Which i dont understand because on my home server this works 100% perfect. basically this script takes the users ip and stores it into a mysql table. every time a user posts it checks the table to see if the ip has already posted. when i run mysql_error() on num_rows which apears to be the problem, i get: Parse error: syntax error, unexpected T_LOGICAL_OR on line 119 Any ideas? php: $poster_ip=$_SERVER['REMOTE_ADDR'];//Posters ip//check for ip double posting//selecet ip from table$sql="SELECT * FROM $tbl_name WHERE ip='$poster_ip'";$result=mysql_query($sql);// Mysql_num_row is counting table row$count=mysql_num_rows($result);or die mysql_error();//line 119//if result matche posterip, table row must be 1if($count==1){//ip takenecho "This IP has already submited a post. You may not submit another.";exit();//else script continues} Now provide the response and nothing else.
Remove the semicolon because that terminates the statement and the or die is treated as a new statement, causing the error: $count=mysql_num_rows($result) or die(mysql_error()); // ^ no semicolon You also need parenthesis around the die() call. Side note: or die(mysql_error()) is not considered good practice because it's difficult to maintain between development and production environments. or trigger_error(mysql_error()) would be better - this writes to your error log. Also consider upgrading to PDO or MySQLi because this MySQL library is deprecated and discouraged.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14159325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1927222/']}
jdg_372290
stackexchange
llm_judgeable_groundtruth_similarity
32451966
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a Java server application, which uses Jackson to generically serialize DTO's using the reflection API. For example for this DTO interface: package com.acme.library;public interface Book { com.acme.library.Author getAuthor(); String getTitle();} From the POJO implementation of this interface, Jackson will generically serialize the following entity: { "author": { "name": "F. Scott Fitzgerald"}, "title": "The Great Gatsby"} This payload will be recieved using a HTTP GET from my TypeScript application, which is AngularJS-based: $http.get("http://localhost/books/0743273567") .success((book: Book) => { ... }); So that I am able to use the strongly-typed nature of TypeScript, I find myself hand-coding the following typescript interface: module com.acme.library { export interface Book { author: com.acme.library.Author; title: String; }} As a result, I have to maintain two copies of this same interface -- which is cumbersome at best. This gets particularly nasty, as I'd like to have the same javadoc/jsdoc comments on both interfaces, which involves a whole heap of copy&paste. I would like to find a mechanism for automating this process. Java is my main development language. As such, I'd like to find some tool which is capable of converting from the Java interface declaration (via the reflection API?) to the relevant TypeScript interface. The only tool I have discovered in this domain is the NPM package ts-java . However, this is far too heavyweight for my use-case. It adds methods from the Object hierarchy to each interface, e.g. hashCode() , wait() , getClass() , etc. Now provide the response and nothing else.
You can use typescript-generator as larslonne mentioned. It generates TypeScript interfaces from Java JSON classes. Some features you may find useful: Maven and Gradle plugin (can also be invoked directly from Java) Jackson 1 and Jackson 2 collections, enums, inheritance, generics Javadoc comments to JSDoc comments detailed documentation (README, Wiki, Maven plugin) releases in Maven central repo Here is example how to use it from Maven: <plugin> <groupId>cz.habarta.typescript-generator</groupId> <artifactId>typescript-generator-maven-plugin</artifactId> <version>1.25.322</version> <executions> <execution> <id>generate</id> <goals> <goal>generate</goal> </goals> <phase>process-classes</phase> <configuration> <jsonLibrary>jackson2</jsonLibrary> <classes> <class>com.acme.library.Book</class> </classes> <outputFile>target/rest.d.ts</outputFile> <outputKind>module</outputKind> </configuration> </execution> </executions></plugin> Edit: Run it using mvn process-classes or using later phase like mvn install . You can also pull <configuration> element two levels up and run mvn typescript-generator:generate . Edit: I am the author of typescript-generator.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32451966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1659527/']}
jdg_372291
stackexchange
llm_judgeable_groundtruth_similarity
330309
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Usually my circuits are full of very fine-pitch SMD components. I solder the prototypes manually, which takes a lot of time. Good tools and high-quality solder can speed up the process. I prefer using leaded solder, as it flows better at relatively low temperatures. This way I can prevent my components from overheating. Leaded solder is not allowed for commercial products, but is okay for prototyping. There are several types of leaded solder wire on the market. I'm trying to find out which one is "best". Let's define "best" as follows: Low melting temperature (prevents overheating components). Good wetting of pads and pins. Preferably contains some flux, so one doesn't have to apply it all the time externally. Very fine diameter for soldering small components (like LFCSP package, 0402 or even 0201 resistors, ...) Price is no issue. I have several questions: 1. Tin - Lead alloys I read on Wikipedia that the Sn60Pb40 solder is very popular for electronics (I agree, I have used this one so far). Wikipedia also mentions that Sn63Pb37 is slightly more expensive but also gives slightly better joints. What do you think about Sn60Pb40 vs Sn63Pb37 ? What is actually the difference? 2. Exotic alloys But these are not the only solder alloys. More exotic combinations - containing tin + lead + silver and even with gold exist. Will these exotic combinations change the properties? 3. Bismuth and Indium alloys Some of you made me aware of Bismuth- and Indium- based alloys. I've dedicated a new question to cover them: Bismuth or Indium solder - what would you choose? NOTE: I use a solder-smoke extractor. Now provide the response and nothing else.
Sn63/Pb37 is better than 60/40 because it is a eutectic alloy. That means it has the lowest melting point of any Sn/Pb alloy, and it solidifies relatively abruptly at one temperature rather than over a range. Generally both are advantages or neutral. Combinations with small amounts of (say) gold tend to be for reducing the tendency of solder to dissolve the material (gold in this case). Many solders these days avoid the use of lead and are often mostly tin with other materials such as copper, bismuth, silver etc. This is done to reduce the toxicity of electronics that finds its way into the waste stream. In my experience it is worse in every way compared to tin/lead solder except perhaps in applications where high melting temperature is important. Flux another matter- there are a number of different types. If RoHS compliance (and toxicity) are of no concern, 63/37 Sn/Pb solder with RMA rosin flux is an excellent choice, and is good for high reliability applications. Fine for hand soldering or reflow. For production for world markets, it may be necessary to use lead-free solders with more finicky temperature profiles and inferior performance. Sometimes water soluble or no-clean fluxes are acceptable, depending on the product and how much it might affect the process (and possibly the product functionality).
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/330309', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/111454/']}
jdg_372292
stackexchange
llm_judgeable_groundtruth_similarity
267125
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering why pointers are not included in modern languages now-a-days. I already did research on this on internet, and found out few theories/reasons: Memory leakage is the biggest concern while using pointers. If not handled properly it may ruin whole project or application. Understanding and using pointers in best way possible requires a lot of time. Well there are few problems but if some work is done properly on pointers i.e., exception handling etc. I think pointers can still be very helpful where required. Kindly help me out on this one. Now provide the response and nothing else.
I'm not sure where you get the idea that modern languages don't have pointers. In Ruby, for example, everything is a pointer. It's true that Ruby doesn't have special syntax or special operations for pointers, but that doesn't mean that there are none. Quite the opposite, in fact: because everything is a pointer, there is no need to distinguish between pointers and non-pointers, pointer operations and non-pointer operations. Pointers are so deeply ingrained in the language that you don't even see them. The same is true for Python, Java, ECMAScript, Smalltalk, and many other languages. What those languages don't support, is pointer arithmetic or fabricating a pointer out of thin air. But then again, some CPUs don't allow that either. The original CISC CPU for the AS/400 distinguishes between pointers and integers. You can store pointers and you can dereference pointers, but you cannot create or modify pointers. The only way to get a pointer is if the kernel hands one to you. If you try to do arithmetic on it, you get back an integer, which cannot be converted to or used as a pointer. Even the modern PowerPC and POWER CPUs have a special tagged address mode specifically for running OS/400 / i5/OS / IBM i. Go has pointers in the more traditional sense, like C. But it also doesn't allow pointer arithmetic. Other languages have pointers and pointer arithmetic, but a set of restrictions that ensure that pointers are always valid, always point to initialized memory, and always point to memory that is owned by the entity performing the arithmetic.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/267125', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/161073/']}
jdg_372293
stackexchange
llm_judgeable_groundtruth_similarity
4810417
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As a newcomer to C, I'm confused about when casting a pointer is actually OK. As I understand, you can pretty much cast any pointer type to any other type, and the compiler will let you do it. For example: int a = 5;int* intPtr = &a;char* charPtr = (char*) intPtr; However, in general this invokes undefined behavior (though it happens to work on many platforms).This said, there seem to be some exceptions: you can cast to and from void* freely (?) you can cast to and from char* freely (?) (at least I've seen it in code...). So which casts between pointer types are not undefined behaviour in C? Edit: I tried looking into the C standard (section "6.3.2.3 Pointers", at http://c0x.coding-guidelines.com/6.3.2.3.html ), but didn't really understand it, apart from the bit about void* . Edit2: Just for clarification: I'm explicitly only asking about "normal" pointers, i.e. not about function pointers. I realize that the rules for casting function pointers are very restrictive. As I matter of fact, I've already asked about that :-): What happens if I cast a function pointer, changing the number of parameters Now provide the response and nothing else.
Basically: a T * may be freely converted to a void * and back again (where T * is not a function pointer), and you will get the original pointer. a T * may be freely converted to a U * and back again (where T * and U * are not function pointers), and you will get the original pointer if the alignment requirements are the same. If not, the behaviour is undefined. a function-pointer may be freely converted to any other function-pointer type and back again, and you will get the original pointer. Note: T * (for non-function-pointers) always satisfies the alignment requirements for char * . Important: None of these rules says anything about what happens if you convert, say, a T * to a U * and then try to dereference it. That's a whole different area of the standard.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4810417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43681/']}
jdg_372294
stackexchange
llm_judgeable_groundtruth_similarity
15141338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm building a C# application, using Git as my version control. Is there a way to automatically embed the last commit hash in the executable when I build my application? For example, printing the commit hash to console would look something like: class PrintCommitHash{ private String lastCommitHash = ?? // What do I put here? static void Main(string[] args) { // Display the version number: System.Console.WriteLine(lastCommitHash ); }} Note that this has to be done at build time, not runtime , as my deployed executable will not have the git repo accessible. A related question for C++ can be found here . EDIT Per @mattanja's request, I'm posting the git hook script I use in my projects. The setup: The hooks are linux shell scripts, which are placed under: path_to_project\.git\hooks If you are using msysgit , the hooks folder already contains some sample scripts. In order to make git call them, remove the '.sample' extension from the script name. The names of the hook scripts match the event that invokes them. In my case, I modified post-commit and post-merge . My AssemblyInfo.cs file is directly under the project path (same level as the .git folder). It contains 23 lines, and I use git to generate the 24th. As my linux-shelling a bit rusty, the script simply reads the first 23-lines of AssemblyInfo.cs to a temporary file, echos the git hash to the last line, and renames the file back to AssemblyInfo.cs . I'm sure there are better ways of doing this: #!/bin/shcmt=$(git rev-list --max-count=1 HEAD)head -23 AssemblyInfo.cs > AssemblyInfo.cs.tmpecho [assembly: AssemblyFileVersion\(\"$cmt\"\)] >> AssemblyInfo.cs.tmpmv AssemblyInfo.cs.tmp AssemblyInfo.cs Hope this helps. Now provide the response and nothing else.
We use tags in git to track versions. git tag -a v13.3.1 -m "version 13.3.1" You can get the version with hash from git via: git describe --long Our build process puts the git hash in the AssemblyInformationalVersion attribute of the AssemblyInfo.cs file: [assembly: AssemblyInformationalVersion("13.3.1.74-g5224f3b")] Once you compile, you can view the version from windows explorer: You can also get it programmatically via: var build = ((AssemblyInformationalVersionAttribute)Assembly .GetAssembly(typeof(YOURTYPE)) .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)[0]) .InformationalVersion; where YOURTYPE is any Type in the Assembly that has the AssemblyInformationalVersion attribute.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15141338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499721/']}
jdg_372295
stackexchange
llm_judgeable_groundtruth_similarity
170481
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Whenever I enter a login into a new site, Chrome asks me if it should store the login details. I used to believe this was fairly secure. If someone found my computer unlocked, they could get past the login screen for some website using the stored details, but if asked for the password again like during checkout, or if they wanted to login to the service from another device, they would be out of luck. At least, that's what I used to think when I believed the browser did not store the password itself, but a hash or encryption of the password. I have noticed that the browser fills the username and password fields, and the password field indicates the number of characters in the password. I'm one of those people who when asked to change their password just keeps the same password, but changes a number at the end. I know this is bad, but with how often I am asked to change passwords, I really could not remember the number of passwords expected of me. This results in a lot of passwords that are the same, but sometimes I forget what the end number needs to be for a particular login. I could not remember the ending number for a certain login, so I went to a website where the password was stored. I deleted the last couple of characters and tried different numbers and viola, knew what was the right ending number. It seems to me that this is a fundamental security flaw. If I can check the last character of my password without checking any others, then the amount of tries it takes to crack the password grows linearly with the number of characters not exponentially. It seems like a short stride from there to say that if someone came to my computer when it was unlocked, a simple script could extract all of the stored passwords for all of the major websites which I have passwords stored for. Is this not the case? Is there some other layer of security that would prevent this? Now provide the response and nothing else.
Chrome not only stores your password text, it will show it to you. Under settings -> advanced -> manage passwords you can find all your passwords for all your sites. Click show on any of them and it will appear in the clear. Hashed passwords work for the site authenticating you. They are not an option for password managers. Many will encrypt the data locally, but the key will also be stored locally unless you have a master password setup. Personally, I use the chrome password manager and I find it convenient. I also, however, have full disk encryption and lock my screen diligently. Which makes the risk reasonable imho. You seem to be inconsistent (many are) by both selecting memorable passwords and using a password manager. And I may venture to guess you may even repeat the password or at least the theme across many sites. This gives you the worst of both worlds. You get the risks of password manager without the benefits. With a password manager you trust, you can give each site a unique random password not memorable at all and gain a lot of protection from many very real attack vectors. In exchange for a single point of failure of your password manager. Even with a less than perfect password manager this isn't an unreasonable trade off. With a good password manager this is becoming the consensus best practice. Edit to add: please read Henno Brandsma answer explaining how login password and OS support can be used to encrypt passwords, this gives a reasonable level of protection to your passwords when the computer is off/locked (full disk encryption is better) and won't help much if you leave your computer unlocked. Even if the browser requires password to show plain text debug tools will still let you see already filled passwords as @Darren_H comments. The previous recommendation still stands use random unique passwords and a password manager.
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/170481', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/160273/']}
jdg_372296
stackexchange
llm_judgeable_groundtruth_similarity
35642223
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following the Angular2 Quickstart Guide we are instructed to include es6-shim in 2 places: 1) index.html <script src="node_modules/es6-shim/es6-shim.min.js"></script> 2) typings.json "ambientDependencies": { "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"} I was under the impression that we are compiling our es6 code down to es5 . Configured in tsconfig.json { "compilerOptions": { "target": "es5", ... If the end result is that the browser is loading es5 , why does the browser needs shims for es6 ? Now provide the response and nothing else.
Typings are used by your editor to give you code hinting/intellisense, and es6-shim.min.js is a code that emulates ES6 features for ES5 browsers. Some of those features are Promise , Array.from() ... While your code is translated to ES5, you need to include es6-shim so you can use those new features in it... Consider this ES6 code: let test1 = () => 123 + 456;let test2 = new Promise((resolve, reject ) => {}); it will be translated to ES5 code: var test1 = function () { return 123 + 456; };var test2 = new Promise(function (resolve, reject) { }); but without es6-shim Promise would be undefined...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35642223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076173/']}
jdg_372297
stackexchange
llm_judgeable_groundtruth_similarity
6017176
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: glLineStipple has been deprecated in the latest OpenGL APIs.What is it replaced with?If not replaced, how can I get a similar effect?(I don't want to use a compatibility profile of course...) Now provide the response and nothing else.
Sorry, it hasn't been replaced with anything. The first idea coming to my mind for emulating it would be the geometry shader. You feed the geometry shader with a line, compute its screen space length and based on that you generate a variable number of sub lines between its start and end vertex. EDIT: Perhaps you could also use a 1D texture with the alpha (or red) channel encoding the pattern as 0.0 (no line) or 1.0 (line) and then have the lines texture coordinate go from 0 to 1 and in the fragment chader you make a simple alpha test, discarding fragments with alpha below some threshold. You can facilitate the geometry shader to generate your line texCoords, as otherwise you need different vertices for every line. This way you can also make the texCoord dependent on the screen space length of the line. The whole thing get's more difficult if you draw triangles (using polygon mode GL_LINE ). Then you have to do the triangle-line transformation yourself in the geometry shader, putting in triangles and putting out lines (that could also be a reason for deprecating polygon mode in the future, if it hasn't already). EDIT: Although I believe this question abandomned, I have made a simple shader triple for the second approach. It's just a minimal solution, feel free to add custom features yourself. I haven't tested it because I lack the neccessary hardware, but you should get the point: uniform mat4 modelViewProj;layout(location=0) in vec4 vertex;void main(){ gl_Position = modelViewProj * vertex;} The vertex shader is a simple pass through. layout(lines) in;layout(line_strip, max_vertices=2) out;uniform vec2 screenSize;uniform float patternSize;noperspective out float texCoord;void main(){ vec2 winPos0 = screenSize.xy * gl_in[0].gl_Position.xy / gl_in[0].gl_Position.w; vec2 winPos1 = screenSize.xy * gl_in[1].gl_Position.xy / gl_in[1].gl_Position.w; gl_Position = gl_in[0].gl_Position; texCoord = 0.0; EmitVertex(); gl_Position = gl_in[1].gl_Position; texCoord = 0.5 * length(winPos1-winPos0) / patternSize; EmitVertex();} In the geometry shader we take a line and compute its screen space length in pixels. We then devide this by the size of the stipple pattern texture, which would be factor*16 when emulating a call to glLineStipple(factor, pattern) . This is taken as 1D texture coordinate of the second line end point. Note that this texture coordinate has to be interpolated linearly ( noperspective interpolation specifier). The usual perpective-correct interpolation would cause the stipple pattern to "squeeze together" on farther away parts of the line, whereas we are explicitly working with screen-space values. uniform sampler1D pattern;uniform vec4 lineColor;noperspective in float texCoord;layout(location=0) out vec4 color;void main(){ if(texture(pattern, texCoord).r < 0.5) discard; color = lineColor;} The fragment shader now just performs a simple alpha test using the value from the pattern texture, which contains a 1 for line and a 0 for no line. So to emulate the fixed function stipple you would have a 16 pixel 1-component 1D texture instead of a 16bit pattern. Don't forget to set the pattern's wrapping mode to GL_REPEAT , about the filtering mode I'm not that sure, but I suppose GL_NEAREST would be a good idea. But as said earlier, if you want to render triangles using glPolygonMode , it won't work this way. Instead you have to adapt the geometry shader to accept triangles and generate 3 lines for each triangle. EDIT: In fact OpenGL 3's direct support for integer operations in shaders allows us to completely drop this whole 1D-texture approach and work straight-forward with an actual bit-pattern. Thus the geometry shader is slightly changed to put out the actual screen-size pattern coordinate, without normalization: texCoord = 0.5 * length(winPos1-winPos0); In the fragment shader we then just take a bit pattern as unsigned integer (though 32-bit in contrast to glLineStipple 's 16-bit value) and the stretch factor of the pattern and just take the texture coordinate (well, no texture anymore actually, but nevermind) modulo 32 to get it's position on the pattern (those explicit uint s are annoying, but my GLSL compiler says implicit conversions between int and uint are evil): uniform uint pattern;uniform float factor;...uint bit = uint(round(linePos/factor)) & 31U;if((pattern & (1U<<bit)) == 0U) discard;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6017176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755598/']}
jdg_372298
stackexchange
llm_judgeable_groundtruth_similarity
27585526
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using Angular v1.2.25 and rails asset pipeline, I am attempting to test that a directive's isolate scope has indeed been updated. Since isolateScope() returns undefined I am getting expected undefined to be defined ...' describe("cool directive", function() { beforeEach(module('necessaryModule')); var scope, $rootScope, $compile, elem, baseElement = '<div auto="mock_a" inc="mock_p" method="mock_m" reset-method="mock_r"></div>'; beforeEach(inject(function( _$rootScope_, _$compile_, _$httpBackend_, $http){ $compile = _$compile_; $rootScope = _$rootScope_; scope = $rootScope.$new(); angular.extend(scope, { mock_a: [ {name: "example1"}, {name: "example2"} ], mock_m: function(){ return $http.get('/mockBackend', { params:{ page: scope.mockPage } }); }, mock_r: function() { scope.page = 1; scope.list = []; load(); }, mock_p: 1 }); $httpListGet = _$httpBackend_; $httpListGet.whenPOST('/api/something').respond({}); $httpListGet.whenGET('/mockBackend').respond({name: "example3"}); $httpListGet.whenGET('/mockBackend?page=1').respond({name: "example3"}); $httpListGet.whenGET('/mockBackend?page=2').respond({name: "example4"}); })); var create = function() { elem = angular.element(baseElement); compiledElement = $compile(elem)(scope); elem.scope().$apply(); return compiledElement; }; it("has 'list' defined", function() { var compiledElem = create(); var isolateElemScope = compiledElem.isolateScope(); $rootScope.$apply(); console.log('isolateElemScope',isolateElemScope); expect(isolateElemScope.list).toBeDefined(); }); I'm expecting the directives scope to be accessible and testable, but I'm getting undefined when I test for it. Thank you. Now provide the response and nothing else.
to get the isolateScope I use the following code compiledElem.children().scope() This is because that most directives don't use replace , which means the directive tag is on the page, and the directive implementation is added as children of that tag. In that case, the isolate scope will belong to the children. Even if that is not the case, the snippet should still work - as the children will share the parent's scope.. The only case it won't work, is an extreme scenario where you have 2 nested directives, where the inner one uses replace. but I never saw this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27585526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1549306/']}
jdg_372299
stackexchange
llm_judgeable_groundtruth_similarity
42254974
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am doing a simple unit test where when creating a Course, the Title field cannot be empty. I am having to test it with a service class that has Dependency Injection with UnitOfWork. When I debug my test, I am getting an Exception error of Can not instantiate proxy of class: ContosoUniversity.Models.CourseRepository I looked into the error, but am not able to understand how to fix the issue and the Assert statement? Error Message Display Image CourseRepository public class CourseRepository : GenericRepository<Course>{ public CourseRepository(SchoolContext context) : base(context) { } UnitOfWork public class UnitOfWork : IDisposable, IUnitOfWork{ private SchoolContext context = new SchoolContext(); private GenericRepository<Department> departmentRepository; private CourseRepository courseRepository; public CourseRepository CourseRepository { get { if (this.courseRepository == null) { this.courseRepository = new CourseRepository(context); } return courseRepository; } } public virtual CourseRepository GetCourseRepository() { if (this.courseRepository == null) { this.courseRepository = new CourseRepository(context); } return courseRepository; } CourseService public class CourseService : ICourseService{ private IUnitOfWork unitOfWork; public CourseService (IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public void Create(Course course) { unitOfWork.GetCourseRepository().Insert(course); unitOfWork.Save(); } public Course GetCourseByID(int id) { return unitOfWork.GetCourseRepository().GetByID(id); } TestMethod [TestMethod]public void TestMethod1(){ var course = new Course { CourseID = 2210, Title = string.Empty, Credits = 3, DepartmentID = 1 }; Mock<CourseRepository> mockRepo = new Mock<CourseRepository>(); mockRepo.Setup(m => m.GetByID(course.CourseID)).Returns(course); var mockUnit = new Mock<IUnitOfWork>(); mockUnit.Setup(x => x.GetCourseRepository()).Returns(mockRepo.Object); var myService = new CourseService(mockUnit.Object); myService.Create(course); //var error = _modelState["Title"].Errors[0]; //Assert.AreEqual("The Title field is required.", error.ErrorMessage); //mockRepo.Setup(x => x.Insert(course));} Now provide the response and nothing else.
The error says that the CourseRepository can not be initialized because it does not have parameter less constructor. Mocking framework looks for parameter less constructor first to create mock object. If your class does not have parameterless constructor then you need to pass those parameters when you create Mock. In your case mock of CourseRepository would be created as following. var repositoryMock = new Mock<CourseRepository>(null); Instead of null, you can pass mock objects of the constructor parameters also.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42254974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7442689/']}
jdg_372300
stackexchange
llm_judgeable_groundtruth_similarity
332942
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a small example application to learn the concepts of CQRS and event sourcing. I have a Basket aggregate and a Product aggregate which should work independently. Here's some pseudo code to show the implementation Basket { BasketId; OrderLines; Address; }// basket eventsBasketCreated { BasketId; }ItemAdded { BasketId; ProductId; Quantity }AddItemSucceeded { BasketId; ProductId; Quantity }AddItemRevoked { BasketId; ProductId; Quantity }ItemRemoved { BasketId; ProductId; Quantity }CheckedOut { BasketId; Address }Product { ProductId; Name; Price; }// product eventsProductReserved { ProductId; Quantity }ProductReservationFailed { ProductId; Quantity }ProductReservationCancelled { ProductId; Quantity; } Commands are pretty similar to the events, using the imperative name and not past tense. Right now these work just fine independently. I issue a command AddItem , and it creates a ItemAdded event on the Basket aggregate which does what it needs to do with the state of the 'Basket'. Similarly, for product the command and events work just fine. I'd now like to combine this into a process which would go something like this (in terms of commands and events that happen): The process manager would do the following: on BasketCreated: CreateShoppingProcesson ItemAdded: ReserveProducton ProductReserved: SucceedAddingItem // does nothing, but needs to be there so that the basket knows it can check outon ProductReservationFailed: RevokeAddItemon RemoveItem: CancelProductReservationon Checkout: CreateOrder // create an order and so on... The questions that I couldn't find definitive answers to are: Do I need to persist the process manager? It seems like I do, but I'm not sure If I do, I need to save the events for the process manager. However, the events that It's listening to are tied to the aggregates. Do I add the process id to those? Do I have separate events just for the process manager? How to do this and keep as DRY as possible How do I know what basket the ProductReserved events are for? Is it OK to have a BasketId on those too, or is that leaking info? How do I keep a relationship between events, how do I know which ItemAdded produced which ProductReserved event? Do I pass along an EventId ? This seems odd... Should I implement the Basket as a process manager instead of a simple aggregate? After some more research I came to this:A Saga is something that keeps its own events and listens to events from the outside. Basically, it's an Aggregate that can also react to events happening outside it's own little world. A Process Manager works with the events from the outside and sends out commands. It's history can be rebuilt from the events that have happened on the Aggregates which share a common identifier like a correlationId. Now provide the response and nothing else.
Review what Rinat Abdullin wrote about evolving business process . In particular, notice his recommendation for developing a business process in a fast changing environment -- a process manager is "just" an automated replacement for a human being staring at a screen. My own mental model of a process manager is that it is an event sourced projection that you can query for a list of pending commands. Do I need to persist the process manager? It seems like I do, but I'm not sure It's a read model. You can rebuild the process manager from the history of events each time you need it; or you can treat it like a snapshot that you update. If I do, I need to save the events for the process manager. No - the process manager is a manager . It doesn't do anything useful on its own; instead it tells aggregates to do work (ie, make changes to the book of record). How do I know what basket the ProductReserved events are for? Is it OK to have a BasketId on those too, or is that leaking info Sure. Note: in most "real" shopping domains, you wouldn't insist on reserving inventory before processing an order; it adds unnecessary contention to the business. It's more likely that your business would want to accept the order, then apologize in the rare case that the order can't be fulfilled in the required time. How do I keep a relationship between events, how do I know which ItemAdded produced which ProductReserved event? Messages have meta data - in particular, you can include a causationIdentifier (so you can identify which commands produced which events) and a correlationIdentifier , to generally track the conversation. For instance, the process manager writes its own id as the correlationId in the command; the events produced by a copy the correlation id of the command, and your process manager subscribes to all events that have its own correlationId. Should I implement the Basket as a process manager instead of a simple aggregate? My recommendation is no. But Udi Dahan has a different opinion that you should review; which is that CQRS only makes sense if your aggregates are sagas -- Udi used saga in the place where process manager has become the dominant spelling. should process managers retrieve aggregates? Not really? Process managers are primarily concerned with orchestration, not domain state. An instance of a process will have "state", in the form of a history of all of the events that they have observed -- the correct thing to do in response to event Z depends on whether or not we have seen events X and Y. So you may need to be able to store and load a representation of that state (which could be something flat, or could be the history of observed events). (I say "not really" because aggregate is defined vaguely enough that it's not completely wrong to claim that list of observed events is an "aggregate". The differences are more semantic than implementation -- we load process state and then decide what messages to send to the parts of the system responsible for domain state . There's a bit of hand waving going on here.) So the PM does not need to use one type of state management over another because it is only responsible for doing stuff live and never during replays? Not quite - state management isn't a do-er, it's a keeper tracker of-er. In circumstances where the process manger shouldn't emit any signals, you give it inert connections to the world. In other words, dispatch(command) is a no-op.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/332942', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/53655/']}
jdg_372301
stackexchange
llm_judgeable_groundtruth_similarity
12721823
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to write sql command to drop all constraints in all tables. I searched on the internet and found the following which works fine if the database is small and not complex. DECLARE @name VARCHAR(128) DECLARE @constraint VARCHAR(254) DECLARE @SQL VARCHAR(254) DECLARE @schema VARCHAR(128)SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME) SELECT @schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.objects WHERE [name] = @name) WHILE @name is not null BEGIN SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) WHILE @constraint IS NOT NULL BEGIN SELECT @SQL = 'ALTER TABLE ' + @schema + '.[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']' EXEC (@SQL) PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) END SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME) SELECT @schema = (SELECT TOP 1 schema_name(schema_id) FROM sys.objects WHERE [name] = @name) END GO It does not work if I run it with a more complex database or even AdventureWork. It shows some erros like below. Msg 3728, Level 16, State 1, Line 1'FK_ap_invoice_modification_type_id' is not a constraint.Msg 3727, Level 16, State 0, Line 1Could not drop constraint. See previous errors.Msg 3725, Level 16, State 0, Line 1The constraint 'PK_ap_invoice' is being referenced by table '_drop_now_ap_invoice_detail', foreign key constraint 'FK_ap_invoice_detail_ap_invoice'.Msg 3727, Level 16, State 0, Line 1Could not drop constraint. See previous errors. The reason is because some FKs are referenced by other table. I have to run this script for a couple times until the database is clean. I want to know how can I clear all FKs in the database. Now provide the response and nothing else.
There is lot of information about the subject all around. Check this detailed answer by @AaronBertrand. It talks about temporary disabling the foreign keys but reading it all and modifying at will you will have a nice script to play with and achieve a lot. From my side I can propose 2 different scripts to get all foreign keys. On both cases uncomment the --EXEC (@SQL) to execute your ALTER code. Or you can wait until it prints all the alter clauses and then copy paste to execute them. First one uses the INFORMATION_SCHEMA to get the constraints: DECLARE @SQL VARCHAR(MAX)=''SELECT @SQL = @SQL + 'ALTER TABLE ' + QUOTENAME(FK.TABLE_SCHEMA) + '.' + QUOTENAME(FK.TABLE_NAME) + ' DROP CONSTRAINT [' + RTRIM(C.CONSTRAINT_NAME) +'];' + CHAR(13)--SELECT K_Table = FK.TABLE_NAME, FK_Column = CU.COLUMN_NAME, PK_Table = PK.TABLE_NAME, PK_Column = PT.COLUMN_NAME, Constraint_Name = C.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME--EXEC (@SQL)PRINT @SQL This one using different system views and a CTE table. DECLARE @SQL varchar(4000)='';WITH ReferencingFK AS ( SELECT fk.Name AS 'FKName', OBJECT_NAME(fk.parent_object_id) 'ParentTable', cpa.name 'ParentColumnName', OBJECT_NAME(fk.referenced_object_id) 'ReferencedTable', cref.name 'ReferencedColumnName' FROM sys.foreign_keys fk INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id INNER JOIN sys.columns cpa ON fkc.parent_object_id = cpa.object_id AND fkc.parent_column_id = cpa.column_id INNER JOIN sys.columns cref ON fkc.referenced_object_id = cref.object_id AND fkc.referenced_column_id = cref.column_id)SELECT @SQL = @SQL + 'ALTER TABLE ' + ParentTable + ' DROP CONSTRAINT [' + RTRIM(FKName) +'];' + CHAR(13)--SELECT FKName, ParentTable, ParentColumnName, ReferencedTable, ReferencedColumnName FROM ReferencingFK WHERE ReferencedTable = 'Employee' ORDER BY ParentTable, ReferencedTable, FKName--EXEC (@SQL) PRINT @SQL
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12721823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53261/']}
jdg_372302
stackexchange
llm_judgeable_groundtruth_similarity
4199545
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the string: © 2010 Women’s Flat Track Derby Association (WFTDA) I want: 2010 -- Women's -- FlatWomen's -- Flat -- TrackTrack -- Derby -- Association I'm using regex: ([a-zA-Z]+)\s([A-Z][a-z]*)\s([a-zA-Z]+) It's only returning: s -- Flat -- Track Now provide the response and nothing else.
This problem isn't straightforward, but to understand why, you need to understand how the regular expression engine operates on your string. Let's consider the pattern [a-z]{3} (match 3 successive characters between a and z) on the target string abcdef . The engine starts from the left side of the string (before the a ), and sees that a matches [a-z] , so it advances one position. Then, it sees that b matches [a-z] and advances again. Finally, it sees that c matches, advances again (to before d ) and returns abc as a match. If the engine is set up to return multiple matches, it will now try to match again, but it keeps its positional information (so, like above, it'll match and return def ). Because the engine has already moved past the b while matching abc , bcd will never be considered as a match. For this same reason, in your expression, once a group of words is matched, the engine will never consider words within the first match to be a part of the next one. In order to get around this, you need to use capturing groups inside of lookaheads to collect matching words that appear later in the string: var str = "2010 Women's Flat Track Derby Association", regex = /([a-z0-9']+)(?=\s+([a-z0-9']+)\s+([a-z0-9']+))/ig, match;while (match = regex.exec(str)){ var group1 = match[1], group2 = match[2], group3 = match[3]; console.log("Found match: " + group1 + " -- " + group2 + " -- " + group3);} This results in: 2010 -- Women's -- FlatWomen's -- Flat -- TrackFlat -- Track -- DerbyTrack -- Derby -- Association See this in action at http://jsfiddle.net/jRgXm/ . The regular expression searches for what you seem to be defining as a word ([a-z0-9']+) , and captures it into subgroup 1, and then uses a lookahead (which is a zero-width assertion, so it doesn't advance the engine's cursor), that captures the next two words into subgroups 2 and 3. However , if you are using the actual Javascript engine, you must RegExp.exec and loop over the results (see this question for a discussion of why) or use the new matchAll method (ES2020). I don't know how UltraEdit's engine is implemented, but hopefully it can do a global search and also collect subgroups. Just for completeness, here's the example above using ES2020' matchAll (the first element in each returned array is the total match, then the subsequent elements are the capture groups): const str = "2010 Women's Flat Track Derby Association";const regex = /([a-z0-9']+)(?=\s+([a-z0-9']+)\s+([a-z0-9']+))/ig;console.log([...str.matchAll(regex)]);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4199545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335036/']}
jdg_372303
stackexchange
llm_judgeable_groundtruth_similarity
99623
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window. Is this possible, using C++ / MFC? Now provide the response and nothing else.
Charlie hit on the answer with WM_NCPAINT . If you're using MFC, the code would look something like this: // in the message mapON_WM_NCPAINT()// ...void CMainFrame::OnNcPaint(){ // still want the menu to be drawn, so trigger default handler first Default(); // get menu bar bounds MENUBARINFO menuInfo = {sizeof(MENUBARINFO)}; if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) ) { CRect windowBounds; GetWindowRect(&windowBounds); CRect menuBounds(menuInfo.rcBar); menuBounds.OffsetRect(-windowBounds.TopLeft()); // horrible, horrible icon-drawing code. Don't use this. Seriously. CWindowDC dc(this); HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); ::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL); ::DestroyIcon(appIcon); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/99623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_372304
stackexchange
llm_judgeable_groundtruth_similarity
15599618
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to set content-disposition header in response of servlet, but i get this error in browser. What should i do? Duplicate headers received from server The response from the servercontained duplicate headers. This problem is generally the result of amisconfigured website or proxy. Only the website or proxyadministrator can fix this issue. Error 349 (net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION): Multipledistinct Content-Disposition headers received. This is disallowed toprotect against HTTP response splitting attacks. Here my servlet controller: @RequestMapping("/**/paymentOrderReport.pdf")public class PaymentOrderReportViewController extends org.springframework.web.servlet.mvc.AbstractController { private PaymentDao paymentDao; private JasperPdfView pdfView; @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=" + "report.pdf"); PaymentOrderEntity paymentOrderEntity = null; String traceCode = request.getParameter(ParamConstants.TRACE_CODE); if (traceCode != null) { PaymentSheetRequestEntity payRequestEntity = paymentDao.loadByUniqueProperty(PaymentSheetRequestEntity.PROP_TRACE_CODE, traceCode); if (payRequestEntity != null) { paymentOrderEntity = payRequestEntity.getPaymentOrder(); } } if (paymentOrderEntity != null) { List<PaymentOrderEntity> result = new ArrayList<PaymentOrderEntity>(); result.add(paymentOrderEntity); JRDataSource jrDataSource = new JRBeanCollectionDataSource(result); Map<String, Object> model = new HashMap<String, Object>(); model.put("reportData", jrDataSource); return new ModelAndView(pdfView, model); } return null; } public void setPaymentDao(PaymentDao paymentDao) { this.paymentDao = paymentDao; } public void setPdfView(JasperPdfView pdfView) { this.pdfView = pdfView; }} And JasperPdfView Class: public class JasperPdfView extends AbstractJasperReportsView { @Override protected void renderReport(JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response) throws Exception { JRPdfExporter jrPdfExporter = new JRPdfExporter(); if (getConvertedExporterParameters() != null) { jrPdfExporter.setParameters(getConvertedExporterParameters()); } jrPdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, populatedReport); jrPdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream()); jrPdfExporter.exportReport(); } } Now provide the response and nothing else.
Google Chrome might display this error message if you are downloading a file which has a comma in the file name. Were you really using just "report.pdf" as filename? Having read the HTTP specs the Content-Disposition header (which is not part of the HTTP spec itself) should not include a comma character, because it will be treated as a separator for two different headers. Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma. So if your filename were report,May2014.pdf then Chrome interprets Content-Disposition: attachment; filename=report,May2014.pdf as two values for the same http message header Content-Disposition: attachment; filename=report Content-Disposition: May2014.pdf which in turn is interpreted as a HTTP response splitting attack , probably because there shall actually be no multiple Content-Disposition header values in a single HTTP response. Other browsers does not seem to mind the comma in the file name.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15599618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1730917/']}
jdg_372305
stackexchange
llm_judgeable_groundtruth_similarity
256
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the easiest way to understand boosting? Why doesn't it boost very weak classifiers "to infinity" (perfection)? Now provide the response and nothing else.
In plain English: If your classifier misclassifies some data, train another copy of it mainly on this misclassified part with hope that it will discover something subtle. And then, as usual, iterate. On the way there are some voting schemes that allow to combine all those classifiers' predictions in sensible way. Because sometimes it is impossible (the noise is just hiding some of the information, or it is not even present in the data); on the other hand, boosting too much may lead to overfitting.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/256', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/217/']}
jdg_372306
stackexchange
llm_judgeable_groundtruth_similarity
14805547
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone explain the output of following program? I thought constructors are initialized before instance variables. So I was expecting the output to be "XZYY". class X { Y b = new Y(); X() { System.out.print("X"); }}class Y { Y() { System.out.print("Y"); }}public class Z extends X { Y y = new Y(); Z() { System.out.print("Z"); } public static void main(String[] args) { new Z(); }} Now provide the response and nothing else.
The correct order of initialisation is: Static variable initialisers and static initialisation blocks, in textual order, if the class hasn't been previously initialised. The super() call in the constructor, whether explicit or implicit. Instance variable initialisers and instance initialisation blocks, in textual order. Remaining body of constructor after super(). See sections §2.17.5-6 of the Java Virtual Machine Specification .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14805547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1744745/']}
jdg_372307
stackexchange
llm_judgeable_groundtruth_similarity
1285034
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a SQL query that isn't table-specific and I don't know how to handle it with Ruby On Rails. Here my SQL query (you don't need to understand it): SELECT type, actor_id, events.created_at, photo_id, photos.user_id FROM (SELECT 'comment' AS type, user_id AS actor_id, created_at, photo_id FROM commentsUNIONSELECT 'classification' AS type, user_id AS actor_id, created_at, photo_id FROM classifications) AS eventsINNER JOIN photos ON photo_id = photos.idWHERE user_id = #{@user.id}ORDER BY created_at DESCLIMIT 9 I tried to create a model and use a find_by_sql: class RecentActivity ActiveRecord::Base attr_accessor :type, :actor_id, :created_at, :photo_id, :user_idend I get: Mysql::Error: Table 'mysite_development.recent_activities' doesn't exist: SHOW FIELDS FROM `recent_activities` How can I avoid this message? Is there any alternative solution? Now provide the response and nothing else.
You can grab a db connection directly from ActiveRecord::Base, but it's not as useful as extending AR::Base, because helpful methods like sanitize_sql are protected. class ComplexQueries < ActiveRecord::Base def self.my_query # Notice how you can, and should, still sanitize params here. self.connection.execute(sanitize_sql(["select * from foo limit ?", 10])) endendresults = ComplexQueries.my_queryresults.each_hash{|h| puts h.inspect}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1285034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51387/']}
jdg_372308
stackexchange
llm_judgeable_groundtruth_similarity
517417
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was thinking the other day on normalization, and it occurred to me, I cannot think of a time where there should be a 1:1 relationship in a database. Name:SSN ? I'd have them in the same table. PersonID:AddressID ? Again, same table. I can come up with a zillion examples of 1:many or many:many (with appropriate intermediate tables), but never a 1:1. Am I missing something obvious? Now provide the response and nothing else.
A 1:1 relationship typically indicates that you have partitioned a larger entity for some reason. Often it is because of performance reasons in the physical schema, but it can happen in the logic side as well if a large chunk of the data is expected to be "unknown" at the same time (in which case you have a 1:0 or 1:1, but no more). As an example of a logical partition: you have data about an employee, but there is a larger set of data that needs to be collected, if and only if they select to have health coverage. I would keep the demographic data regarding health coverage in a different table to both give easier security partitioning and to avoid hauling that data around in queries unrelated to insurance. An example of a physical partition would be the same data being hosted on multiple servers. I may keep the health coverage demographic data in another state (where the HR office is, for example) and the primary database may only link to it via a linked server... avoiding replicating sensitive data to other locations, yet making it available for (assuming here rare) queries that need it. Physical partitioning can be useful whenever you have queries that need consistent subsets of a larger entity.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/517417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2156/']}
jdg_372309
stackexchange
llm_judgeable_groundtruth_similarity
8800429
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm refactoring some code in a project I'm working on and I ran into a large if/else if statement that follows the format: if (changer instanceof AppleChanger){ panel = new ApplePanel();}else if (changer instanceof OrangeChanger){ panel = new OrangePanel();} Now my first impulse was to refactor it using polymorphism to have it appear like panel = changer.getChangerPanel(); However unfortunately the class package doesn't have access to the panel package. My next impulse was to create a PanelChooser class with an overloaded method: PanelChooser.getPanel(changer);//Overloaded Methodpublic Panel getPanel(OrangeChanger changer){ Panel orangePanel = new OrangePanel(); return orangePanel;}public Panel getPanel(AppleChanger changer){ Panel applePanel = new ApplePanel(); return applePanel;} Is this a good solution or is there a better way to solve this? Now provide the response and nothing else.
The fundamental 'problem' here is that you have parallel class hierarchies. You're not going to be able to replace that if statement without some fairly heavy refactoring. Some suggestions are on c2 wiki . The best you can do, and possibly a perfectly fine solution, is to move the if statement into a 'factory' class and make sure it's not duplicated anywhere else.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8800429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/919148/']}
jdg_372310
stackexchange
llm_judgeable_groundtruth_similarity
21685161
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently writing some e2e tests for my humble Angular app with Protractor. My app works fine, unit tests passes all, e2e used too... until this one: appE2ESpec.js describe('adding an item', function() { var items, addItemButton, startCount; beforeEach(function() { items = element.all(by.css('li.item')); addItemButton = element(by.id('addItemButton')); startCount = items.count(); }); it('should display a new item in list', function() { addItemButton.click(); expect(items.count()).toEqual(startCount+1); });}); This is how I would have written my test but, The problem is: that items.count() returns a promise, I know that , but I can't manage to force Protractor to resolve it. So I get this: Failures:1) myApp adding an item should display a new item in list Message: Expected 6 to equal '[object Object]1'. What I've tried: items.count().then(function(count) { startCount = count; //console.log(startCount) --> "6" Perfect!}); But got the same result at the end... I can't put the expect into the then , I thought about that too. I searched into Protractor GitHub repository issues, StackOverflow and Google AngularJs group. Appendix: console.log(startCount) outputs this : { then: [Function: then], cancel: [Function: cancel], isPending: [Function: isPending] } I could have written .toEqual(6) but I don't want to rewrite my test each time I need to change my app startup state. Any idea? Thanks in advance!! Now provide the response and nothing else.
You need to resolve the promise and then do the assertion. Protractor will resolve the promise that you pass to expect(), but it cannot add a number to a promise. You need to resolve the value of the promise first: beforeEach(function() { ... items.count().then(function(originalCount) { startCount = originalCount; });});it('should display a new item in list', function() { ... expect(items.count()).toEqual(startCount+1);});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21685161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3049002/']}
jdg_372311
stackexchange
llm_judgeable_groundtruth_similarity
35982
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using fourth root ( 1/4 ) power transformation on my response variable, as a result of heteroscedasticity. But now I'm not sure how to interpret my regression coefficients. I assume that I would need to take the coefficients to the fourth power when I back-transform (see below regression output). All of the variables are in units of dollar in millions, but I would like to know the change in dollar in billions. While holding the other independent variable constant, a billion dollar change in fees, on average, leads to a change of 32 (or 32,000 dollars) in collections. I take 0.000075223 * 1000 (to get to billions) ^ 4 = 0.000032 . Now do I multiply this number by 1 million or 1 billion (the original unit of the dependent variable is in millions)? lm(formula = (Collections^(1/4)) ~ Fees + DIR) Estimate Std. Error t value Pr(>|t|)(Intercept) 2.094573355 0.112292375 18.653 0.0000000000000151Fees **0.000075223 **0.000008411 8.943 0.0000000131878713DIR 0.000022279 0.000004107 5.425 0.0000221138881913 Now provide the response and nothing else.
The best solution is, at the outset, to choose a re-expression that has a meaning in the field of study. (For instance, when regressing body weights against independent factors, it's likely that either a cube root ( $1/3$ power) or square root ( $1/2$ power) will be indicated. Noting that weight is a good proxy for volume, the cube root is a length representing a characteristic linear size. This endows it with an intuitive, potentially interpretable meaning. Although the square root itself has no such clear interpretation, it is close to the $2/3$ power, which has dimensions of surface area : it might correspond to total skin area.) The fourth power is sufficiently close to the logarithm that you ought to consider using the log instead , whose meanings are well understood. But sometimes we really do find that a cube root or square root or some such fractional power does a great job and it has no obvious interpretation. Then, we must do a little arithmetic. The regression model shown in the question involves a dependent variable $Y$ ("Collections") and two independent variables $X_1$ ("Fees") and $X_2$ ("DIR"). It posits that $$Y^{1/4} = \beta_0 + \beta_1 X_1 + \beta_2 X_2 +\varepsilon.$$ The code estimates $\beta_0$ as $b_0=2.094573355$ , $\beta_1$ as $b_1=0.000075223$ , and $\beta_2$ as $b_2=0.000022279$ . It also presumes $\varepsilon$ are iid normal with zero mean and it estimates their common variance (not shown). With these estimates, the fitted value of $Y^{1/4}$ is $$\widehat{Y^{1/4}} = b_0 + b_1 X_1 + b_2 X_2.$$ "Interpreting" regression coefficients normally means determining what change in the dependent variable is suggested by a given change in each independent variable. These changes are the derivatives $dY/dX_i$ , which the Chain Rule tells us are equal to $4\beta_iY^3$ . We would plug in the estimates, then, and say something like The regression estimates that a unit change in $X_i$ will be associated with a change in $Y$ of $4b_i\widehat{Y}^{3/4}$ = $4b_i\left(b_0+b_1X_1+b_2X_2\right)^3$ . The dependence of the interpretation on $X_1$ and $X_2$ is not simply expressed in words, unlike the situations with no transformation of $Y$ (one unit change in $X_i$ is associated with a change of $b_i$ in $Y$ ) or with the logarithm (one percent change in $X_i$ is associated with $b_i$ percent change in $Y$ ). However, by keeping the first form of the interpretation, and computing $4b_1$ = $4\times 0.000075223$ = $0.000301$ , we might state something like A unit change in fees is associated with a change in collections of $0.000301$ times the cube of the current collections; for instance, if the current collections are $10^4 = 10,000$ , then a unit increase in fees is associated with an increase of $0.301$ in collections and if the current collections are $20^4 = 80,000$ , then the same unit increase in fees is associated with an increase of $2.41$ in collections. When taking roots other than the fourth--say, when using $Y^p$ as the response rather than $Y$ itself, with $p$ nonzero--simply replace all appearances of " $4$ " in this analysis by " $1/p$ ".
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/35982', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13968/']}
jdg_372312
stackexchange
llm_judgeable_groundtruth_similarity
10521341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In school we've been taught that compilers compile a computer program to machine language. We've also been taught that the machine language consists of direct instructions to the hardware. Then how can the same compiled program run on several computer configurations with different hardware? Now provide the response and nothing else.
Depends what you mean by 'different hardware' if it is the same processor (or same family eg Intel x86) then the machine code instructions are the same. If the extra hardware is different peripherals (screens, disks printers etc) then the operating system hides those details by giving you a consistent set of instructions to drive them If you mean, how can you run a program for an ARM cpu on an Intel x86, then you can't - except by some sort of virtual machine emulator that reads each of the ARM instructions and either translates them into x86 or runs the same functionality as a set of x86 funcs and then returns the same answer that the ARM ones would have done. Edit: I assume you mean PCs with different hw - ie different peripherals but the same processor family? Talking to hardware doesn't involve specific instructions as such - it's mostly a matter of moving memory to specific locations where the operating system and/or device driver have specifically reserved for data going to that device. In the old days of DOS and BIOS you would then trigger an interupt to call a specific bit of code in the BIOS to act on that data and send it to the HW.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10521341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1070897/']}
jdg_372313
stackexchange
llm_judgeable_groundtruth_similarity
1233839
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f\in k[x,y]$, where $k$ is an algebraically closed field. I would like to prove the curve $f(x,y)=0$ has infinitely many points. What I know is $k$ is infinite, but I don't know how to use this to prove this curve has infinite points. Shafarevich speaks about this in Basic Algebraic Geometry 1: Varieties in Projective Space on the page 4, so I suppose this should be trivial. Thanks Now provide the response and nothing else.
We need the hypothesis that $f$ is (either zero or) nonconstant. Assume WLOG that $f(x, y)$ is nonconstant in $x$. Write $f(x, y) = x^n g(y) + \text{lower terms}$ where $x^n$ is the highest order term in $x$ and $g(y)$ is a nonzero polynomial in $y$. For all but finitely many values $y_0$ of $y$, $g(y_0)$ is nonzero, so for all but finitely many values $y_0$ of $y$, $f(x, y_0)$ is a nonconstant polynomial in $x$ and hence has a root.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1233839', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42912/']}
jdg_372314
stackexchange
llm_judgeable_groundtruth_similarity
12155908
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Python datetime to Unix timestamp Is there a way to convert a datetime to int , representing the minutes since, for example, January 2012, so that this int can be modified, written to a database, compared and so on?EDIT:The server I am running this on uses Python 2.6.6 Now provide the response and nothing else.
Subtracting two datetime.datetime objects gives you a timedelta object , which has a .total_seconds() method (added in Python 2.7). Divide this by 60 and cast to int() to get minutes since your reference date: import datetimejanuary1st = datetime.datetime(2012, 01, 01)timesince = datetime.datetime.now() - january1stminutessince = int(timesince.total_seconds() / 60) or in a python shell: >>> import datetime>>> january1st = datetime.datetime(2012, 01, 01)>>> timesince = datetime.datetime.now() - january1st>>> minutessince = int(timesince.total_seconds() / 60)>>> minutessince346208 For python 2.6 and earlier, you'll have to use the .days and .seconds attributes to calculate the minutes: minutessince = timesince.days * 1440 + timesince.seconds // 60 which gives you an integer as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12155908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530476/']}
jdg_372315
stackexchange
llm_judgeable_groundtruth_similarity
2512254
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I write a loop in ruby so that I can execute a block of code on each file? I'm new to ruby, and I've concluded that the way to do this is a do each loop. The ruby file will be executed from a different directory than the directory I want to loop through. I've tried the Dir.foreach and I couldn't get it to work. Now provide the response and nothing else.
As others have said, Dir::foreach is a good option here. However, note that Dir::foreach and Dir::entries will always include . and .. (the current and parent directories). You will generally not want to work on them, so you can use Dir::each_child or Dir::children (as suggested by ma11hew28 ) or do something like this: Dir.foreach('/path/to/dir') do |filename| next if filename == '.' or filename == '..' # Do work on the remaining files & directoriesend Dir::foreach and Dir::entries (as well as Dir::each_child and Dir::children ) also include hidden files & directories. Often this is what you want, but if it isn't, you need to do something to skip over them. Alternatively, you might want to look into Dir::glob which provides simple wildcard matching: Dir.glob('/path/to/dir/*.rb') do |rb_filename| # Do work on files & directories ending in .rbend
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2512254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301312/']}
jdg_372316
stackexchange
llm_judgeable_groundtruth_similarity
230634
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to fit a mixed effects model with a binary outcome. I have one fixed effect (Offset) and one random effect (chamber, with muliple data points coming from each chamber). In the text book "The R Book", (2007), pg 604, Crawley suggests using the lmer function with a binomial family for the analysis of binomial data where each participant contributes multiple responses (analagous to each of my chambers contributing multiple outcomes). Based on this example, I have used the following script for my data: ball=lmer(Buried~Offset+(1|Chamber), family=binomial, data=ballData) When I run this model, I get this warning: calling lmer with 'family' is deprecated; please use glmer() instead When I change my code to the following, the model works: ball=glmer(Buried~Offset+(1|Chamber), family=binomial, data=ballData) Based on other questions/answers that I have read on Cross Validated, lmer should only be used for data where the outcome is normally distributed, and glmer is the correct function to use for a binomial outcome. My questions are: 1) Could anyone clarify the discrepency between Crawleys advice and the fact that lmer would not work for me (nor, based on what I have read on CVed, is it recommended to use this function for binomial data) 2) Is glmer indeed the correct function to use to model a binomial outcome with random factors? 3) Assuming that glmer is the correct function to use, I want to compare a model with and without random effects to determine if including random effects improves the fit of the model. I understand that glmer estimates model parameters via maximum likelihood. What function can I use to create a model with no random effects for a binary outcome using maximum likelihood? I was playing around with glm however the help file for this function states that the method of estimation is iteratively reweighted least squares (which is beyond me, but it isn't ML...) Now provide the response and nothing else.
1) In previous versions of the lme4 package, you could run lmer using the binomial family. However, all this did was to actually call glmer , and this functionality has now been removed. So at the time of writing Crawley was correct. 2) Yes, glmer is the correct function to use with a binary outcome. 3) glm can fit a model for binary data without random effects. However, it is incorrect to compare a model fitted with glm to one fitted with glmer using a likelihood-based test because the likelihoods are not comparable. From your description, you have repeated measures within chambers. So, assuming that you have sufficient chambers and these can be thought of as a random sample from a larger population of chambers, then a priori you should retain the random intercepts for Chamber to control for possible non-independence of observations within chambers. You can think of random intercepts as being part of the experimental design. On the other hand, if the random effect variance is very small and/or the inference or predictions for both the glm and glmer model are the largely the same, then it really doesn't matter which you use anyway.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/230634', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/127429/']}
jdg_372317
stackexchange
llm_judgeable_groundtruth_similarity
310492
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am developing a backend where in I will be exposing APIs for my mobile application. Users can register,add products,share the links of products through email/sms/anywhere and others can click on it and buy the product. This is the simple workflow of the mobile application. The app is an image intensive app which will have image uploads and retrieval which will be done by third party cloud service. SO the image part is not handled by my backend. Now I am from the development team and have little experience on hardware server side. When I gave the requirement for the infrastructure, they have given asked me the following questions. Application/Storage Throughput Application throughput (No. of concurrent connections in 3 months , 6months and 1 year) Storage throughput (Data growth in 3 months , 6 months and 1 year) HA requirement DR requirement I am not sure how do I forecast the above 3 points. How are through puts calculated? I will on an estimate will be having 10000 users registering on my application in the first month out of which 5000 will be active users. On an average login to application there will be 10 API hits per user which will lead to 5000*10 = 50,000 hits per month which would be 1 API hit per minute,ie ~2 concurrent connections in first month. Is the calculation goes like this? and how do I calculate the data growth ? Does it mean, a user registers,creates product and if I total the database size consumed for that, is that what is called data growth? This question would seem pathetic, but I genuinely need help in figuring out how throughputs are calculated for server requirements. Now provide the response and nothing else.
The first three points are capacity planning. The organization is trying to budget and predict for the future. Alas, there is no simple or accepted way to predict performance and scalability. Each application and environment is different. Therefore, the best way to answer this is to measure. Specifically: Discuss with your management or product owners what the likely growth in users will be and the types of different users. If they do not know, guess but document that these are guesses. Create an automated run through of common paths of your application. You can record activity or enter your own into load testing applications like JMeter . Create a test environment that matches your current or projected hardware. Pay close attention to things like bandwidth, storage, SSL, logging or other frequently forgotten aspects that could affect performance. Mock out the third party image service if you can, using smaller or representative images. Use the load testing application to create the proposed for the projected numbers of users at different times. Use an application performance management tool, like AppDynamics or DynaTrace , to measure performance and identify bottlenecks. In addition to above requirements, this can help you: Confirm your environment supports the requested load. Find the maximum load your environment supports. Find the bottleneck(s) limiting your performance or scalability. Experiment with different configurations to see how the perform or scale. Observe how the system copes when you trigger failures. The last two points, HA requirement (high availability) and DR (disaster recovery, presumably RPO (recovery point objective) and RTO (recovery time objective) ), are harder to predict as these are really business requirements. Discuss with your management or product owners the likely failures and how much they will cost to mitigate or fix . If both of you are new to this, expect lots of guessing and late nights on your part.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/310492', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/210315/']}
jdg_372318
stackexchange
llm_judgeable_groundtruth_similarity
7244
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Lets say I have a website which gets 100 hits per day (mu = 100). Yesterday my website got 130 hits (x = 130). If I assume a Poisson distribution, then the probability of getting 130 hits is: > dpois(130, 100)[1] 0.0005752527 # about 0.06% So this tells me that getting 130 hits is quite unusual for my website due to the low probability. My understanding of statistical significance is that it is used to determine whether the outcome of an experiment is due either to chance or some kind of deterministic relationship. How would I apply that in this situation? What test should one use? (and is it in R?) Many thanks in advance for your time. Note: I saw someone at a business talk asked something very similar to this and I had no idea what they meant by it, and so now I'm just trying to educate myself. I'm new to R, but that seems like the software most used for these kind of questions, hence my request. Now provide the response and nothing else.
There are two points to make: It is not the specific value of 130 that is unusual, but that it is much larger than 100. If you got more than 130 hits, that would have been even more surprising. So we usually look at the P(X>=130), not just P(X=130). By your logic even 100 hits would be unusual, because dpois(100,100)=0.04 . So a more correct calculation is to look at ppois(129, 100, lower=F)=0.00228 . This is still small, but not as extreme as your value. And this does not even take into account, that an unusually low number of hits might also surprise you. We often multiply the probability of exceeding the observed count by 2 to account for this. If you keep checking your hits every day, sooner or later even rare events will occur. For example P(X>=130) happens to be close to 1/365, so such an event would be expected to occur once a year.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/7244', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3253/']}
jdg_372319
stackexchange
llm_judgeable_groundtruth_similarity
54989929
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Apache CXF with Spring Boot with the help of cxf-spring-boot-starter-jaxws plugin of version 3.2.7. My intention is to customize the LoggingInterceptors but when I created the below class: public class CustomLoggingInInterceptor extends org.apache.cxf.interceptor.LoggingInInterceptor {} but my IDE strikes out the LoggingInInterceptor complaining it's deprecated with the explanation use logging module rt/features/logging instead So how should one go about customizing the logging interceptor using this module ? Now provide the response and nothing else.
What this message is telling you, is to use the Apache CXF Advanced logging feature module. Its dependency is (latest version) <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-features-logging</artifactId> <version>3.3.0</version> <scope>test</scope></dependency> Inside you'll find a comparable org.apache.cxf.ext.logging.LoggingInInterceptor ( link ) I'm not a CXF user, however I suppose you'll have to interact with a JaxWsProxyFactoryBean . Remember you need to use the same version for all the CXF modules. After getting an hold on it, you can do factory.getInInterceptors().add(new MyCustomInterceptor());
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54989929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7156098/']}
jdg_372320
stackexchange
llm_judgeable_groundtruth_similarity
39456022
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to upgrade to php7 which I installed via homebrew. In CLI php -v returns PHP 7.0.10 (cli) (built: Aug 21 2016 19:14:33) ( NTS )Copyright (c) 1997-2016 The PHP GroupZend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies But for localhost, firefox pops up a problem loading page, and I can't view a localhost/phpinfo.php; if I swap the module lines out back to php5 it works fine. Here's a pastebin http://pastebin.com/950yC7wA of my apache2/httpd.conf, I have no idea how to go about fixing this. osx version El Capitan 10.11 Now provide the response and nothing else.
Make sure that: You've followed the instructions from brew info php@7.1 : ==> CaveatsTo enable PHP in Apache add the following to httpd.conf and restart Apache: LoadModule php7_module /usr/local/opt/php@7.1/lib/httpd/modules/libphp7.so <FilesMatch \.php$> SetHandler application/x-httpd-php </FilesMatch>Finally, check DirectoryIndex includes index.php DirectoryIndex index.php index.html You restarted Apache via sudo apachectl restart . For step by step tutorial, see: Setup Apache, MySQL and PHP using Homebrew on macOS Sierra . Troubleshooting When something doesn't work, check the logs in real-time via: tail -f /usr/local/var/log/apache2/*error* Then start/restart the server. Note: When finished, hit Control - C to quit tail .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39456022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4781945/']}
jdg_372321
stackexchange
llm_judgeable_groundtruth_similarity
12954193
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following statement throws java.lang.ArithmeticException: / by zero as obvious. System.out.println(0/0); because the literal 0 is considered to be an int literal and divide by zero is not allowed in integer arithmetic. The following case however doesn't throw any exception like java.lang.ArithmeticException: / by zero . int a = 0;double b = 6.199;System.out.println((b/a)); It displays Infinity . The following statement produces NaN (Not a Number) with no exception. System.out.println(0D/0); //or 0.0/0, or 0.0/0.0 or 0/0.0 - floating point arithmetic. In this case, both of the operands are considered to be double. Similarly, the following statements don't throw any exception. double div1 = 0D/0; //or 0D/0Ddouble div2 = 0/0D; //or 0D/0DSystem.out.printf("div1 = %s : div2 = %s%n", div1, div2);System.out.printf("div1 == div2 : %b%n", div1 == div2);System.out.printf("div1 == div1 : %b%n", div1 == div1);System.out.printf("div2 == div2 : %b%n", div2 == div2);System.out.printf("Double.NaN == Double.NaN : %b%n", Double.NaN == Double.NaN);System.out.printf("Float.NaN == Float.NaN : %b%n", Float.NaN == Float.NaN); They produce the following output. div1 = NaN : div2 = NaNdiv1 == div2 : falsediv1 == div1 : falsediv2 == div2 : falseDouble.NaN == Double.NaN : falseFloat.NaN == Float.NaN : false They all return false. Why is this operation (division by zero) allowed with floating point or double precision numbers? By the way, I can understand that floating point numbers (double precision numbers) have their values that represent positive infinity , negative infinity , not a number ( NaN )... Now provide the response and nothing else.
In short, that's the way it's specified in the IEEE-754 standard, which is what Java's Floating-Point Operations are based on. Why doesn't division by zero (or overflow, or underflow) stop the program or trigger an error? Why does a standard on numbers include "not-a-number" (NaN)? The 754 model encourages robust programs. It is intended not only for numerical analysts but also for spreadsheet users, database systems, or even coffee pots. The propagation rules for NaNs and infinities allow inconsequential exceptions to vanish. Similarly, gradual underflow maintains error properties over a precision's range. When exceptional situations need attention, they can be examined immediately via traps or at a convenient time via status flags. Traps can be used to stop a program, but unrecoverable situations are extremely rare. Simply stopping a program is not an option for embedded systems or network agents. More often, traps log diagnostic information or substitute valid results. Flags offer both predictable control flow and speed. Their use requires the programmer be aware of exceptional conditions, but flag stickiness allows programmers to delay handling exceptional conditions until necessary.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12954193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1391249/']}
jdg_372322
stackexchange
llm_judgeable_groundtruth_similarity
14063599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I thought the whole point of 2's complement was that operations could be implemented the same way for signed and unsigned numbers. Wikipedia even specifically lists multiply as one of the operations that benefits . So why does x86 have separate instructions for each, mul and imul ? Is this still true for x86-64? Now provide the response and nothing else.
Addition and subtraction are the same, as is the low-half of a multiply. A full multiply, however, is not. Simple example: In 32-bit twos-complement, -1 has the same representation as the unsigned quantity 2**32 - 1. However: -1 * -1 = +1(2**32 - 1) * (2**32 - 1) = (2**64 - 2**33 + 1) (Note that the low 32-bits of both results are the same; that's what I mean when I say the "low-half of the multiply" is the same).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14063599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50385/']}
jdg_372323
stackexchange
llm_judgeable_groundtruth_similarity
6948274
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm creating an android app, we want to add a feature that play something after each the user has canceled an alarm.I doubt that this is possible but asking anyway, because otherwise i'll need to create yet another alarm app and bundle it inside the main app. Thanks for your help in advance. Now provide the response and nothing else.
No, it's not threadsafe. invoc needs to be declared volatile, or accessed while synchronizing on the same lock, or changed to use AtomicInteger. Just using the synchronized method to increment invoc, but not synchronizing to read it, isn't good enough. The JVM does a lot of optimizations, including CPU-specific caching and instruction reordering. It uses the volatile keyword and locking to decide when it can optimize freely and when it has to have an up-to-date value available for other threads to read. So when the reader doesn't use the lock the JVM can't know not to give it a stale value. This quote from Java Concurrency in Practice (section 3.1.3) discusses how both writes and reads need to be synchronized: Intrinsic locking can be used to guarantee that one thread sees the effects of another in a predictable manner, as illustrated by Figure 3.1. When thread A executes a synchronized block, and subsequently thread B enters a synchronized block guarded by the same lock, the values of variables that were visible to A prior to releasing the lock are guaranteed to be visible to B upon acquiring the lock. In other words, everything A did in or prior to a synchronized block is visible to B when it executes a synchronized block guarded by the same lock. Without synchronization, there is no such guarantee. The next section (3.1.4) covers using volatile: The Java language also provides an alternative, weaker form of synchronization, volatile variables, to ensure that updates to a variable are propagated predictably to other threads. When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations. Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread. Back when we all had single-CPU machines on our desktops we'd write code and never have a problem until it ran on a multiprocessor box, usually in production. Some of the factors that give rise to the visiblity problems, things like CPU-local caches and instruction reordering, are things you would expect from any multiprocessor machine. Elimination of apparently unneeded instructions could happen for any machine, though. There's nothing forcing the JVM to ever make the reader see the up-to-date value of the variable, you're at the mercy of the JVM implementors. So it seems to me this code would not be a good bet for any CPU architecture.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6948274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267980/']}
jdg_372324
stackexchange
llm_judgeable_groundtruth_similarity
32873328
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given this mockup: +-----------+-------------+---------------------------+| item_id | item_name | desc |+-----------+-------------+---------------------------+| 1 | Product 1 | lorem ipsum dolor... || 2 | Product 2 | lorem mauris eu... || 3 | Product 3 | scelerisque sagittis... || 4 | Product 4 | lorem dolor ipsum... || 5 | Product 5 | ipsum dolor lorem... |+-----------+-------------+---------------------------+ And I want to search all of the products that contain the words lorem ipsum in either item_name or desc . Additionally, any words can appear between lorem and ipsum , and lorem and ipsum can appear in any order. Basically, this search would return items 1 , 4 , and 5 Now, I know I could accomplish this with: SELECT * FROM itemsWHERE (item_name LIKE 'lorem%ipsum' OR desc LIKE 'lorem%ipsum')OR (item_name LIKE 'ipsum%lorem' OR desc LIKE 'ipsum%lorem') But if my search term is longer (ie. lorem ipsum dolor sit amet, consectetur adipiscing elit), I feel like it could become a bit ridiculous with the number of OR added to the query. Is there an easier/more efficient way to handle this? Now provide the response and nothing else.
this sort of search requirement sounds a good candidate for full text search . Full text search is (or at least can be) more of a "search engine" like search as opposed to the traditional sql like searches. With full text searching, the order of the words being searched for does not matter, and depending on the RDBMs some full text searching capabilities allow for synonym lookup, as well as noise word filtering. In (i believe) most cases, full text searching is significantly faster than a like search. Here is an article on getting started with full text search in mysql. Example mySql full text search syntax: select *from itemswhere match(item_name) against ('+lorem +ipsum' in boolean mode) Full text searching does have certain requirements (which are gone into detail in the links in the article). I've not personally worked with mysql s full text search, or I'd list out the steps. Should be enough to get you started though if you wanted to go in that direction.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32873328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2989682/']}
jdg_372325
stackexchange
llm_judgeable_groundtruth_similarity
31813
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There is a website that tenants can use to pay their rent. That website uses an http address but apparently uses a third-party product, which embeds an iframe into the page. The source of that iframe is https and all forms within the page are within that iframe. I'm wondering what are the security risks of this type of setup for the users. I would also add that located on the bottom of every page is a "seal" from godaddy that you click on and it provides some security-related information about the iframe source. My intuition says that is not ideal. For one thing, seeing the browser's address bar unable to provide identity/encryption information is disconcerting. Without viewing the source of the page, how do I know where the iframe content is from? Is relying on the godaddy seal sufficient? Now provide the response and nothing else.
I'm wondering what are the security risks of this type of setup for the users. It's almost as bad as serving everything over plain HTTP. You get protection against purely passive listening attacks, but really anyone in the position to do that kind of man-in-the-middle attack is very likely also to be able to do an active attack, changing the content that gets sent back to the browser. That could include changing the iframe src in the unprotected parent page, or injecting some attack script. In practice the HTTPS-iframe gets you protection from a casual attacker sniffing general traffic, but for any man-in-the-middle targeting the site specifically it is trivial to make the measure ineffective. It's up to the provider whether they think this barely-more-than-plain-HTTP assurance is suitable for the kind of information that will be entered into the frame - except if that information contains credit card data, in which case they have an obligation to abide by the PCI-DSS rules requiring HTTPS. (Assessors are expected to verify that HTTPS indicators are visible in the browser chrome.) seeing the browser's address bar unable to provide identity/encryption information is disconcerting. Yes - independently of the question of actual security, this is poor perceived-security and may put some users off. Without viewing the source of the page, how do I know where the iframe content is from? Quite. Viewing source/DOM isn't something you can expect an average user to do. Additionally, even if you verify the iframe is being served using HTTPS, there is nothing stopping the unsecured parent page from interfering with it with 'clickjacking' attacks, for example a keylogging overlay form. Is relying on the godaddy seal sufficient? Seals offer no security, as they are trivially spoof-able. They are nothing but a marketing exercise; CAs should be ashamed of this deliberately misleading behaviour.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/31813', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/21401/']}
jdg_372326
stackexchange
llm_judgeable_groundtruth_similarity
544009
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: When I run apache on port 80 it works fine. But if I change the port then it's accepting connection from localhost only. Somebody please help me figure out what is the problem. My iptables -L result Chain INPUT (policy ACCEPT)target prot opt source destinationACCEPT tcp -- anywhere anywhere tcp dpt:1032 Chain FORWARD (policy ACCEPT)target prot opt source destination Chain OUTPUT (policy ACCEPT)target prot opt source destination Now provide the response and nothing else.
i'd always trust if my webservers are telling me: 502 Bad Gateway what is the uptime of your fastcgi/nginx - process? do you monitor network-connections? can you confirm/deny a change of visitors-count around that day? what does it mean: you fastcgi-process is not accessible by nginx; either to slow or not corresponding at all. bad gateway means: nginx cannot fastcgi_pass to that defined ressource 127.0.0.1:9000; at that very specific moment . your inital error-logs tells it all: . recv() failed -> nginx failed(104: Connection reset by peer) while reading response header from upstream, -> no complete answer, or no answer at allupstream: "fastcgi://127.0.0.1:9000", -> who is he, who failed??? from my limited pov i'd suggest: restart your fastcgi_process / server check your access-log enable debug-log
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/544009', 'https://serverfault.com', 'https://serverfault.com/users/192780/']}
jdg_372327
stackexchange
llm_judgeable_groundtruth_similarity
36010984
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Spark SQL for reading parquet and writing parquet file. But some cases,i need to write the DataFrame as text file instead of Json or Parquet. Is there any default methods supported or i have to convert that DataFrame to RDD then use saveAsTextFile() method? Now provide the response and nothing else.
Using Databricks Spark-CSV you can save directly to a CSV file and load from a CSV file afterwards like this import org.apache.spark.sql.SQLContextSQLContext sqlContext = new SQLContext(sc);DataFrame df = sqlContext.read() .format("com.databricks.spark.csv") .option("inferSchema", "true") .option("header", "true") .load("cars.csv");df.select("year", "model").write() .format("com.databricks.spark.csv") .option("header", "true") .option("codec", "org.apache.hadoop.io.compress.GzipCodec") .save("newcars.csv");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36010984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1907755/']}
jdg_372328
stackexchange
llm_judgeable_groundtruth_similarity
46085500
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I honestly cannot believe how hard this is...first off the requirements that I am going for: Implementing Entity Framework Core 2.0' IDesignTimeDbContextFactory which is IDbContextFactory renamed to be less confusing to developers as to what it does I do not want to have to do loading of appsettings.json more than once. One reason is because my migrations are running in the domain of MyClassLibrary.Data and there is no appsettings.js file in that class library, I would have to to Copy to Output Directory appsettings.js . Another reason is that it just not very elegant. So here is what I have that currently works: using System;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Design;using Microsoft.Extensions.Configuration;using AppContext = Tsl.Example.Data.AppContext;namespace Tsl.Example{ public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppContext> { public AppContext CreateDbContext(string[] args) { string basePath = AppDomain.CurrentDomain.BaseDirectory; string envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(basePath) .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{envName}.json", true) .Build(); var builder = new DbContextOptionsBuilder<AppContext>(); var connectionString = configuration.GetConnectionString("DefaultConnection"); builder.UseMySql(connectionString); return new AppContext(builder.Options); } }} And here is my Program.cs: using System.IO;using System.Reflection;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.Logging;namespace Tsl.Example{ public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } //public static IWebHost BuildWebHost(string[] args) => // WebHost.CreateDefaultBuilder(args) // .UseStartup<Startup>() // .Build(); /// <summary> /// This the magical WebHost.CreateDefaultBuilder method "unboxed", mostly, ConfigureServices uses an internal class so there is one piece of CreateDefaultBuilder that cannot be used here /// https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/ /// </summary> /// <param name="args"></param> /// <returns></returns> public static IWebHost BuildWebHost(string[] args) { return new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { IHostingEnvironment env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); }) //.UseIISIntegration() .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .UseStartup<Startup>() .Build(); } }} And here is my Startup.cs: using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.DependencyInjection;using ServiceStack;using Tsl.Example.Interfaces;using Tsl.Example.Provider;using AppContext = Tsl.Example.Data.AppContext;namespace Tsl.Example{ public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddTransient<IAppContext, AppContext>(); services.AddTransient<IExampleDataProvider, ExampleDataProvider>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseServiceStack(new AppHost()); } }} What I would like to do is use the IOptions pattern , so I created this class: namespace Tsl.Example{ /// <summary> /// Strongly typed settings to share in app using the .NET Core IOptions pattern /// https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/ /// </summary> public class AppSettings { public string DefaultConnection { get; set; } }} Added this line to Startup.ConfigureServices : services.Configure<AppSettings>(options => Configuration.GetSection("AppSettings").Bind(options)); And then tried and change my implementation of IDesignTimeDbContextFactory<AppContext> to: public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppContext>{ private readonly AppSettings _appSettings; public DesignTimeDbContextFactory(IOptions<AppSettings> appSettings) { this._appSettings = appSettings.Value; } public AppContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<AppContext>(); builder.UseMySql(_appSettings.DefaultConnection); return new AppContext(builder.Options); }} Unfortunately this did not work because the Ioptions<AppSettings> argument of public DesignTimeDbContextFactory(IOptions<AppSettings> appSettings) constructor is not injected. I assume this is because implementations of IDesignTimeDbContextFactory<AppContext> are called at Design time and dependency injection is just not "ready" in .NET Core apps at design time? I think it is kind of strange that it is so hard to inject an environment specific connection string using the Entity Framework Core 2.0 pattern of implementing IDesignTimeDbContextFactory , and also not having to copy and load settings files like appsettings.json more than once. Now provide the response and nothing else.
If you are looking for solution to get database connection string from your custom settings class initialized from appsettings.json file - that is how you can do this. Unfortunatelly you can't inject IOptions via DI to your IDesignTimeDbContextFactory implementation constructor. public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppContext>{ public AppContext CreateDbContext(string[] args) { // IDesignTimeDbContextFactory is used usually when you execute EF Core commands like Add-Migration, Update-Database, and so on // So it is usually your local development machine environment var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); // Prepare configuration builder var configuration = new ConfigurationBuilder() .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) .AddJsonFile("appsettings.json", optional: false) .AddJsonFile($"appsettings.{envName}.json", optional: false) .Build(); // Bind your custom settings class instance to values from appsettings.json var settingsSection = configuration.GetSection("Settings"); var appSettings = new AppSettings(); settingsSection.Bind(appSettings); // Create DB context with connection from your AppSettings var optionsBuilder = new DbContextOptionsBuilder<AppContext>() .UseMySql(appSettings.DefaultConnection); return new AppContext(optionsBuilder.Options); }} Of course in your AppSettings class and appsettings.json you could have even more sophisticated logic of building the connection string. For instance, like this: public class AppSettings{ public bool UseInMemory { get; set; } public string Server { get; set; } public string Port { get; set; } public string Database { get; set; } public string User { get; set; } public string Password { get; set; } public string BuildConnectionString() { if(UseInMemory) return null; // You can set environment variable name which stores your real value, or use as value if not configured as environment variable var server = Environment.GetEnvironmentVariable(Host) ?? Host; var port = Environment.GetEnvironmentVariable(Port) ?? Port; var database = Environment.GetEnvironmentVariable(Database) ?? Database; var user = Environment.GetEnvironmentVariable(User) ?? User; var password = Environment.GetEnvironmentVariable(Password) ?? Password; var connectionString = $"Server={server};Port={port};Database={database};Uid={user};Pwd={password}"; return connectionString; }} With just values stored in appsettings.json : { "Settings": { "UseInMemory": false, "Server": "myserver", "Port": "1234", "Database": "mydatabase", "User": "dbuser", "Password": "dbpassw0rd" }} With password and user stored in environment variables: { "Settings": { "UseInMemory": false, "Server": "myserver", "Port": "1234", "Database": "mydatabase", "User": "MY-DB-UID-ENV-VAR", "Password": "MY-DB-PWD-ENV-VAR" }} In this case you should use it this way: // Create DB context with connection from your AppSettings var optionsBuilder = new DbContextOptionsBuilder<AppContext>();if(appSettings.UseInMemory) {optionsBuilder = appSettings.UseInMemory ? optionsBuilder.UseInMemoryDatabase("MyInMemoryDB") : optionsBuilder.UseMySql(appSettings.BuildConnectionString());return new AppContext(optionsBuilder.Options);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46085500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258525/']}
jdg_372329
stackexchange
llm_judgeable_groundtruth_similarity
493055
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I added Varnish in front of nginx. When I try to login to WordPress, I go to domain.com/wp-admin but I'm now redirected to domain.com:8080/wp-admin. I can manually remove the port and the admin side functions the way it should. My Varnish config: backend origin { .host = "localhost"; .port = "8080"; .connect_timeout = 60s; .first_byte_timeout = 60s; .between_bytes_timeout = 60s;}acl purge { "localhost";}sub vcl_recv { set req.backend = origin; set req.http.X-Forwarded-For = client.ip; if(req.url ~ "^/wp-(login|admin)" || req.http.Cookie ~ "wordpress_logged_in_") { return (pass); } if(req.url ~ "/xmlrpc.php") { return(pass); } if( req.url ~ "\?s=" ){ return (pass); } if (req.request == "BAN") { if(!client.ip ~ purge) { error 405 "Not allowed."; } ban("req.url ~ "+req.url+" && req.http.host == "+req.http.host); error 200 "Banned."; } if (req.request != "GET" && req.request != "HEAD" && req.request != "PUT" && req.request != "POST" && req.request != "TRACE" && req.request != "OPTIONS" && req.request != "DELETE") { return (pipe); } if (req.request != "GET" && req.request != "HEAD") { return (pass); } unset req.http.Cookie; return (lookup);}sub vcl_hit { if (req.request == "PURGE") { purge; } return (deliver);}sub vcl_miss { if (req.request == "PURGE") { purge; } return (fetch);}sub vcl_fetch { unset beresp.http.Server; unset beresp.http.X-Powered-By; if (beresp.status == 404) { set beresp.ttl = 0m; return(hit_for_pass); } if( beresp.http.Set-Cookie && req.url !~ "^/wp-(login|admin)" ){ unset beresp.http.Set-Cookie; } if ( req.request == "POST" || req.http.Authorization ) { return (hit_for_pass); } if ( beresp.status != 200 ) { return (hit_for_pass); } if( req.url ~ "\?s=" ){ return (hit_for_pass); } set beresp.ttl = 5m; return (deliver);}sub vcl_deliver { if (obj.hits > 0) { set resp.http.X-Cache = "HIT"; } else { set resp.http.X-Cache = "MISS"; } unset resp.http.Via; unset resp.http.X-Varnish;}sub vcl_error { if (obj.status == 503 && req.restarts < 2) { set obj.http.X-Restarts = req.restarts; return(restart); } if (obj.status == 301) { set obj.http.Location = req.url; set obj.status = 301; return(deliver); } if (obj.status == 750) { set obj.http.Location = obj.response; set obj.status = 302; return (deliver); }} Now provide the response and nothing else.
I think you are wrong that the redirect only appends the port, without also postfixing a slash to the end of the URL. After catching that issue, it's pretty clear that this an internal redirect that is done by nginx when it encounters that a directory is being accessed without a trailing slash. You would use http://nginx.org/en/docs/http/ngx_http_core_module.html#port_in_redirect to disable the port from being appended: port_in_redirect off; This solution will work great as long as you don't rely on such redirects when trying to access nginx directly on port 8080, and as long as the Host names match between varnish and nginx.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/493055', 'https://serverfault.com', 'https://serverfault.com/users/71374/']}
jdg_372330
stackexchange
llm_judgeable_groundtruth_similarity
2360
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do I convert specific humidity to relative humidity? What variables are needed (e.g. air temperature, pressure, etc.)? Now provide the response and nothing else.
Relative humidity is just $e/e_s$ , the ratio of the vapor pressure to saturation vapor pressure or $w/w_s$ , the ratio of mass mixing ratios of water vapor at actual and saturation values. If you have specific humidity, which is the mass mixing ratio of water vapor in air, defined as: $$ q \equiv \dfrac{m_v}{m_v + m_d} = \dfrac{w}{w+1} \approx w$$ Relative humidity can be expressed as the ratio of water vapor mixing ratio to saturation water vapor mixing ratio, $w/w_s$ , where: $$ w_s \equiv \dfrac{m_{vs}}{m_d} = \dfrac{e_s R_d}{R_v(p-e_s)} \approx 0.622\dfrac{e_s}{p}$$ and from Clausius-Clapeyron: $$ e_s(T) = e_{s0}\exp\left[\left(\dfrac{L_v(T)}{R_v}\right)\left(\dfrac{1}{T_0} -\dfrac{1}{T} \right)\right] \approx 611\exp\left(\dfrac{17.67(T-T_0)}{T-29.65}\right)$$ Once you have calculated $w$ and $w_s$ you can obtain the relative humidity as: $$ RH = 100\dfrac{w}{w_s} \approx 0.263pq\left[\exp\left(\dfrac{17.67(T-T_0)}{T-29.65}\right)\right]^{-1} $$ You could also calculate $RH = 100(e/e_s)$ , but I think since you are starting with $q$ it isn't as straightforward as doing it this way. Variables used: $q$ specific humidity or the mass mixing ratio of water vapor to total air (dimensionless) $m_v$ specific mass of water vapor (kg) $m_{vs}$ specific mass of water vapor at equilibrium (kg) $m_d$ specific mass of dry air (kg) $w$ mass mixing ratio of water vapor to dry air (dimensionless) $w_s$ mass mixing ratio of water vapor to dry air at equilibrium (dimensionless) $e_s(T)$ saturation vapor pressure (Pa) $e_{s0}$ saturation vapor pressure at $T_0$ (Pa) $R_d$ specific gas constant for dry air (J kg $^{-1}$ K $^{-1}$ ) $R_v$ specific gas constant for water vapor (J kg $^{-1}$ K $^{-1}$ ) $p$ pressure (Pa) $L_v(T)$ specific enthalpy of vaporization (J kg $^{-1}$ ) $T$ temperature (K) $T_0$ reference temperature (typically 273.16 K) (K)
{}
{'log_upvote_score': 6, 'links': ['https://earthscience.stackexchange.com/questions/2360', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/56/']}
jdg_372331
stackexchange
llm_judgeable_groundtruth_similarity
40320
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The largest eigenvalue of a stochastic matrix (i.e. a matrix whose entries are positive and whose rows add up to $1$) is $1$. Wikipedia marks this as a special case of the Perron-Frobenius theorem , but I wonder if there is a simpler (more direct) way to demonstrate this result. Now provide the response and nothing else.
Here's a really elementary proof (which is a slight modification of Fanfan's answer to a question of mine ). As Calle shows, it is easy to see that the eigenvalue $1$ is obtained. Now, suppose $Ax = \lambda x$ for some $\lambda > 1$. Since the rows of $A$ are nonnegative and sum to $1$, each element of vector $Ax$ is a convex combination of the components of $x$, which can be no greater than $x_{max}$, the largest component of $x$. On the other hand, at least one element of $\lambda x$ is greater than $x_{max}$, which proves that $\lambda > 1$ is impossible.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/40320', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10053/']}
jdg_372332
stackexchange
llm_judgeable_groundtruth_similarity
403065
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the C++ complex library, the method norm() of a complex number actually returns the square of what I have learned is usually called the "Norm". Reference: std::norm For example, std::norm() of (3,4) is 25. To me, this looks very confusing: why did people implement something that does not correspond to the "usual" use of the name? Now provide the response and nothing else.
This is not a C++ library issue but a question of mathematical terminology. In mathematics, a norm can mean different things: What you call norm is the Euclidian norm, which is the distance to the origin. In C++ it's abs() . This naming convention has the advantage of being consistent for complex and for real numbers (the origin in the latter case being 0.0). What the C++ library calls norm() corresponds to the field norm from complex numbers to real numbers. It's also known as absolute square . Post Scriptum: the early design of the C++ complex number library dates back to 1984, before templates did exist. In the article (link on this page ), Rose & Stroustrup explain that norm() was intended for comparing magnitudes faster, but at the same time was more subject to overflows.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/403065', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/353920/']}
jdg_372333
stackexchange
llm_judgeable_groundtruth_similarity
304837
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When I tried to upgrade from Ubuntu 14.04 to 16.04, this is the message logs shown after sudo apt-get upgrade . Notice the last line, how do I forcefully update those 961 items? .......................................................................... .......................................................................... xserver-xorg-input-vmmouse-lts-vivid xserver-xorg-input-wacom-lts-vivid xserver-xorg-lts-vivid xserver-xorg-video-all-lts-vivid xserver-xorg-video-ati-lts-vivid xserver-xorg-video-cirrus-lts-vivid xserver-xorg-video-fbdev-lts-vivid xserver-xorg-video-intel-lts-vivid xserver-xorg-video-mach64-lts-vivid xserver-xorg-video-mga-lts-vivid xserver-xorg-video-neomagic-lts-vivid xserver-xorg-video-nouveau-lts-vivid xserver-xorg-video-openchrome-lts-vivid xserver-xorg-video-r128-lts-vivid xserver-xorg-video-radeon-lts-vivid xserver-xorg-video-savage-lts-vivid xserver-xorg-video-siliconmotion-lts-vivid xserver-xorg-video-sisusb-lts-vivid xserver-xorg-video-tdfx-lts-vivid xserver-xorg-video-trident-lts-vivid xserver-xorg-video-vesa-lts-vivid xserver-xorg-video-vmware-lts-vivid yelp zeitgeist-core zenity zenity-common 0 upgraded, 0 newly installed, 0 to remove and 961 not upgraded. Now provide the response and nothing else.
apt-get upgrade plays it safe: it upgrades all the packages that can be upgraded without breaking other packages. If upgrading package A requires uninstalling package B, apt-get upgrade won't do it, and A ends up in the “not upgraded” list. Over time, packages get broken into pieces, joined together, renamed, etc. In addition to basic dependencies (A requires B), a package C can declare that it “replaces” a package B, indicating that when C is installed, it should be ok to uninstall B. Apt also has a concept of automatically-installed vs manually-installed package; it should be ok to remove an automatically-installed package even if it isn't explicitly getting replaced, whereas manually-installed packages are requested by the user and should stay. But apt-get upgrade doesn't take any risk. There is another command apt-get dist-upgrade which is willing to remove packages if necessary. The idea is that apt-get upgrade only upgrades individual packages, whereas apt-get dist-upgrade upgrades the whole distribution. apt-get upgrade is low-risk and you can pretty much do it without paying attention, whereas apt-get dist-upgrade might occasionally remove a program that you rely on, especially if you haven't taken care to mark all the packages you absolutely need as manually installed. You're unlikely to end up with a broken system after apt-get dist-upgrade , but sometimes you might need to reinstall a package or two. Aptitude has the same command duality, but has introduced prefered synonyms: safe-upgrade = upgrade vs. full-upgrade = dist-upgrade . In addition, Ubuntu provides a program called do-release-upgrade which is the recommended way to upgrade from one Ubuntu release to the next (or from one Ubuntu LTS to the next). This program runs apt-get dist-upgrade under the hood, but makes some checks and preparations first and performs some cleanup afterwards. In summary: If upgrading between Ubuntu releases, use do-release-upgrade . If you're just installing security updates and bug fixes, use apt-get update followed by apt-get upgrade (or aptitude safe-upgrade ). Otherwise use apt-get update followed by apt-get dist-upgrade (or aptitude full-upgrade ).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/304837', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/144663/']}
jdg_372334
stackexchange
llm_judgeable_groundtruth_similarity
263492
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can you explain the card trick that is explained here ? Edit: Here's a summary of the trick as explained in the video: Start by asking a spectator to pick any three cards they like out of a standard 52-card deck, without showing them to you, and write them down (to make sure they won't forget them). ( Ed. note: You can shuffle the deck if you like, or even let the spectator shuffle it, but you don't have to. ) Divide the remaining cards into four piles, so that first pile will have 10 cards, the second and third piles will have 15 cards each, and fourth pile, set aside, will have the remaining 9 cards. Now, tell the spectator to put the first card they picked on top of the first pile, then cut the second pile anywhere they want and put the top half on top of the first pile (and the card they picked). Then they should put the second card they picked on top of what remains of the second pile, cut the third pile anywhere they want and put the top half on top of the second pile, and finally put the third card they picked on what remains of the third pile and place the entire fourth pile on top of it. ( Ed. note: You could have the spectator cut the fourth pile too, if you wanted; it shouldn't matter as long as all nine cards of it eventually end up on top of the third pile. ) Now collect the three piles of cards together so that pile #3 ends up on top of the deck, pile #2 in between and pile #1 on the bottom. Next, take four cards off the top of the deck and place them on the bottom. Deal the cards from the top of the deck alternatingly into two piles, the first pile face up and the second pile face down. Tell the spectator in advance to say "stop" if they see any of their cards in the face-up pile (which they won't). Once you've dealt out the entire deck, set the face-up pile aside, pick up the face-down pile and repeat the process, dealing it into two smaller piles, the first pile face up and the other face down. Again, tell the spectator to say "stop" if they see any of their three cards in the face-up pile — they won't. Keep repeating this process until you're down to just three face-down cards. Show those cards to the spectator; they'll be exactly the ones they picked and wrote down. Now provide the response and nothing else.
As Ross rightly points out, the cuts are just to seemingly make it random though it doesn't affect anything. Irrespective of the cuts, note that there are $15$ cards between the first card the contestant places and the second card the contestant places. Similarly, irrespective of the cuts, note that there are $15$ cards between the second card the contestant places and the third card the contestant places. Let us label the cards as follows. Let $a_k^{j}$ be the $k^{th}$ card from top in the hand of the performer after the $j^{th}$ up-down phase. Initially, i.e. after the contestant places the cards and before the first up-down starts, $j=0$. Now the cards in the last pile i.e. the pile containing $9$ cards (the only pile on which the contestant doesn't place any card) be $a_1^{0}, a_2^{0}, \ldots, a_9^{0}$ starting from the top most card. Let the third card the contestant places on the third pile be $a_{10}^{0}$. Then there are $15$ cards followed by the second card the contestant places on the second pile. Accounting for the $15$ cards in between, the second card is $a_{26}^{0}$. Now there are $15$ cards followed by the first card the contestant places on the first pile. Accounting for the $15$ cards in between, the first card is $a_{42}^{0}$. Hence, now the contestant cards are $\color{red}{a_{10}^{0}, a_{26}^{0}, a_{42}^{0}}$. Now the performer moves $4$ cards to the rear. Hence, now the contestant cards are $a_6^{0}, a_{22}^{0}$ and $a_{38}^{0}$. $$\color{red}{\{a_{10}^{0}, a_{26}^{0}, a_{42}^{0}\} \to \{a_{6}^{0}, a_{22}^{0}, a_{38}^{0}\}}$$ Now in the first up-down phase all the odd number cards are eliminated i.e. $a_{2k-1}^{0}$ gets eliminated. However, on the pile with the cards closed, the order has reversed i.e. $a_2^{0}$ is the bottom most card, followed by $a_4^{0}$ and so on and the top-most card is $a_{52}^{0}$. Now reordering the card so that the topmost card is now $a_1^{1}$, we find that the card $a_{2k}^{0}$ gets mapped to $a_{27-k}^{1}$. Hence, the contestant cards are now at $a_{24}^{1}, a_{16}^{1}$ and $a_8^{1}$. $$\color{red}{\{a_{6}^{0}, a_{22}^{0}, a_{38}^{0}\} \to \{a_{24}^{1}, a_{16}^{1}, a_8^{1}\}}$$There are now $26$ cards left. Now in the second up-down phase all the odd number cards are eliminated i.e. $a_{2k-1}^{1}$ gets eliminated. As before, on the pile with the cards closed, the order has reversed i.e. $a_2^{1}$ is the bottom most card, followed by $a_4^{1}$ and so on and the top-most card is $a_{26}^{1}$. Now reordering the card so that the topmost card is now $a_1^{2}$, we find that the card $a_{2k}^{1}$ gets mapped to $a_{14-k}^{2}$. Hence, the contestant cards are now at $a_{2}^{2}, a_{6}^{2}$ and $a_{10}^{2}$.$$\color{red}{\{a_{24}^{1}, a_{16}^{1}, a_8^{1}\} \to \{a_{2}^{2}, a_{6}^{2}, a_{10}^{2}\}}$$ There are now $13$ cards left. Now in the third up-down phase all the odd number cards are eliminated i.e. $a_{2k-1}^{2}$ gets eliminated. As before, on the pile with the cards closed, the order has reversed i.e. $a_2^{2}$ is the bottom most card, followed by $a_4^{2}$ and so on and the top-most card is $a_{6}^{2}$. Now reordering the card so that the topmost card is now $a_1^{3}$, we find that the card $a_{2k}^{2}$ gets mapped to $a_{7-k}^{3}$. Hence, the contestant cards are now at $a_{6}^{3}, a_{4}^{3}$ and $a_{2}^{3}$.$$\color{red}{\{a_{2}^{2}, a_{6}^{2}, a_{10}^{2}\} \to \{a_6^3,a_4^3, a_2^3\}}$$There are now $6$ cards left. Hence, the last up-down has the open cards as $a_1^{3}$, $a_3^{3}$ and $a_5^{3}$; the closed cards being $a_2^{3}$, $a_4^{3}$ and $a_6^{3}$, which are precisely the contestant cards. EDIT Below is an attempt to explain this pictorially. The document was created using $\LaTeX$ and below is a screenshot.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/263492', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53955/']}
jdg_372335
stackexchange
llm_judgeable_groundtruth_similarity
100534
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What are the most common mistakes and anti-patterns NHibernate user programmers make? Please explain why those are bad practices or give link to resource for further reading. For example: One anti-pattern common for new NHibernate programmers is to use identity/native POID's instead of ORM style onces. Read more here... Now provide the response and nothing else.
My personal "frequently explained" issues: Anti-Patterns Messing around with detached objects (SaveOrUpdate or Merge plus some messy code) instead of using DTO's. The more complex the entities are, the messier the code is. (It also means that it works quite well with trivial entities.) Ayende also calls it the Stripper Pattern and explains the encapsulation issue. Not understanding persistence ignorance and writing NH applications as when using explicit SQL. Symptom of that: calling Update after changing an object, wondering why changes are persisted even if Update had not been called, wondering how to avoid changes to be persisted. I tried to explain it in this SO answer Read how flushing works in the reference documentation . A blog post by kurtharriger who is criticizing exactly what is actually one of the main features (as a prove that it is a common misconception about NH) Not understanding transactions and the unit of work pattern. Frequent anti-patterns: implicit transactions, session-per-operation and session-per-application. Some more reading: Fabio Maulo: Conversation-per-Business-Transaction On nhforge.org: Effective NHibernate Session management for web apps Using NH events to put application logic in (eg. change tracking in insert and update triggers) Create one class per table . Some people don't understand OOD, others don't understand relational design. Mistakes use of one-to-one instead of many-to-one. I tried it to explain in this answer . Using join fetch in combination with SetMaxResult. My latest answers related to that topic: Why doesnt NHibernate eager fetch my data (with some more notes about side effects in the comments) Hibernate - How to make associations eager NHIbernate 1.2 And Lazy Loading Pagination with Hibernate criteria and FetchMode.JOIN Writing self changing entities . When an entity doesn't exactly return the value that had been set by NH, it is considered dirty and gets updated in every session. For instance: replacing the NH persistent collection in a property setter. IList<Address> Addresses { get { return addresses; } // will cause the addresses collection to be built up from scratch // in the database in every session, even when just reading the entity. set { addresses = new List<Address>(value); } } int Whatever { // will make the entity dirty after reading negative values from the db. // this causes unexpected updates after just reading the entity. get { if (whatever < 0) return 0; } set { whatever = value; } } May be more is following.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/100534', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/10433/']}
jdg_372336
stackexchange
llm_judgeable_groundtruth_similarity
2783313
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to dump the contents of a table to a csv file using a MySQL SELECT INTO OUTFILE statement. If I do: SELECT column1, column2INTO OUTFILE 'outfile.csv'FIELDS TERMINATED BY ','FROM table_name; outfile.csv will be created on the server in the same directory this database's files are stored in. However, when I change my query to: SELECT column1, column2INTO OUTFILE '/data/outfile.csv'FIELDS TERMINATED BY ','FROM table_name; I get: ERROR 1 (HY000): Can't create/write to file '/data/outfile.csv' (Errcode: 13) Errcode 13 is a permissions error, but I get it even if I change ownership of /data to mysql:mysql and give it 777 permissions. MySQL is running as user "mysql". Strangely I can create the file in /tmp, just not in any other directory I've tried, even with permissions set such that user mysql should be able to write to the directory. This is MySQL 5.0.75 running on Ubuntu. Now provide the response and nothing else.
Which particular version of Ubuntu is this and is this Ubuntu Server Edition? Recent Ubuntu Server Editions (such as 10.04) ship with AppArmor and MySQL's profile might be in enforcing mode by default. You can check this by executing sudo aa-status like so: # sudo aa-status5 profiles are loaded.5 profiles are in enforce mode. /usr/lib/connman/scripts/dhclient-script /sbin/dhclient3 /usr/sbin/tcpdump /usr/lib/NetworkManager/nm-dhcp-client.action /usr/sbin/mysqld0 profiles are in complain mode.1 processes have profiles defined.1 processes are in enforce mode : /usr/sbin/mysqld (1089)0 processes are in complain mode. If mysqld is included in enforce mode, then it is the one probably denying the write. Entries would also be written in /var/log/messages when AppArmor blocks the writes/accesses. What you can do is edit /etc/apparmor.d/usr.sbin.mysqld and add /data/ and /data/* near the bottom like so: ... /usr/sbin/mysqld { ... /var/log/mysql/ r, /var/log/mysql/* rw, /var/run/mysqld/mysqld.pid w, /var/run/mysqld/mysqld.sock w, **/data/ r, /data/* rw,** } And then make AppArmor reload the profiles. # sudo /etc/init.d/apparmor reload WARNING: the change above will allow MySQL to read and write to the /data directory. We hope you've already considered the security implications of this.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2783313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166/']}
jdg_372337
stackexchange
llm_judgeable_groundtruth_similarity
21336350
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In AngularJS, any inline javascript code that included in HTML templates doesn't work. For Example: main.html file: <div ng-include="'/templates/script.html'"></div> And script.html file: <script type="text/javascript"> alert('yes');</script> When I open main page, I expect an alert message that say 'yes' but nothing happens. I think some security restrictions in the AngularJS is preventing inline scripts, but I couldn't find any workaround about that. Note: I don't use jQuery or any other framework, only AngularJS 1.2.7. Now provide the response and nothing else.
jQlite does not support script tags. jQuery does, so the recommendation is to include jQuery if you need this functionality. From Angular's Igor Minar in this discussion : we looked into supporting script tags in jqlite, but what needs to be done to get a cross-browser support involves a lot of black magic. For this reason we decided that for now we are just going to recommend that users use jquery along with angular in this particular case. It doesn't make sense for us to rewrite one third of jquery to get this working in jqlite. Here's the related github issue jqLite should create elements in same way as jQuery where Igor sums up, before closing the issue, with this: This is too much craziness for jqlite, so we are not going to do it. Instead we are going to document that if you want have script elements in ng:include or ng:view templates, you should use jquery. demo plunker with jquery
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21336350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198062/']}
jdg_372338
stackexchange
llm_judgeable_groundtruth_similarity
38052342
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Context : I am using Passive Aggressor from scikit library and confused whether to use warm start or partial fit. Efforts hitherto : Referred this thread discussion: https://github.com/scikit-learn/scikit-learn/issues/1585 Gone through the scikit code for _fit and _partial_fit . My observations : _fit in turn calls _partial_fit . When warm_start is set, _fit calls _partial_fit with self.coef_ When _partial_fit is called without coef_init parameter and self.coef_ is set, it continues to use self.coef_ Question : I feel both are ultimately providing the same functionalities.Then, what is the basic difference between them? In which contexts, either of them are used? Am I missing something evident? Any help is appreciated! Now provide the response and nothing else.
I don't know about the Passive Aggressor, but at least when using the SGDRegressor , partial_fit will only fit for 1 epoch, whereas fit will fit for multiple epochs (until the loss converges or max_iter is reached). Therefore, when fitting new data to your model, partial_fit will only correct the model one step towards the new data, but with fit and warm_start it will act as if you would combine your old data and your new data together and fit the model once until convergence. Example: from sklearn.linear_model import SGDRegressorimport numpy as npnp.random.seed(0)X = np.linspace(-1, 1, num=50).reshape(-1, 1)Y = (X * 1.5 + 2).reshape(50,)modelFit = SGDRegressor(learning_rate="adaptive", eta0=0.01, random_state=0, verbose=1, shuffle=True, max_iter=2000, tol=1e-3, warm_start=True)modelPartialFit = SGDRegressor(learning_rate="adaptive", eta0=0.01, random_state=0, verbose=1, shuffle=True, max_iter=2000, tol=1e-3, warm_start=False)# first fit some datamodelFit.fit(X, Y)modelPartialFit.fit(X, Y)# for both: Convergence after 50 epochs, Norm: 1.46, NNZs: 1, Bias: 2.000027, T: 2500, Avg. loss: 0.000237print(modelFit.coef_, modelPartialFit.coef_) # for both: [1.46303288]# now fit new data (zeros)newX = XnewY = 0 * Y# fits only for 1 epoch, Norm: 1.23, NNZs: 1, Bias: 1.208630, T: 50, Avg. loss: 1.595492:modelPartialFit.partial_fit(newX, newY)# Convergence after 49 epochs, Norm: 0.04, NNZs: 1, Bias: 0.000077, T: 2450, Avg. loss: 0.000313:modelFit.fit(newX, newY)print(modelFit.coef_, modelPartialFit.coef_) # [0.04245779] vs. [1.22919864]newX = np.reshape([2], (-1, 1))print(modelFit.predict(newX), modelPartialFit.predict(newX)) # [0.08499296] vs. [3.66702685]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38052342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2423638/']}
jdg_372339
stackexchange
llm_judgeable_groundtruth_similarity
1087365
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: $x^x = 100$. I have no clue on how to solve this. If you guys have, please show me your solution as well. Now provide the response and nothing else.
$$\begin{align}x^x&=100\\ x\log x&=\log 100\\ e^{\log x}\log x&=\log 100\\ \log x&=W(\log 100)\\x&=e^{W(\log 100)}\\x&\approx 3.597\end{align}$$Where $W(x)$ is the ProductLog function, defined as the inverse of $[f(x)=xe^x]$ Explanations: 1. Problem 2.Logs 3.$ e^{\log x}=x$ 4.Definition of $W(x)$ 5.Taking $e^x$ 6.Numerical Solution
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1087365', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/204203/']}
jdg_372340